HeroWarsHelper

Automation of actions for the game Hero Wars

当前为 2025-01-26 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name HeroWarsHelper
  3. // @name:en HeroWarsHelper
  4. // @name:ru HeroWarsHelper
  5. // @namespace HeroWarsHelper
  6. // @version 2.315
  7. // @description Automation of actions for the game Hero Wars
  8. // @description:en Automation of actions for the game Hero Wars
  9. // @description:ru Автоматизация действий для игры Хроники Хаоса
  10. // @author ZingerY
  11. // @license Copyright ZingerY
  12. // @homepage https://zingery.ru/scripts/HeroWarsHelper.user.js
  13. // @icon https://zingery.ru/scripts/VaultBoyIco16.ico
  14. // @icon64 https://zingery.ru/scripts/VaultBoyIco64.png
  15. // @match https://www.hero-wars.com/*
  16. // @match https://apps-1701433570146040.apps.fbsbx.com/*
  17. // @run-at document-start
  18. // ==/UserScript==
  19.  
  20. (function() {
  21. /**
  22. * Start script
  23. *
  24. * Стартуем скрипт
  25. */
  26. console.log('%cStart ' + GM_info.script.name + ', v' + GM_info.script.version + ' by ' + GM_info.script.author, 'color: red');
  27. /**
  28. * Script info
  29. *
  30. * Информация о скрипте
  31. */
  32. this.scriptInfo = (({name, version, author, homepage, lastModified}, updateUrl) =>
  33. ({name, version, author, homepage, lastModified, updateUrl}))
  34. (GM_info.script, GM_info.scriptUpdateURL);
  35. this.GM_info = GM_info;
  36. /**
  37. * Information for completing daily quests
  38. *
  39. * Информация для выполнения ежендевных квестов
  40. */
  41. const questsInfo = {};
  42. /**
  43. * Is the game data loaded
  44. *
  45. * Загружены ли данные игры
  46. */
  47. let isLoadGame = false;
  48. /**
  49. * Headers of the last request
  50. *
  51. * Заголовки последнего запроса
  52. */
  53. let lastHeaders = {};
  54. /**
  55. * Information about sent gifts
  56. *
  57. * Информация об отправленных подарках
  58. */
  59. let freebieCheckInfo = null;
  60. /**
  61. * missionTimer
  62. *
  63. * missionTimer
  64. */
  65. let missionBattle = null;
  66. /**
  67. * User data
  68. *
  69. * Данные пользователя
  70. */
  71. let userInfo;
  72. this.isTimeBetweenNewDays = function () {
  73. if (userInfo.timeZone <= 3) {
  74. return false;
  75. }
  76. const nextDayTs = new Date(userInfo.nextDayTs * 1e3);
  77. const nextServerDayTs = new Date(userInfo.nextServerDayTs * 1e3);
  78. if (nextDayTs > nextServerDayTs) {
  79. nextDayTs.setDate(nextDayTs.getDate() - 1);
  80. }
  81. const now = Date.now();
  82. if (now > nextDayTs && now < nextServerDayTs) {
  83. return true;
  84. }
  85. return false;
  86. };
  87.  
  88. function getUserInfo() {
  89. return userInfo;
  90. }
  91. /**
  92. * Original methods for working with AJAX
  93. *
  94. * Оригинальные методы для работы с AJAX
  95. */
  96. const original = {
  97. open: XMLHttpRequest.prototype.open,
  98. send: XMLHttpRequest.prototype.send,
  99. setRequestHeader: XMLHttpRequest.prototype.setRequestHeader,
  100. SendWebSocket: WebSocket.prototype.send,
  101. fetch: fetch,
  102. };
  103.  
  104. // Sentry blocking
  105. // Блокировка наблюдателя
  106. this.fetch = function (url, options) {
  107. /**
  108. * Checking URL for blocking
  109. * Проверяем URL на блокировку
  110. */
  111. if (url.includes('sentry.io')) {
  112. console.log('%cFetch blocked', 'color: red');
  113. console.log(url, options);
  114. const body = {
  115. id: md5(Date.now()),
  116. };
  117. let info = {};
  118. try {
  119. info = JSON.parse(options.body);
  120. } catch (e) {}
  121. if (info.event_id) {
  122. body.id = info.event_id;
  123. }
  124. /**
  125. * Mock response for blocked URL
  126. *
  127. * Мокаем ответ для заблокированного URL
  128. */
  129. const mockResponse = new Response('Custom blocked response', {
  130. status: 200,
  131. headers: { 'Content-Type': 'application/json' },
  132. body,
  133. });
  134. return Promise.resolve(mockResponse);
  135. } else {
  136. /**
  137. * Call the original fetch function for all other URLs
  138. * Вызываем оригинальную функцию fetch для всех других URL
  139. */
  140. return original.fetch.apply(this, arguments);
  141. }
  142. };
  143.  
  144. /**
  145. * Decoder for converting byte data to JSON string
  146. *
  147. * Декодер для перобразования байтовых данных в JSON строку
  148. */
  149. const decoder = new TextDecoder("utf-8");
  150. /**
  151. * Stores a history of requests
  152. *
  153. * Хранит историю запросов
  154. */
  155. let requestHistory = {};
  156. /**
  157. * URL for API requests
  158. *
  159. * URL для запросов к API
  160. */
  161. let apiUrl = '';
  162.  
  163. /**
  164. * Connecting to the game code
  165. *
  166. * Подключение к коду игры
  167. */
  168. this.cheats = new hackGame();
  169. /**
  170. * The function of calculating the results of the battle
  171. *
  172. * Функция расчета результатов боя
  173. */
  174. this.BattleCalc = cheats.BattleCalc;
  175. /**
  176. * Sending a request available through the console
  177. *
  178. * Отправка запроса доступная через консоль
  179. */
  180. this.SendRequest = send;
  181. /**
  182. * Simple combat calculation available through the console
  183. *
  184. * Простой расчет боя доступный через консоль
  185. */
  186. this.Calc = function (data) {
  187. const type = getBattleType(data?.type);
  188. return new Promise((resolve, reject) => {
  189. try {
  190. BattleCalc(data, type, resolve);
  191. } catch (e) {
  192. reject(e);
  193. }
  194. })
  195. }
  196. /**
  197. * Short asynchronous request
  198. * Usage example (returns information about a character):
  199. * const userInfo = await Send('{"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}')
  200. *
  201. * Короткий асинхронный запрос
  202. * Пример использования (возвращает информацию о персонаже):
  203. * const userInfo = await Send('{"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}')
  204. */
  205. this.Send = function (json, pr) {
  206. return new Promise((resolve, reject) => {
  207. try {
  208. send(json, resolve, pr);
  209. } catch (e) {
  210. reject(e);
  211. }
  212. })
  213. }
  214.  
  215. this.xyz = (({ name, version, author }) => ({ name, version, author }))(GM_info.script);
  216. const i18nLangData = {
  217. /* English translation by BaBa */
  218. en: {
  219. /* Checkboxes */
  220. SKIP_FIGHTS: 'Skip battle',
  221. SKIP_FIGHTS_TITLE: 'Skip battle in Outland and the arena of the titans, auto-pass in the tower and campaign',
  222. ENDLESS_CARDS: 'Infinite cards',
  223. ENDLESS_CARDS_TITLE: 'Disable Divination Cards wasting',
  224. AUTO_EXPEDITION: 'Auto Expedition',
  225. AUTO_EXPEDITION_TITLE: 'Auto-sending expeditions',
  226. CANCEL_FIGHT: 'Cancel battle',
  227. CANCEL_FIGHT_TITLE: 'Ability to cancel manual combat on GW, CoW and Asgard',
  228. GIFTS: 'Gifts',
  229. GIFTS_TITLE: 'Collect gifts automatically',
  230. BATTLE_RECALCULATION: 'Battle recalculation',
  231. BATTLE_RECALCULATION_TITLE: 'Preliminary calculation of the battle',
  232. QUANTITY_CONTROL: 'Quantity control',
  233. QUANTITY_CONTROL_TITLE: 'Ability to specify the number of opened "lootboxes"',
  234. REPEAT_CAMPAIGN: 'Repeat missions',
  235. REPEAT_CAMPAIGN_TITLE: 'Auto-repeat battles in the campaign',
  236. DISABLE_DONAT: 'Disable donation',
  237. DISABLE_DONAT_TITLE: 'Removes all donation offers',
  238. DAILY_QUESTS: 'Quests',
  239. DAILY_QUESTS_TITLE: 'Complete daily quests',
  240. AUTO_QUIZ: 'AutoQuiz',
  241. AUTO_QUIZ_TITLE: 'Automatically receive correct answers to quiz questions',
  242. SECRET_WEALTH_CHECKBOX: 'Automatic purchase in the store "Secret Wealth" when entering the game',
  243. HIDE_SERVERS: 'Collapse servers',
  244. HIDE_SERVERS_TITLE: 'Hide unused servers',
  245. /* Input fields */
  246. HOW_MUCH_TITANITE: 'How much titanite to farm',
  247. COMBAT_SPEED: 'Combat Speed Multiplier',
  248. NUMBER_OF_TEST: 'Number of test fights',
  249. NUMBER_OF_AUTO_BATTLE: 'Number of auto-battle attempts',
  250. /* Buttons */
  251. RUN_SCRIPT: 'Run the',
  252. TO_DO_EVERYTHING: 'Do All',
  253. TO_DO_EVERYTHING_TITLE: 'Perform multiple actions of your choice',
  254. OUTLAND: 'Outland',
  255. OUTLAND_TITLE: 'Collect Outland',
  256. TITAN_ARENA: 'ToE',
  257. TITAN_ARENA_TITLE: 'Complete the titan arena',
  258. DUNGEON: 'Dungeon',
  259. DUNGEON_TITLE: 'Go through the dungeon',
  260. SEER: 'Seer',
  261. SEER_TITLE: 'Roll the Seer',
  262. TOWER: 'Tower',
  263. TOWER_TITLE: 'Pass the tower',
  264. EXPEDITIONS: 'Expeditions',
  265. EXPEDITIONS_TITLE: 'Sending and collecting expeditions',
  266. SYNC: 'Sync',
  267. SYNC_TITLE: 'Partial synchronization of game data without reloading the page',
  268. ARCHDEMON: 'Archdemon',
  269. FURNACE_OF_SOULS: 'Furnace of souls',
  270. ARCHDEMON_TITLE: 'Hitting kills and collecting rewards',
  271. ESTER_EGGS: 'Easter eggs',
  272. ESTER_EGGS_TITLE: 'Collect all Easter eggs or rewards',
  273. REWARDS: 'Rewards',
  274. REWARDS_TITLE: 'Collect all quest rewards',
  275. MAIL: 'Mail',
  276. MAIL_TITLE: 'Collect all mail, except letters with energy and charges of the portal',
  277. MINIONS: 'Minions',
  278. MINIONS_TITLE: 'Attack minions with saved packs',
  279. ADVENTURE: 'Adventure',
  280. ADVENTURE_TITLE: 'Passes the adventure along the specified route',
  281. STORM: 'Storm',
  282. STORM_TITLE: 'Passes the Storm along the specified route',
  283. SANCTUARY: 'Sanctuary',
  284. SANCTUARY_TITLE: 'Fast travel to Sanctuary',
  285. GUILD_WAR: 'Guild War',
  286. GUILD_WAR_TITLE: 'Fast travel to Guild War',
  287. SECRET_WEALTH: 'Secret Wealth',
  288. SECRET_WEALTH_TITLE: 'Buy something in the store "Secret Wealth"',
  289. /* Misc */
  290. BOTTOM_URLS:
  291. '<a href="https://t.me/+0oMwICyV1aQ1MDAy" target="_blank" title="Telegram"><svg width="20" height="20" style="margin:2px" viewBox="0 0 1e3 1e3" xmlns="http://www.w3.org/2000/svg"><defs><linearGradient id="a" x1="50%" x2="50%" y2="99.258%"><stop stop-color="#2AABEE" offset="0"/><stop stop-color="#229ED9" offset="1"/></linearGradient></defs><g fill-rule="evenodd"><circle cx="500" cy="500" r="500" fill="url(#a)"/><path d="m226.33 494.72c145.76-63.505 242.96-105.37 291.59-125.6 138.86-57.755 167.71-67.787 186.51-68.119 4.1362-0.072862 13.384 0.95221 19.375 5.8132 5.0584 4.1045 6.4501 9.6491 7.1161 13.541 0.666 3.8915 1.4953 12.756 0.83608 19.683-7.5246 79.062-40.084 270.92-56.648 359.47-7.0089 37.469-20.81 50.032-34.17 51.262-29.036 2.6719-51.085-19.189-79.207-37.624-44.007-28.847-68.867-46.804-111.58-74.953-49.366-32.531-17.364-50.411 10.769-79.631 7.3626-7.6471 135.3-124.01 137.77-134.57 0.30968-1.3202 0.59708-6.2414-2.3265-8.8399s-7.2385-1.7099-10.352-1.0032c-4.4137 1.0017-74.715 47.468-210.9 139.4-19.955 13.702-38.029 20.379-54.223 20.029-17.853-0.3857-52.194-10.094-77.723-18.393-31.313-10.178-56.199-15.56-54.032-32.846 1.1287-9.0037 13.528-18.212 37.197-27.624z" fill="#fff"/></g></svg></a><a href="https://www.patreon.com/HeroWarsUserScripts" target="_blank" title="Patreon"><svg width="20" height="20" viewBox="0 0 1080 1080" xmlns="http://www.w3.org/2000/svg"><g fill="#FFF" stroke="None"><path d="m1033 324.45c-0.19-137.9-107.59-250.92-233.6-291.7-156.48-50.64-362.86-43.3-512.28 27.2-181.1 85.46-237.99 272.66-240.11 459.36-1.74 153.5 13.58 557.79 241.62 560.67 169.44 2.15 194.67-216.18 273.07-321.33 55.78-74.81 127.6-95.94 216.01-117.82 151.95-37.61 255.51-157.53 255.29-316.38z"/></g></svg></a>',
  292. GIFTS_SENT: 'Gifts sent!',
  293. DO_YOU_WANT: 'Do you really want to do this?',
  294. BTN_RUN: 'Run',
  295. BTN_CANCEL: 'Cancel',
  296. BTN_OK: 'OK',
  297. MSG_HAVE_BEEN_DEFEATED: 'You have been defeated!',
  298. BTN_AUTO: 'Auto',
  299. MSG_YOU_APPLIED: 'You applied',
  300. MSG_DAMAGE: 'damage',
  301. MSG_CANCEL_AND_STAT: 'Auto (F5) and show statistic',
  302. MSG_REPEAT_MISSION: 'Repeat the mission?',
  303. BTN_REPEAT: 'Repeat',
  304. BTN_NO: 'No',
  305. MSG_SPECIFY_QUANT: 'Specify Quantity:',
  306. BTN_OPEN: 'Open',
  307. QUESTION_COPY: 'Question copied to clipboard',
  308. ANSWER_KNOWN: 'The answer is known',
  309. ANSWER_NOT_KNOWN: 'ATTENTION THE ANSWER IS NOT KNOWN',
  310. BEING_RECALC: 'The battle is being recalculated',
  311. THIS_TIME: 'This time',
  312. VICTORY: '<span style="color:green;">VICTORY</span>',
  313. DEFEAT: '<span style="color:red;">DEFEAT</span>',
  314. CHANCE_TO_WIN: 'Chance to win <span style="color: red;">based on pre-calculation</span>',
  315. OPEN_DOLLS: 'nesting dolls recursively',
  316. SENT_QUESTION: 'Question sent',
  317. SETTINGS: 'Settings',
  318. MSG_BAN_ATTENTION: '<p style="color:red;">Using this feature may result in a ban.</p> Continue?',
  319. BTN_YES_I_AGREE: 'Yes, I understand the risks!',
  320. BTN_NO_I_AM_AGAINST: 'No, I refuse it!',
  321. VALUES: 'Values',
  322. EXPEDITIONS_SENT: 'Expeditions:<br>Collected: {countGet}<br>Sent: {countSend}',
  323. EXPEDITIONS_NOTHING: 'Nothing to collect/send',
  324. EXPEDITIONS_NOTTIME: 'It is not time for expeditions',
  325. TITANIT: 'Titanit',
  326. COMPLETED: 'completed',
  327. FLOOR: 'Floor',
  328. LEVEL: 'Level',
  329. BATTLES: 'battles',
  330. EVENT: 'Event',
  331. NOT_AVAILABLE: 'not available',
  332. NO_HEROES: 'No heroes',
  333. DAMAGE_AMOUNT: 'Damage amount',
  334. NOTHING_TO_COLLECT: 'Nothing to collect',
  335. COLLECTED: 'Collected',
  336. REWARD: 'rewards',
  337. REMAINING_ATTEMPTS: 'Remaining attempts',
  338. BATTLES_CANCELED: 'Battles canceled',
  339. MINION_RAID: 'Minion Raid',
  340. STOPPED: 'Stopped',
  341. REPETITIONS: 'Repetitions',
  342. MISSIONS_PASSED: 'Missions passed',
  343. STOP: 'stop',
  344. TOTAL_OPEN: 'Total open',
  345. OPEN: 'Open',
  346. ROUND_STAT: 'Damage statistics for ',
  347. BATTLE: 'battles',
  348. MINIMUM: 'Minimum',
  349. MAXIMUM: 'Maximum',
  350. AVERAGE: 'Average',
  351. NOT_THIS_TIME: 'Not this time',
  352. RETRY_LIMIT_EXCEEDED: 'Retry limit exceeded',
  353. SUCCESS: 'Success',
  354. RECEIVED: 'Received',
  355. LETTERS: 'letters',
  356. PORTALS: 'portals',
  357. ATTEMPTS: 'attempts',
  358. /* Quests */
  359. QUEST_10001: 'Upgrade the skills of heroes 3 times',
  360. QUEST_10002: 'Complete 10 missions',
  361. QUEST_10003: 'Complete 3 heroic missions',
  362. QUEST_10004: 'Fight 3 times in the Arena or Grand Arena',
  363. QUEST_10006: 'Use the exchange of emeralds 1 time',
  364. QUEST_10007: 'Perform 1 summon in the Solu Atrium',
  365. QUEST_10016: 'Send gifts to guildmates',
  366. QUEST_10018: 'Use an experience potion',
  367. QUEST_10019: 'Open 1 chest in the Tower',
  368. QUEST_10020: 'Open 3 chests in Outland',
  369. QUEST_10021: 'Collect 75 Titanite in the Guild Dungeon',
  370. QUEST_10021: 'Collect 150 Titanite in the Guild Dungeon',
  371. QUEST_10023: 'Upgrade Gift of the Elements by 1 level',
  372. QUEST_10024: 'Level up any artifact once',
  373. QUEST_10025: 'Start Expedition 1',
  374. QUEST_10026: 'Start 4 Expeditions',
  375. QUEST_10027: 'Win 1 battle of the Tournament of Elements',
  376. QUEST_10028: 'Level up any titan artifact',
  377. QUEST_10029: 'Unlock the Orb of Titan Artifacts',
  378. QUEST_10030: 'Upgrade any Skin of any hero 1 time',
  379. QUEST_10031: 'Win 6 battles of the Tournament of Elements',
  380. QUEST_10043: 'Start or Join an Adventure',
  381. QUEST_10044: 'Use Summon Pets 1 time',
  382. QUEST_10046: 'Open 3 chests in Adventure',
  383. QUEST_10047: 'Get 150 Guild Activity Points',
  384. NOTHING_TO_DO: 'Nothing to do',
  385. YOU_CAN_COMPLETE: 'You can complete quests',
  386. BTN_DO_IT: 'Do it',
  387. NOT_QUEST_COMPLETED: 'Not a single quest completed',
  388. COMPLETED_QUESTS: 'Completed quests',
  389. /* everything button */
  390. ASSEMBLE_OUTLAND: 'Assemble Outland',
  391. PASS_THE_TOWER: 'Pass the tower',
  392. CHECK_EXPEDITIONS: 'Check Expeditions',
  393. COMPLETE_TOE: 'Complete ToE',
  394. COMPLETE_DUNGEON: 'Complete the dungeon',
  395. COLLECT_MAIL: 'Collect mail',
  396. COLLECT_MISC: 'Collect some bullshit',
  397. COLLECT_MISC_TITLE: 'Collect Easter Eggs, Skin Gems, Keys, Arena Coins and Soul Crystal',
  398. COLLECT_QUEST_REWARDS: 'Collect quest rewards',
  399. MAKE_A_SYNC: 'Make a sync',
  400.  
  401. RUN_FUNCTION: 'Run the following functions?',
  402. BTN_GO: 'Go!',
  403. PERFORMED: 'Performed',
  404. DONE: 'Done',
  405. ERRORS_OCCURRES: 'Errors occurred while executing',
  406. COPY_ERROR: 'Copy error information to clipboard',
  407. BTN_YES: 'Yes',
  408. ALL_TASK_COMPLETED: 'All tasks completed',
  409.  
  410. UNKNOWN: 'unknown',
  411. ENTER_THE_PATH: 'Enter the path of adventure using commas or dashes',
  412. START_ADVENTURE: 'Start your adventure along this path!',
  413. INCORRECT_WAY: 'Incorrect path in adventure: {from} -> {to}',
  414. BTN_CANCELED: 'Canceled',
  415. MUST_TWO_POINTS: 'The path must contain at least 2 points.',
  416. MUST_ONLY_NUMBERS: 'The path must contain only numbers and commas',
  417. NOT_ON_AN_ADVENTURE: 'You are not on an adventure',
  418. YOU_IN_NOT_ON_THE_WAY: 'Your location is not on the way',
  419. ATTEMPTS_NOT_ENOUGH: 'Your attempts are not enough to complete the path, continue?',
  420. YES_CONTINUE: 'Yes, continue!',
  421. NOT_ENOUGH_AP: 'Not enough action points',
  422. ATTEMPTS_ARE_OVER: 'The attempts are over',
  423. MOVES: 'Moves',
  424. BUFF_GET_ERROR: 'Buff getting error',
  425. BATTLE_END_ERROR: 'Battle end error',
  426. AUTOBOT: 'Autobot',
  427. FAILED_TO_WIN_AUTO: 'Failed to win the auto battle',
  428. ERROR_OF_THE_BATTLE_COPY: 'An error occurred during the passage of the battle<br>Copy the error to the clipboard?',
  429. ERROR_DURING_THE_BATTLE: 'Error during the battle',
  430. NO_CHANCE_WIN: 'No chance of winning this fight: 0/',
  431. LOST_HEROES: 'You have won, but you have lost one or several heroes',
  432. VICTORY_IMPOSSIBLE: 'Is victory impossible, should we focus on the result?',
  433. FIND_COEFF: 'Find the coefficient greater than',
  434. BTN_PASS: 'PASS',
  435. BRAWLS: 'Brawls',
  436. BRAWLS_TITLE: 'Activates the ability to auto-brawl',
  437. START_AUTO_BRAWLS: 'Start Auto Brawls?',
  438. LOSSES: 'Losses',
  439. WINS: 'Wins',
  440. FIGHTS: 'Fights',
  441. STAGE: 'Stage',
  442. DONT_HAVE_LIVES: "You don't have lives",
  443. LIVES: 'Lives',
  444. SECRET_WEALTH_ALREADY: 'Item for Pet Potions already purchased',
  445. SECRET_WEALTH_NOT_ENOUGH: 'Not Enough Pet Potion, You Have {available}, Need {need}',
  446. SECRET_WEALTH_UPGRADE_NEW_PET: 'After purchasing the Pet Potion, it will not be enough to upgrade a new pet',
  447. SECRET_WEALTH_PURCHASED: 'Purchased {count} {name}',
  448. SECRET_WEALTH_CANCELED: 'Secret Wealth: Purchase Canceled',
  449. SECRET_WEALTH_BUY: 'You have {available} Pet Potion.<br>Do you want to buy {countBuy} {name} for {price} Pet Potion?',
  450. DAILY_BONUS: 'Daily bonus',
  451. DO_DAILY_QUESTS: 'Do daily quests',
  452. ACTIONS: 'Actions',
  453. ACTIONS_TITLE: 'Dialog box with various actions',
  454. OTHERS: 'Others',
  455. OTHERS_TITLE: 'Others',
  456. CHOOSE_ACTION: 'Choose an action',
  457. OPEN_LOOTBOX: 'You have {lootBox} boxes, should we open them?',
  458. STAMINA: 'Energy',
  459. BOXES_OVER: 'The boxes are over',
  460. NO_BOXES: 'No boxes',
  461. NO_MORE_ACTIVITY: 'No more activity for items today',
  462. EXCHANGE_ITEMS: 'Exchange items for activity points (max {maxActive})?',
  463. GET_ACTIVITY: 'Get Activity',
  464. NOT_ENOUGH_ITEMS: 'Not enough items',
  465. ACTIVITY_RECEIVED: 'Activity received',
  466. NO_PURCHASABLE_HERO_SOULS: 'No purchasable Hero Souls',
  467. PURCHASED_HERO_SOULS: 'Purchased {countHeroSouls} Hero Souls',
  468. NOT_ENOUGH_EMERALDS_540: 'Not enough emeralds, you need {imgEmerald}540 you have {imgEmerald}{currentStarMoney}',
  469. BUY_OUTLAND_BTN: 'Buy {count} chests {imgEmerald}{countEmerald}',
  470. CHESTS_NOT_AVAILABLE: 'Chests not available',
  471. OUTLAND_CHESTS_RECEIVED: 'Outland chests received',
  472. RAID_NOT_AVAILABLE: 'The raid is not available or there are no spheres',
  473. RAID_ADVENTURE: 'Raid {adventureId} adventure!',
  474. SOMETHING_WENT_WRONG: 'Something went wrong',
  475. ADVENTURE_COMPLETED: 'Adventure {adventureId} completed {times} times',
  476. CLAN_STAT_COPY: 'Clan statistics copied to clipboard',
  477. GET_ENERGY: 'Get Energy',
  478. GET_ENERGY_TITLE: 'Opens platinum boxes one at a time until you get 250 energy',
  479. ITEM_EXCHANGE: 'Item Exchange',
  480. ITEM_EXCHANGE_TITLE: 'Exchanges items for the specified amount of activity',
  481. BUY_SOULS: 'Buy souls',
  482. BUY_SOULS_TITLE: 'Buy hero souls from all available shops',
  483. BUY_OUTLAND: 'Buy Outland',
  484. BUY_OUTLAND_TITLE: 'Buy 9 chests in Outland for 540 emeralds',
  485. RAID: 'Raid',
  486. AUTO_RAID_ADVENTURE: 'Raid adventure',
  487. AUTO_RAID_ADVENTURE_TITLE: 'Raid adventure set number of times',
  488. CLAN_STAT: 'Clan statistics',
  489. CLAN_STAT_TITLE: 'Copies clan statistics to the clipboard',
  490. BTN_AUTO_F5: 'Auto (F5)',
  491. BOSS_DAMAGE: 'Boss Damage: ',
  492. NOTHING_BUY: 'Nothing to buy',
  493. LOTS_BOUGHT: '{countBuy} lots bought for gold',
  494. BUY_FOR_GOLD: 'Buy for gold',
  495. BUY_FOR_GOLD_TITLE: 'Buy items for gold in the Town Shop and in the Pet Soul Stone Shop',
  496. REWARDS_AND_MAIL: 'Rewards and Mail',
  497. REWARDS_AND_MAIL_TITLE: 'Collects rewards and mail',
  498. COLLECT_REWARDS_AND_MAIL: 'Collected {countQuests} rewards and {countMail} letters',
  499. TIMER_ALREADY: 'Timer already started {time}',
  500. NO_ATTEMPTS_TIMER_START: 'No attempts, timer started {time}',
  501. EPIC_BRAWL_RESULT: 'Wins: {wins}/{attempts}, Coins: {coins}, Streak: {progress}/{nextStage} [Close]{end}',
  502. ATTEMPT_ENDED: '<br>Attempts ended, timer started {time}',
  503. EPIC_BRAWL: 'Cosmic Battle',
  504. EPIC_BRAWL_TITLE: 'Spends attempts in the Cosmic Battle',
  505. RELOAD_GAME: 'Reload game',
  506. TIMER: 'Timer:',
  507. SHOW_ERRORS: 'Show errors',
  508. SHOW_ERRORS_TITLE: 'Show server request errors',
  509. ERROR_MSG: 'Error: {name}<br>{description}',
  510. EVENT_AUTO_BOSS:
  511. 'Maximum number of battles for calculation:</br>{length} ∗ {countTestBattle} = {maxCalcBattle}</br>If you have a weak computer, it may take a long time for this, click on the cross to cancel.</br>Should I search for the best pack from all or the first suitable one?',
  512. BEST_SLOW: 'Best (slower)',
  513. FIRST_FAST: 'First (faster)',
  514. FREEZE_INTERFACE: 'Calculating... <br>The interface may freeze.',
  515. ERROR_F12: 'Error, details in the console (F12)',
  516. FAILED_FIND_WIN_PACK: 'Failed to find a winning pack',
  517. BEST_PACK: 'Best pack:',
  518. BOSS_HAS_BEEN_DEF: 'Boss {bossLvl} has been defeated.',
  519. NOT_ENOUGH_ATTEMPTS_BOSS: 'Not enough attempts to defeat boss {bossLvl}, retry?',
  520. BOSS_VICTORY_IMPOSSIBLE:
  521. 'Based on the recalculation of {battles} battles, victory has not been achieved. Would you like to continue the search for a winning battle in real battles?',
  522. BOSS_HAS_BEEN_DEF_TEXT:
  523. 'Boss {bossLvl} defeated in<br>{countBattle}/{countMaxBattle} attempts{winTimer}<br>(Please synchronize or restart the game to update the data)',
  524. MAP: 'Map: ',
  525. PLAYER_POS: 'Player positions:',
  526. NY_GIFTS: 'Gifts',
  527. NY_GIFTS_TITLE: "Open all New Year's gifts",
  528. NY_NO_GIFTS: 'No gifts not received',
  529. NY_GIFTS_COLLECTED: '{count} gifts collected',
  530. CHANGE_MAP: 'Island map',
  531. CHANGE_MAP_TITLE: 'Change island map',
  532. SELECT_ISLAND_MAP: 'Select an island map:',
  533. MAP_NUM: 'Map {num}',
  534. SECRET_WEALTH_SHOP: 'Secret Wealth {name}: ',
  535. SHOPS: 'Shops',
  536. SHOPS_DEFAULT: 'Default',
  537. SHOPS_DEFAULT_TITLE: 'Default stores',
  538. SHOPS_LIST: 'Shops {number}',
  539. SHOPS_LIST_TITLE: 'List of shops {number}',
  540. SHOPS_WARNING:
  541. 'Stores<br><span style="color:red">If you buy brawl store coins for emeralds, you must use them immediately, otherwise they will disappear after restarting the game!</span>',
  542. MINIONS_WARNING: 'The hero packs for attacking minions are incomplete, should I continue?',
  543. FAST_SEASON: 'Fast season',
  544. FAST_SEASON_TITLE: 'Skip the map selection screen in a season',
  545. SET_NUMBER_LEVELS: 'Specify the number of levels:',
  546. POSSIBLE_IMPROVE_LEVELS: 'It is possible to improve only {count} levels.<br>Improving?',
  547. NOT_ENOUGH_RESOURECES: 'Not enough resources',
  548. IMPROVED_LEVELS: 'Improved levels: {count}',
  549. ARTIFACTS_UPGRADE: 'Artifacts Upgrade',
  550. ARTIFACTS_UPGRADE_TITLE: 'Upgrades the specified amount of the cheapest hero artifacts',
  551. SKINS_UPGRADE: 'Skins Upgrade',
  552. SKINS_UPGRADE_TITLE: 'Upgrades the specified amount of the cheapest hero skins',
  553. HINT: '<br>Hint: ',
  554. PICTURE: '<br>Picture: ',
  555. ANSWER: '<br>Answer: ',
  556. NO_HEROES_PACK: 'Fight at least one battle to save the attacking team',
  557. BRAWL_AUTO_PACK: 'Automatic selection of packs',
  558. BRAWL_AUTO_PACK_NOT_CUR_HERO: 'Automatic pack selection is not suitable for the current hero',
  559. BRAWL_DAILY_TASK_COMPLETED: 'Daily task completed, continue attacking?',
  560. CALC_STAT: 'Calculate statistics',
  561. ELEMENT_TOURNAMENT_REWARD: 'Unclaimed bonus for Elemental Tournament',
  562. BTN_TRY_FIX_IT: 'Fix it',
  563. BTN_TRY_FIX_IT_TITLE: 'Enable auto attack combat correction',
  564. DAMAGE_FIXED: 'Damage fixed from {lastDamage} to {maxDamage}!',
  565. DAMAGE_NO_FIXED: 'Failed to fix damage: {lastDamage}',
  566. LETS_FIX: "Let's fix",
  567. COUNT_FIXED: 'For {count} attempts',
  568. DEFEAT_TURN_TIMER: 'Defeat! Turn on the timer to complete the mission?',
  569. SEASON_REWARD: 'Season Rewards',
  570. SEASON_REWARD_TITLE: 'Collects available free rewards from all current seasons',
  571. SEASON_REWARD_COLLECTED: 'Collected {count} season rewards',
  572. SELL_HERO_SOULS: 'Sell ​​souls',
  573. SELL_HERO_SOULS_TITLE: 'Exchanges all absolute star hero souls for gold',
  574. GOLD_RECEIVED: 'Gold received: {gold}',
  575. OPEN_ALL_EQUIP_BOXES: 'Open all Equipment Fragment Box?',
  576. SERVER_NOT_ACCEPT: 'The server did not accept the result',
  577. INVASION_BOSS_BUFF: 'For {bossLvl} boss need buff {needBuff} you have {haveBuff}}',
  578. },
  579. ru: {
  580. /* Чекбоксы */
  581. SKIP_FIGHTS: 'Пропуск боев',
  582. SKIP_FIGHTS_TITLE: 'Пропуск боев в запределье и арене титанов, автопропуск в башне и кампании',
  583. ENDLESS_CARDS: 'Бесконечные карты',
  584. ENDLESS_CARDS_TITLE: 'Отключить трату карт предсказаний',
  585. AUTO_EXPEDITION: 'АвтоЭкспедиции',
  586. AUTO_EXPEDITION_TITLE: 'Автоотправка экспедиций',
  587. CANCEL_FIGHT: 'Отмена боя',
  588. CANCEL_FIGHT_TITLE: 'Возможность отмены ручного боя на ВГ, СМ и в Асгарде',
  589. GIFTS: 'Подарки',
  590. GIFTS_TITLE: 'Собирать подарки автоматически',
  591. BATTLE_RECALCULATION: 'Прерасчет боя',
  592. BATTLE_RECALCULATION_TITLE: 'Предварительный расчет боя',
  593. QUANTITY_CONTROL: 'Контроль кол-ва',
  594. QUANTITY_CONTROL_TITLE: 'Возможность указывать количество открываемых "лутбоксов"',
  595. REPEAT_CAMPAIGN: 'Повтор в кампании',
  596. REPEAT_CAMPAIGN_TITLE: 'Автоповтор боев в кампании',
  597. DISABLE_DONAT: 'Отключить донат',
  598. DISABLE_DONAT_TITLE: 'Убирает все предложения доната',
  599. DAILY_QUESTS: 'Квесты',
  600. DAILY_QUESTS_TITLE: 'Выполнять ежедневные квесты',
  601. AUTO_QUIZ: 'АвтоВикторина',
  602. AUTO_QUIZ_TITLE: 'Автоматическое получение правильных ответов на вопросы викторины',
  603. SECRET_WEALTH_CHECKBOX: 'Автоматическая покупка в магазине "Тайное Богатство" при заходе в игру',
  604. HIDE_SERVERS: 'Свернуть сервера',
  605. HIDE_SERVERS_TITLE: 'Скрывать неиспользуемые сервера',
  606. /* Поля ввода */
  607. HOW_MUCH_TITANITE: 'Сколько фармим титанита',
  608. COMBAT_SPEED: 'Множитель ускорения боя',
  609. NUMBER_OF_TEST: 'Количество тестовых боев',
  610. NUMBER_OF_AUTO_BATTLE: 'Количество попыток автобоев',
  611. /* Кнопки */
  612. RUN_SCRIPT: 'Запустить скрипт',
  613. TO_DO_EVERYTHING: 'Сделать все',
  614. TO_DO_EVERYTHING_TITLE: 'Выполнить несколько действий',
  615. OUTLAND: 'Запределье',
  616. OUTLAND_TITLE: 'Собрать Запределье',
  617. TITAN_ARENA: 'Турнир Стихий',
  618. TITAN_ARENA_TITLE: 'Автопрохождение Турнира Стихий',
  619. DUNGEON: 'Подземелье',
  620. DUNGEON_TITLE: 'Автопрохождение подземелья',
  621. SEER: 'Провидец',
  622. SEER_TITLE: 'Покрутить Провидца',
  623. TOWER: 'Башня',
  624. TOWER_TITLE: 'Автопрохождение башни',
  625. EXPEDITIONS: 'Экспедиции',
  626. EXPEDITIONS_TITLE: 'Отправка и сбор экспедиций',
  627. SYNC: 'Синхронизация',
  628. SYNC_TITLE: 'Частичная синхронизация данных игры без перезагрузки сатраницы',
  629. ARCHDEMON: 'Архидемон',
  630. FURNACE_OF_SOULS: 'Горнило душ',
  631. ARCHDEMON_TITLE: 'Набивает килы и собирает награду',
  632. ESTER_EGGS: 'Пасхалки',
  633. ESTER_EGGS_TITLE: 'Собрать все пасхалки или награды',
  634. REWARDS: 'Награды',
  635. REWARDS_TITLE: 'Собрать все награды за задания',
  636. MAIL: 'Почта',
  637. MAIL_TITLE: 'Собрать всю почту, кроме писем с энергией и зарядами портала',
  638. MINIONS: 'Прислужники',
  639. MINIONS_TITLE: 'Атакует прислужников сохраннеными пачками',
  640. ADVENTURE: 'Приключение',
  641. ADVENTURE_TITLE: 'Проходит приключение по указанному маршруту',
  642. STORM: 'Буря',
  643. STORM_TITLE: 'Проходит бурю по указанному маршруту',
  644. SANCTUARY: 'Святилище',
  645. SANCTUARY_TITLE: 'Быстрый переход к Святилищу',
  646. GUILD_WAR: 'Война гильдий',
  647. GUILD_WAR_TITLE: 'Быстрый переход к Войне гильдий',
  648. SECRET_WEALTH: 'Тайное богатство',
  649. SECRET_WEALTH_TITLE: 'Купить что-то в магазине "Тайное богатство"',
  650. /* Разное */
  651. BOTTOM_URLS:
  652. '<a href="https://t.me/+q6gAGCRpwyFkNTYy" target="_blank" title="Telegram"><svg width="20" height="20" style="margin:2px" viewBox="0 0 1e3 1e3" xmlns="http://www.w3.org/2000/svg"><defs><linearGradient id="a" x1="50%" x2="50%" y2="99.258%"><stop stop-color="#2AABEE" offset="0"/><stop stop-color="#229ED9" offset="1"/></linearGradient></defs><g fill-rule="evenodd"><circle cx="500" cy="500" r="500" fill="url(#a)"/><path d="m226.33 494.72c145.76-63.505 242.96-105.37 291.59-125.6 138.86-57.755 167.71-67.787 186.51-68.119 4.1362-0.072862 13.384 0.95221 19.375 5.8132 5.0584 4.1045 6.4501 9.6491 7.1161 13.541 0.666 3.8915 1.4953 12.756 0.83608 19.683-7.5246 79.062-40.084 270.92-56.648 359.47-7.0089 37.469-20.81 50.032-34.17 51.262-29.036 2.6719-51.085-19.189-79.207-37.624-44.007-28.847-68.867-46.804-111.58-74.953-49.366-32.531-17.364-50.411 10.769-79.631 7.3626-7.6471 135.3-124.01 137.77-134.57 0.30968-1.3202 0.59708-6.2414-2.3265-8.8399s-7.2385-1.7099-10.352-1.0032c-4.4137 1.0017-74.715 47.468-210.9 139.4-19.955 13.702-38.029 20.379-54.223 20.029-17.853-0.3857-52.194-10.094-77.723-18.393-31.313-10.178-56.199-15.56-54.032-32.846 1.1287-9.0037 13.528-18.212 37.197-27.624z" fill="#fff"/></g></svg></a><a href="https://vk.com/invite/YNPxKGX" target="_blank" title="Вконтакте"><svg width="20" height="20" style="margin:2px" viewBox="0 0 101 100" xmlns="http://www.w3.org/2000/svg"><g clip-path="url(#a)"><path d="M0.5 48C0.5 25.3726 0.5 14.0589 7.52944 7.02944C14.5589 0 25.8726 0 48.5 0H52.5C75.1274 0 86.4411 0 93.4706 7.02944C100.5 14.0589 100.5 25.3726 100.5 48V52C100.5 74.6274 100.5 85.9411 93.4706 92.9706C86.4411 100 75.1274 100 52.5 100H48.5C25.8726 100 14.5589 100 7.52944 92.9706C0.5 85.9411 0.5 74.6274 0.5 52V48Z" fill="#07f"/><path d="m53.708 72.042c-22.792 0-35.792-15.625-36.333-41.625h11.417c0.375 19.083 8.7915 27.167 15.458 28.833v-28.833h10.75v16.458c6.5833-0.7083 13.499-8.2082 15.832-16.458h10.75c-1.7917 10.167-9.2917 17.667-14.625 20.75 5.3333 2.5 13.875 9.0417 17.125 20.875h-11.834c-2.5417-7.9167-8.8745-14.042-17.25-14.875v14.875h-1.2919z" fill="#fff"/></g><defs><clipPath id="a"><rect transform="translate(.5)" width="100" height="100" fill="#fff"/></clipPath></defs></svg></a>',
  653. GIFTS_SENT: 'Подарки отправлены!',
  654. DO_YOU_WANT: 'Вы действительно хотите это сделать?',
  655. BTN_RUN: 'Запускай',
  656. BTN_CANCEL: 'Отмена',
  657. BTN_OK: 'Ок',
  658. MSG_HAVE_BEEN_DEFEATED: 'Вы потерпели поражение!',
  659. BTN_AUTO: 'Авто',
  660. MSG_YOU_APPLIED: 'Вы нанесли',
  661. MSG_DAMAGE: 'урона',
  662. MSG_CANCEL_AND_STAT: 'Авто (F5) и показать Статистику',
  663. MSG_REPEAT_MISSION: 'Повторить миссию?',
  664. BTN_REPEAT: 'Повторить',
  665. BTN_NO: 'Нет',
  666. MSG_SPECIFY_QUANT: 'Указать количество:',
  667. BTN_OPEN: 'Открыть',
  668. QUESTION_COPY: 'Вопрос скопирован в буфер обмена',
  669. ANSWER_KNOWN: 'Ответ известен',
  670. ANSWER_NOT_KNOWN: 'ВНИМАНИЕ ОТВЕТ НЕ ИЗВЕСТЕН',
  671. BEING_RECALC: 'Идет прерасчет боя',
  672. THIS_TIME: 'На этот раз',
  673. VICTORY: '<span style="color:green;">ПОБЕДА</span>',
  674. DEFEAT: '<span style="color:red;">ПОРАЖЕНИЕ</span>',
  675. CHANCE_TO_WIN: 'Шансы на победу <span style="color:red;">на основе прерасчета</span>',
  676. OPEN_DOLLS: 'матрешек рекурсивно',
  677. SENT_QUESTION: 'Вопрос отправлен',
  678. SETTINGS: 'Настройки',
  679. MSG_BAN_ATTENTION: '<p style="color:red;">Использование этой функции может привести к бану.</p> Продолжить?',
  680. BTN_YES_I_AGREE: 'Да, я беру на себя все риски!',
  681. BTN_NO_I_AM_AGAINST: 'Нет, я отказываюсь от этого!',
  682. VALUES: 'Значения',
  683. EXPEDITIONS_SENT: 'Экспедиции:<br>Собрано: {countGet}<br>Отправлено: {countSend}',
  684. EXPEDITIONS_NOTHING: 'Нечего собирать/отправлять',
  685. EXPEDITIONS_NOTTIME: 'Не время для экспедиций',
  686. TITANIT: 'Титанит',
  687. COMPLETED: 'завершено',
  688. FLOOR: 'Этаж',
  689. LEVEL: 'Уровень',
  690. BATTLES: 'бои',
  691. EVENT: 'Эвент',
  692. NOT_AVAILABLE: 'недоступен',
  693. NO_HEROES: 'Нет героев',
  694. DAMAGE_AMOUNT: 'Количество урона',
  695. NOTHING_TO_COLLECT: 'Нечего собирать',
  696. COLLECTED: 'Собрано',
  697. REWARD: 'наград',
  698. REMAINING_ATTEMPTS: 'Осталось попыток',
  699. BATTLES_CANCELED: 'Битв отменено',
  700. MINION_RAID: 'Рейд прислужников',
  701. STOPPED: 'Остановлено',
  702. REPETITIONS: 'Повторений',
  703. MISSIONS_PASSED: 'Миссий пройдено',
  704. STOP: 'остановить',
  705. TOTAL_OPEN: 'Всего открыто',
  706. OPEN: 'Открыто',
  707. ROUND_STAT: 'Статистика урона за',
  708. BATTLE: 'боев',
  709. MINIMUM: 'Минимальный',
  710. MAXIMUM: 'Максимальный',
  711. AVERAGE: 'Средний',
  712. NOT_THIS_TIME: 'Не в этот раз',
  713. RETRY_LIMIT_EXCEEDED: 'Превышен лимит попыток',
  714. SUCCESS: 'Успех',
  715. RECEIVED: 'Получено',
  716. LETTERS: 'писем',
  717. PORTALS: 'порталов',
  718. ATTEMPTS: 'попыток',
  719. QUEST_10001: 'Улучши умения героев 3 раза',
  720. QUEST_10002: 'Пройди 10 миссий',
  721. QUEST_10003: 'Пройди 3 героические миссии',
  722. QUEST_10004: 'Сразись 3 раза на Арене или Гранд Арене',
  723. QUEST_10006: 'Используй обмен изумрудов 1 раз',
  724. QUEST_10007: 'Соверши 1 призыв в Атриуме Душ',
  725. QUEST_10016: 'Отправь подарки согильдийцам',
  726. QUEST_10018: 'Используй зелье опыта',
  727. QUEST_10019: 'Открой 1 сундук в Башне',
  728. QUEST_10020: 'Открой 3 сундука в Запределье',
  729. QUEST_10021: 'Собери 75 Титанита в Подземелье Гильдии',
  730. QUEST_10021: 'Собери 150 Титанита в Подземелье Гильдии',
  731. QUEST_10023: 'Прокачай Дар Стихий на 1 уровень',
  732. QUEST_10024: 'Повысь уровень любого артефакта один раз',
  733. QUEST_10025: 'Начни 1 Экспедицию',
  734. QUEST_10026: 'Начни 4 Экспедиции',
  735. QUEST_10027: 'Победи в 1 бою Турнира Стихий',
  736. QUEST_10028: 'Повысь уровень любого артефакта титанов',
  737. QUEST_10029: 'Открой сферу артефактов титанов',
  738. QUEST_10030: 'Улучши облик любого героя 1 раз',
  739. QUEST_10031: 'Победи в 6 боях Турнира Стихий',
  740. QUEST_10043: 'Начни или присоеденись к Приключению',
  741. QUEST_10044: 'Воспользуйся призывом питомцев 1 раз',
  742. QUEST_10046: 'Открой 3 сундука в Приключениях',
  743. QUEST_10047: 'Набери 150 очков активности в Гильдии',
  744. NOTHING_TO_DO: 'Нечего выполнять',
  745. YOU_CAN_COMPLETE: 'Можно выполнить квесты',
  746. BTN_DO_IT: 'Выполняй',
  747. NOT_QUEST_COMPLETED: 'Ни одного квеста не выполенно',
  748. COMPLETED_QUESTS: 'Выполнено квестов',
  749. /* everything button */
  750. ASSEMBLE_OUTLAND: 'Собрать Запределье',
  751. PASS_THE_TOWER: 'Пройти башню',
  752. CHECK_EXPEDITIONS: 'Проверить экспедиции',
  753. COMPLETE_TOE: 'Пройти Турнир Стихий',
  754. COMPLETE_DUNGEON: 'Пройти подземелье',
  755. COLLECT_MAIL: 'Собрать почту',
  756. COLLECT_MISC: 'Собрать всякую херню',
  757. COLLECT_MISC_TITLE: 'Собрать пасхалки, камни облика, ключи, монеты арены и Хрусталь души',
  758. COLLECT_QUEST_REWARDS: 'Собрать награды за квесты',
  759. MAKE_A_SYNC: 'Сделать синхронизацию',
  760.  
  761. RUN_FUNCTION: 'Выполнить следующие функции?',
  762. BTN_GO: 'Погнали!',
  763. PERFORMED: 'Выполняется',
  764. DONE: 'Выполнено',
  765. ERRORS_OCCURRES: 'Призошли ошибки при выполнении',
  766. COPY_ERROR: 'Скопировать в буфер информацию об ошибке',
  767. BTN_YES: 'Да',
  768. ALL_TASK_COMPLETED: 'Все задачи выполнены',
  769.  
  770. UNKNOWN: 'Неизвестно',
  771. ENTER_THE_PATH: 'Введите путь приключения через запятые или дефисы',
  772. START_ADVENTURE: 'Начать приключение по этому пути!',
  773. INCORRECT_WAY: 'Неверный путь в приключении: {from} -> {to}',
  774. BTN_CANCELED: 'Отменено',
  775. MUST_TWO_POINTS: 'Путь должен состоять минимум из 2х точек',
  776. MUST_ONLY_NUMBERS: 'Путь должен содержать только цифры и запятые',
  777. NOT_ON_AN_ADVENTURE: 'Вы не в приключении',
  778. YOU_IN_NOT_ON_THE_WAY: 'Указанный путь должен включать точку вашего положения',
  779. ATTEMPTS_NOT_ENOUGH: 'Ваших попыток не достаточно для завершения пути, продолжить?',
  780. YES_CONTINUE: 'Да, продолжай!',
  781. NOT_ENOUGH_AP: 'Попыток не достаточно',
  782. ATTEMPTS_ARE_OVER: 'Попытки закончились',
  783. MOVES: 'Ходы',
  784. BUFF_GET_ERROR: 'Ошибка при получении бафа',
  785. BATTLE_END_ERROR: 'Ошибка завершения боя',
  786. AUTOBOT: 'АвтоБой',
  787. FAILED_TO_WIN_AUTO: 'Не удалось победить в автобою',
  788. ERROR_OF_THE_BATTLE_COPY: 'Призошли ошибка в процессе прохождения боя<br>Скопировать ошибку в буфер обмена?',
  789. ERROR_DURING_THE_BATTLE: 'Ошибка в процессе прохождения боя',
  790. NO_CHANCE_WIN: 'Нет шансов победить в этом бою: 0/',
  791. LOST_HEROES: 'Вы победили, но потеряли одного или несколько героев!',
  792. VICTORY_IMPOSSIBLE: 'Победа не возможна, бъем на результат?',
  793. FIND_COEFF: 'Поиск коэффициента больше чем',
  794. BTN_PASS: 'ПРОПУСК',
  795. BRAWLS: 'Потасовки',
  796. BRAWLS_TITLE: 'Включает возможность автопотасовок',
  797. START_AUTO_BRAWLS: 'Запустить Автопотасовки?',
  798. LOSSES: 'Поражений',
  799. WINS: 'Побед',
  800. FIGHTS: 'Боев',
  801. STAGE: 'Стадия',
  802. DONT_HAVE_LIVES: 'У Вас нет жизней',
  803. LIVES: 'Жизни',
  804. SECRET_WEALTH_ALREADY: 'товар за Зелья питомцев уже куплен',
  805. SECRET_WEALTH_NOT_ENOUGH: 'Не достаточно Зелье Питомца, у Вас {available}, нужно {need}',
  806. SECRET_WEALTH_UPGRADE_NEW_PET: 'После покупки Зелье Питомца будет не достаточно для прокачки нового питомца',
  807. SECRET_WEALTH_PURCHASED: 'Куплено {count} {name}',
  808. SECRET_WEALTH_CANCELED: 'Тайное богатство: покупка отменена',
  809. SECRET_WEALTH_BUY: 'У вас {available} Зелье Питомца.<br>Вы хотите купить {countBuy} {name} за {price} Зелье Питомца?',
  810. DAILY_BONUS: 'Ежедневная награда',
  811. DO_DAILY_QUESTS: 'Сделать ежедневные квесты',
  812. ACTIONS: 'Действия',
  813. ACTIONS_TITLE: 'Диалоговое окно с различными действиями',
  814. OTHERS: 'Разное',
  815. OTHERS_TITLE: 'Диалоговое окно с дополнительными различными действиями',
  816. CHOOSE_ACTION: 'Выберите действие',
  817. OPEN_LOOTBOX: 'У Вас {lootBox} ящиков, откываем?',
  818. STAMINA: 'Энергия',
  819. BOXES_OVER: 'Ящики закончились',
  820. NO_BOXES: 'Нет ящиков',
  821. NO_MORE_ACTIVITY: 'Больше активности за предметы сегодня не получить',
  822. EXCHANGE_ITEMS: 'Обменять предметы на очки активности (не более {maxActive})?',
  823. GET_ACTIVITY: 'Получить активность',
  824. NOT_ENOUGH_ITEMS: 'Предметов недостаточно',
  825. ACTIVITY_RECEIVED: 'Получено активности',
  826. NO_PURCHASABLE_HERO_SOULS: 'Нет доступных для покупки душ героев',
  827. PURCHASED_HERO_SOULS: 'Куплено {countHeroSouls} душ героев',
  828. NOT_ENOUGH_EMERALDS_540: 'Недостаточно изюма, нужно {imgEmerald}540 у Вас {imgEmerald}{currentStarMoney}',
  829. BUY_OUTLAND_BTN: 'Купить {count} сундуков {imgEmerald}{countEmerald}',
  830. CHESTS_NOT_AVAILABLE: 'Сундуки не доступны',
  831. OUTLAND_CHESTS_RECEIVED: 'Получено сундуков Запределья',
  832. RAID_NOT_AVAILABLE: 'Рейд не доступен или сфер нет',
  833. RAID_ADVENTURE: 'Рейд {adventureId} приключения!',
  834. SOMETHING_WENT_WRONG: 'Что-то пошло не так',
  835. ADVENTURE_COMPLETED: 'Приключение {adventureId} пройдено {times} раз',
  836. CLAN_STAT_COPY: 'Клановая статистика скопирована в буфер обмена',
  837. GET_ENERGY: 'Получить энергию',
  838. GET_ENERGY_TITLE: 'Открывает платиновые шкатулки по одной до получения 250 энергии',
  839. ITEM_EXCHANGE: 'Обмен предметов',
  840. ITEM_EXCHANGE_TITLE: 'Обменивает предметы на указанное количество активности',
  841. BUY_SOULS: 'Купить души',
  842. BUY_SOULS_TITLE: 'Купить души героев из всех доступных магазинов',
  843. BUY_OUTLAND: 'Купить Запределье',
  844. BUY_OUTLAND_TITLE: 'Купить 9 сундуков в Запределье за 540 изумрудов',
  845. RAID: 'Рейд',
  846. AUTO_RAID_ADVENTURE: 'Рейд приключения',
  847. AUTO_RAID_ADVENTURE_TITLE: 'Рейд приключения заданное количество раз',
  848. CLAN_STAT: 'Клановая статистика',
  849. CLAN_STAT_TITLE: 'Копирует клановую статистику в буфер обмена',
  850. BTN_AUTO_F5: 'Авто (F5)',
  851. BOSS_DAMAGE: 'Урон по боссу: ',
  852. NOTHING_BUY: 'Нечего покупать',
  853. LOTS_BOUGHT: 'За золото куплено {countBuy} лотов',
  854. BUY_FOR_GOLD: 'Скупить за золото',
  855. BUY_FOR_GOLD_TITLE: 'Скупить предметы за золото в Городской лавке и в магазине Камней Душ Питомцев',
  856. REWARDS_AND_MAIL: 'Награды и почта',
  857. REWARDS_AND_MAIL_TITLE: 'Собирает награды и почту',
  858. COLLECT_REWARDS_AND_MAIL: 'Собрано {countQuests} наград и {countMail} писем',
  859. TIMER_ALREADY: 'Таймер уже запущен {time}',
  860. NO_ATTEMPTS_TIMER_START: 'Попыток нет, запущен таймер {time}',
  861. EPIC_BRAWL_RESULT: '{i} Победы: {wins}/{attempts}, Монеты: {coins}, Серия: {progress}/{nextStage} [Закрыть]{end}',
  862. ATTEMPT_ENDED: '<br>Попытки закончились, запущен таймер {time}',
  863. EPIC_BRAWL: 'Вселенская битва',
  864. EPIC_BRAWL_TITLE: 'Тратит попытки во Вселенской битве',
  865. RELOAD_GAME: 'Перезагрузить игру',
  866. TIMER: 'Таймер:',
  867. SHOW_ERRORS: 'Отображать ошибки',
  868. SHOW_ERRORS_TITLE: 'Отображать ошибки запросов к серверу',
  869. ERROR_MSG: 'Ошибка: {name}<br>{description}',
  870. EVENT_AUTO_BOSS:
  871. 'Максимальное количество боев для расчета:</br>{length} * {countTestBattle} = {maxCalcBattle}</br>Если у Вас слабый компьютер на это может потребоваться много времени, нажмите крестик для отмены.</br>Искать лучший пак из всех или первый подходящий?',
  872. BEST_SLOW: 'Лучший (медленее)',
  873. FIRST_FAST: 'Первый (быстрее)',
  874. FREEZE_INTERFACE: 'Идет расчет... <br> Интерфейс может зависнуть.',
  875. ERROR_F12: 'Ошибка, подробности в консоли (F12)',
  876. FAILED_FIND_WIN_PACK: 'Победный пак найти не удалось',
  877. BEST_PACK: 'Наилучший пак: ',
  878. BOSS_HAS_BEEN_DEF: 'Босс {bossLvl} побежден',
  879. NOT_ENOUGH_ATTEMPTS_BOSS: 'Для победы босса ${bossLvl} не хватило попыток, повторить?',
  880. BOSS_VICTORY_IMPOSSIBLE:
  881. 'По результатам прерасчета {battles} боев победу получить не удалось. Вы хотите продолжить поиск победного боя на реальных боях?',
  882. BOSS_HAS_BEEN_DEF_TEXT:
  883. 'Босс {bossLvl} побежден за<br>{countBattle}/{countMaxBattle} попыток{winTimer}<br>(Сделайте синхронизацию или перезагрузите игру для обновления данных)',
  884. MAP: 'Карта: ',
  885. PLAYER_POS: 'Позиции игроков:',
  886. NY_GIFTS: 'Подарки',
  887. NY_GIFTS_TITLE: 'Открыть все новогодние подарки',
  888. NY_NO_GIFTS: 'Нет не полученных подарков',
  889. NY_GIFTS_COLLECTED: 'Собрано {count} подарков',
  890. CHANGE_MAP: 'Карта острова',
  891. CHANGE_MAP_TITLE: 'Сменить карту острова',
  892. SELECT_ISLAND_MAP: 'Выберите карту острова:',
  893. MAP_NUM: 'Карта {num}',
  894. SECRET_WEALTH_SHOP: 'Тайное богатство {name}: ',
  895. SHOPS: 'Магазины',
  896. SHOPS_DEFAULT: 'Стандартные',
  897. SHOPS_DEFAULT_TITLE: 'Стандартные магазины',
  898. SHOPS_LIST: 'Магазины {number}',
  899. SHOPS_LIST_TITLE: 'Список магазинов {number}',
  900. SHOPS_WARNING:
  901. 'Магазины<br><span style="color:red">Если Вы купите монеты магазинов потасовок за изумруды, то их надо использовать сразу, иначе после перезагрузки игры они пропадут!</span>',
  902. MINIONS_WARNING: 'Пачки героев для атаки приспешников неполные, продолжить?',
  903. FAST_SEASON: 'Быстрый сезон',
  904. FAST_SEASON_TITLE: 'Пропуск экрана с выбором карты в сезоне',
  905. SET_NUMBER_LEVELS: 'Указать колличество уровней:',
  906. POSSIBLE_IMPROVE_LEVELS: 'Возможно улучшить только {count} уровней.<br>Улучшаем?',
  907. NOT_ENOUGH_RESOURECES: 'Не хватает ресурсов',
  908. IMPROVED_LEVELS: 'Улучшено уровней: {count}',
  909. ARTIFACTS_UPGRADE: 'Улучшение артефактов',
  910. ARTIFACTS_UPGRADE_TITLE: 'Улучшает указанное количество самых дешевых артефактов героев',
  911. SKINS_UPGRADE: 'Улучшение обликов',
  912. SKINS_UPGRADE_TITLE: 'Улучшает указанное количество самых дешевых обликов героев',
  913. HINT: '<br>Подсказка: ',
  914. PICTURE: '<br>На картинке: ',
  915. ANSWER: '<br>Ответ: ',
  916. NO_HEROES_PACK: 'Проведите хотя бы один бой для сохранения атакующей команды',
  917. BRAWL_AUTO_PACK: 'Автоподбор пачки',
  918. BRAWL_AUTO_PACK_NOT_CUR_HERO: 'Автоматический подбор пачки не подходит для текущего героя',
  919. BRAWL_DAILY_TASK_COMPLETED: 'Ежедневное задание выполнено, продолжить атаку?',
  920. CALC_STAT: 'Посчитать статистику',
  921. ELEMENT_TOURNAMENT_REWARD: 'Несобранная награда за Турнир Стихий',
  922. BTN_TRY_FIX_IT: 'Исправить',
  923. BTN_TRY_FIX_IT_TITLE: 'Включить исправление боев при автоатаке',
  924. DAMAGE_FIXED: 'Урон исправлен с {lastDamage} до {maxDamage}!',
  925. DAMAGE_NO_FIXED: 'Не удалось исправить урон: {lastDamage}',
  926. LETS_FIX: 'Исправляем',
  927. COUNT_FIXED: 'За {count} попыток',
  928. DEFEAT_TURN_TIMER: 'Поражение! Включить таймер для завершения миссии?',
  929. SEASON_REWARD: 'Награды сезонов',
  930. SEASON_REWARD_TITLE: 'Собирает доступные бесплатные награды со всех текущих сезонов',
  931. SEASON_REWARD_COLLECTED: 'Собрано {count} наград сезонов',
  932. SELL_HERO_SOULS: 'Продать души',
  933. SELL_HERO_SOULS_TITLE: 'Обменивает все души героев с абсолютной звездой на золото',
  934. GOLD_RECEIVED: 'Получено золота: {gold}',
  935. OPEN_ALL_EQUIP_BOXES: 'Открыть все ящики фрагментов экипировки?',
  936. SERVER_NOT_ACCEPT: 'Сервер не принял результат',
  937. INVASION_BOSS_BUFF: 'Для {bossLvl} босса нужен баф {needBuff} у вас {haveBuff}',
  938. },
  939. };
  940.  
  941. function getLang() {
  942. let lang = '';
  943. if (typeof NXFlashVars !== 'undefined') {
  944. lang = NXFlashVars.interface_lang
  945. }
  946. if (!lang) {
  947. lang = (navigator.language || navigator.userLanguage).substr(0, 2);
  948. }
  949. if (lang == 'ru') {
  950. return lang;
  951. }
  952. return 'en';
  953. }
  954.  
  955. this.I18N = function (constant, replace) {
  956. const selectLang = getLang();
  957. if (constant && constant in i18nLangData[selectLang]) {
  958. const result = i18nLangData[selectLang][constant];
  959. if (replace) {
  960. return result.sprintf(replace);
  961. }
  962. return result;
  963. }
  964. return `% ${constant} %`;
  965. };
  966.  
  967. String.prototype.sprintf = String.prototype.sprintf ||
  968. function () {
  969. "use strict";
  970. var str = this.toString();
  971. if (arguments.length) {
  972. var t = typeof arguments[0];
  973. var key;
  974. var args = ("string" === t || "number" === t) ?
  975. Array.prototype.slice.call(arguments)
  976. : arguments[0];
  977.  
  978. for (key in args) {
  979. str = str.replace(new RegExp("\\{" + key + "\\}", "gi"), args[key]);
  980. }
  981. }
  982.  
  983. return str;
  984. };
  985.  
  986. /**
  987. * Checkboxes
  988. *
  989. * Чекбоксы
  990. */
  991. const checkboxes = {
  992. passBattle: {
  993. label: I18N('SKIP_FIGHTS'),
  994. cbox: null,
  995. title: I18N('SKIP_FIGHTS_TITLE'),
  996. default: false,
  997. },
  998. sendExpedition: {
  999. label: I18N('AUTO_EXPEDITION'),
  1000. cbox: null,
  1001. title: I18N('AUTO_EXPEDITION_TITLE'),
  1002. default: false,
  1003. },
  1004. cancelBattle: {
  1005. label: I18N('CANCEL_FIGHT'),
  1006. cbox: null,
  1007. title: I18N('CANCEL_FIGHT_TITLE'),
  1008. default: false,
  1009. },
  1010. preCalcBattle: {
  1011. label: I18N('BATTLE_RECALCULATION'),
  1012. cbox: null,
  1013. title: I18N('BATTLE_RECALCULATION_TITLE'),
  1014. default: false,
  1015. },
  1016. countControl: {
  1017. label: I18N('QUANTITY_CONTROL'),
  1018. cbox: null,
  1019. title: I18N('QUANTITY_CONTROL_TITLE'),
  1020. default: true,
  1021. },
  1022. repeatMission: {
  1023. label: I18N('REPEAT_CAMPAIGN'),
  1024. cbox: null,
  1025. title: I18N('REPEAT_CAMPAIGN_TITLE'),
  1026. default: false,
  1027. },
  1028. noOfferDonat: {
  1029. label: I18N('DISABLE_DONAT'),
  1030. cbox: null,
  1031. title: I18N('DISABLE_DONAT_TITLE'),
  1032. /**
  1033. * A crutch to get the field before getting the character id
  1034. *
  1035. * Костыль чтоб получать поле до получения id персонажа
  1036. */
  1037. default: (() => {
  1038. $result = false;
  1039. try {
  1040. $result = JSON.parse(localStorage[GM_info.script.name + ':noOfferDonat']);
  1041. } catch (e) {
  1042. $result = false;
  1043. }
  1044. return $result || false;
  1045. })(),
  1046. },
  1047. dailyQuests: {
  1048. label: I18N('DAILY_QUESTS'),
  1049. cbox: null,
  1050. title: I18N('DAILY_QUESTS_TITLE'),
  1051. default: false,
  1052. },
  1053. // Потасовки
  1054. autoBrawls: {
  1055. label: I18N('BRAWLS'),
  1056. cbox: null,
  1057. title: I18N('BRAWLS_TITLE'),
  1058. default: (() => {
  1059. $result = false;
  1060. try {
  1061. $result = JSON.parse(localStorage[GM_info.script.name + ':autoBrawls']);
  1062. } catch (e) {
  1063. $result = false;
  1064. }
  1065. return $result || false;
  1066. })(),
  1067. hide: false,
  1068. },
  1069. getAnswer: {
  1070. label: I18N('AUTO_QUIZ'),
  1071. cbox: null,
  1072. title: I18N('AUTO_QUIZ_TITLE'),
  1073. default: false,
  1074. hide: true,
  1075. },
  1076. tryFixIt_v2: {
  1077. label: I18N('BTN_TRY_FIX_IT'),
  1078. cbox: null,
  1079. title: I18N('BTN_TRY_FIX_IT_TITLE'),
  1080. default: false,
  1081. hide: false,
  1082. },
  1083. showErrors: {
  1084. label: I18N('SHOW_ERRORS'),
  1085. cbox: null,
  1086. title: I18N('SHOW_ERRORS_TITLE'),
  1087. default: true,
  1088. },
  1089. buyForGold: {
  1090. label: I18N('BUY_FOR_GOLD'),
  1091. cbox: null,
  1092. title: I18N('BUY_FOR_GOLD_TITLE'),
  1093. default: false,
  1094. },
  1095. hideServers: {
  1096. label: I18N('HIDE_SERVERS'),
  1097. cbox: null,
  1098. title: I18N('HIDE_SERVERS_TITLE'),
  1099. default: false,
  1100. },
  1101. fastSeason: {
  1102. label: I18N('FAST_SEASON'),
  1103. cbox: null,
  1104. title: I18N('FAST_SEASON_TITLE'),
  1105. default: false,
  1106. },
  1107. };
  1108. /**
  1109. * Get checkbox state
  1110. *
  1111. * Получить состояние чекбокса
  1112. */
  1113. function isChecked(checkBox) {
  1114. if (!(checkBox in checkboxes)) {
  1115. return false;
  1116. }
  1117. return checkboxes[checkBox].cbox?.checked;
  1118. }
  1119. /**
  1120. * Input fields
  1121. *
  1122. * Поля ввода
  1123. */
  1124. const inputs = {
  1125. countTitanit: {
  1126. input: null,
  1127. title: I18N('HOW_MUCH_TITANITE'),
  1128. default: 150,
  1129. },
  1130. speedBattle: {
  1131. input: null,
  1132. title: I18N('COMBAT_SPEED'),
  1133. default: 5,
  1134. },
  1135. countTestBattle: {
  1136. input: null,
  1137. title: I18N('NUMBER_OF_TEST'),
  1138. default: 10,
  1139. },
  1140. countAutoBattle: {
  1141. input: null,
  1142. title: I18N('NUMBER_OF_AUTO_BATTLE'),
  1143. default: 10,
  1144. },
  1145. FPS: {
  1146. input: null,
  1147. title: 'FPS',
  1148. default: 60,
  1149. }
  1150. }
  1151. /**
  1152. * Checks the checkbox
  1153. *
  1154. * Поплучить данные поля ввода
  1155. */
  1156. function getInput(inputName) {
  1157. return inputs[inputName]?.input?.value;
  1158. }
  1159.  
  1160. /**
  1161. * Control FPS
  1162. *
  1163. * Контроль FPS
  1164. */
  1165. let nextAnimationFrame = Date.now();
  1166. const oldRequestAnimationFrame = this.requestAnimationFrame;
  1167. this.requestAnimationFrame = async function (e) {
  1168. const FPS = Number(getInput('FPS')) || -1;
  1169. const now = Date.now();
  1170. const delay = nextAnimationFrame - now;
  1171. nextAnimationFrame = Math.max(now, nextAnimationFrame) + Math.min(1e3 / FPS, 1e3);
  1172. if (delay > 0) {
  1173. await new Promise((e) => setTimeout(e, delay));
  1174. }
  1175. oldRequestAnimationFrame(e);
  1176. };
  1177. /**
  1178. * Button List
  1179. *
  1180. * Список кнопочек
  1181. */
  1182. const buttons = {
  1183. getOutland: {
  1184. name: I18N('TO_DO_EVERYTHING'),
  1185. title: I18N('TO_DO_EVERYTHING_TITLE'),
  1186. func: testDoYourBest,
  1187. },
  1188. doActions: {
  1189. name: I18N('ACTIONS'),
  1190. title: I18N('ACTIONS_TITLE'),
  1191. func: async function () {
  1192. const popupButtons = [
  1193. {
  1194. msg: I18N('OUTLAND'),
  1195. result: function () {
  1196. confShow(`${I18N('RUN_SCRIPT')} ${I18N('OUTLAND')}?`, getOutland);
  1197. },
  1198. title: I18N('OUTLAND_TITLE'),
  1199. },
  1200. {
  1201. msg: I18N('TOWER'),
  1202. result: function () {
  1203. confShow(`${I18N('RUN_SCRIPT')} ${I18N('TOWER')}?`, testTower);
  1204. },
  1205. title: I18N('TOWER_TITLE'),
  1206. },
  1207. {
  1208. msg: I18N('EXPEDITIONS'),
  1209. result: function () {
  1210. confShow(`${I18N('RUN_SCRIPT')} ${I18N('EXPEDITIONS')}?`, checkExpedition);
  1211. },
  1212. title: I18N('EXPEDITIONS_TITLE'),
  1213. },
  1214. {
  1215. msg: I18N('MINIONS'),
  1216. result: function () {
  1217. confShow(`${I18N('RUN_SCRIPT')} ${I18N('MINIONS')}?`, testRaidNodes);
  1218. },
  1219. title: I18N('MINIONS_TITLE'),
  1220. },
  1221. {
  1222. msg: I18N('ESTER_EGGS'),
  1223. result: function () {
  1224. confShow(`${I18N('RUN_SCRIPT')} ${I18N('ESTER_EGGS')}?`, offerFarmAllReward);
  1225. },
  1226. title: I18N('ESTER_EGGS_TITLE'),
  1227. },
  1228. {
  1229. msg: I18N('STORM'),
  1230. result: function () {
  1231. testAdventure('solo');
  1232. },
  1233. title: I18N('STORM_TITLE'),
  1234. },
  1235. {
  1236. msg: I18N('REWARDS'),
  1237. result: function () {
  1238. confShow(`${I18N('RUN_SCRIPT')} ${I18N('REWARDS')}?`, questAllFarm);
  1239. },
  1240. title: I18N('REWARDS_TITLE'),
  1241. },
  1242. {
  1243. msg: I18N('MAIL'),
  1244. result: function () {
  1245. confShow(`${I18N('RUN_SCRIPT')} ${I18N('MAIL')}?`, mailGetAll);
  1246. },
  1247. title: I18N('MAIL_TITLE'),
  1248. },
  1249. {
  1250. msg: I18N('SEER'),
  1251. result: function () {
  1252. confShow(`${I18N('RUN_SCRIPT')} ${I18N('SEER')}?`, rollAscension);
  1253. },
  1254. title: I18N('SEER_TITLE'),
  1255. },
  1256. /*
  1257. {
  1258. msg: I18N('NY_GIFTS'),
  1259. result: getGiftNewYear,
  1260. title: I18N('NY_GIFTS_TITLE'),
  1261. },
  1262. */
  1263. ];
  1264. popupButtons.push({ result: false, isClose: true });
  1265. const answer = await popup.confirm(`${I18N('CHOOSE_ACTION')}:`, popupButtons);
  1266. if (typeof answer === 'function') {
  1267. answer();
  1268. }
  1269. },
  1270. },
  1271. doOthers: {
  1272. name: I18N('OTHERS'),
  1273. title: I18N('OTHERS_TITLE'),
  1274. func: async function () {
  1275. const popupButtons = [
  1276. {
  1277. msg: I18N('GET_ENERGY'),
  1278. result: farmStamina,
  1279. title: I18N('GET_ENERGY_TITLE'),
  1280. },
  1281. {
  1282. msg: I18N('ITEM_EXCHANGE'),
  1283. result: fillActive,
  1284. title: I18N('ITEM_EXCHANGE_TITLE'),
  1285. },
  1286. {
  1287. msg: I18N('BUY_SOULS'),
  1288. result: function () {
  1289. confShow(`${I18N('RUN_SCRIPT')} ${I18N('BUY_SOULS')}?`, buyHeroFragments);
  1290. },
  1291. title: I18N('BUY_SOULS_TITLE'),
  1292. },
  1293. {
  1294. msg: I18N('BUY_FOR_GOLD'),
  1295. result: function () {
  1296. confShow(`${I18N('RUN_SCRIPT')} ${I18N('BUY_FOR_GOLD')}?`, buyInStoreForGold);
  1297. },
  1298. title: I18N('BUY_FOR_GOLD_TITLE'),
  1299. },
  1300. {
  1301. msg: I18N('BUY_OUTLAND'),
  1302. result: bossOpenChestPay,
  1303. title: I18N('BUY_OUTLAND_TITLE'),
  1304. },
  1305. {
  1306. msg: I18N('AUTO_RAID_ADVENTURE'),
  1307. result: autoRaidAdventure,
  1308. title: I18N('AUTO_RAID_ADVENTURE_TITLE'),
  1309. },
  1310. {
  1311. msg: I18N('CLAN_STAT'),
  1312. result: clanStatistic,
  1313. title: I18N('CLAN_STAT_TITLE'),
  1314. },
  1315. {
  1316. msg: I18N('EPIC_BRAWL'),
  1317. result: async function () {
  1318. confShow(`${I18N('RUN_SCRIPT')} ${I18N('EPIC_BRAWL')}?`, () => {
  1319. const brawl = new epicBrawl();
  1320. brawl.start();
  1321. });
  1322. },
  1323. title: I18N('EPIC_BRAWL_TITLE'),
  1324. },
  1325. {
  1326. msg: I18N('ARTIFACTS_UPGRADE'),
  1327. result: updateArtifacts,
  1328. title: I18N('ARTIFACTS_UPGRADE_TITLE'),
  1329. },
  1330. {
  1331. msg: I18N('SKINS_UPGRADE'),
  1332. result: updateSkins,
  1333. title: I18N('SKINS_UPGRADE_TITLE'),
  1334. },
  1335. {
  1336. msg: I18N('SEASON_REWARD'),
  1337. result: farmBattlePass,
  1338. title: I18N('SEASON_REWARD_TITLE'),
  1339. },
  1340. {
  1341. msg: I18N('SELL_HERO_SOULS'),
  1342. result: sellHeroSoulsForGold,
  1343. title: I18N('SELL_HERO_SOULS_TITLE'),
  1344. },
  1345. {
  1346. msg: I18N('CHANGE_MAP'),
  1347. result: async function () {
  1348. const maps = Object.values(lib.data.seasonAdventure.list)
  1349. .filter((e) => e.map.cells.length > 2)
  1350. .map((i) => ({
  1351. msg: I18N('MAP_NUM', { num: i.id }),
  1352. result: i.id,
  1353. }));
  1354.  
  1355. const result = await popup.confirm(I18N('SELECT_ISLAND_MAP'), [...maps, { result: false, isClose: true }]);
  1356. if (result) {
  1357. cheats.changeIslandMap(result);
  1358. }
  1359. },
  1360. title: I18N('CHANGE_MAP_TITLE'),
  1361. },
  1362. ];
  1363. popupButtons.push({ result: false, isClose: true });
  1364. const answer = await popup.confirm(`${I18N('CHOOSE_ACTION')}:`, popupButtons);
  1365. if (typeof answer === 'function') {
  1366. answer();
  1367. }
  1368. },
  1369. },
  1370. testTitanArena: {
  1371. name: I18N('TITAN_ARENA'),
  1372. title: I18N('TITAN_ARENA_TITLE'),
  1373. func: function () {
  1374. confShow(`${I18N('RUN_SCRIPT')} ${I18N('TITAN_ARENA')}?`, testTitanArena);
  1375. },
  1376. },
  1377. testDungeon: {
  1378. name: I18N('DUNGEON'),
  1379. title: I18N('DUNGEON_TITLE'),
  1380. func: function () {
  1381. confShow(`${I18N('RUN_SCRIPT')} ${I18N('DUNGEON')}?`, testDungeon);
  1382. },
  1383. },
  1384. // Архидемон
  1385. bossRatingEvent: {
  1386. name: I18N('ARCHDEMON'),
  1387. title: I18N('ARCHDEMON_TITLE'),
  1388. func: function () {
  1389. confShow(`${I18N('RUN_SCRIPT')} ${I18N('ARCHDEMON')}?`, bossRatingEvent);
  1390. },
  1391. hide: true,
  1392. },
  1393. // Горнило душ
  1394. bossRatingEvent: {
  1395. name: I18N('FURNACE_OF_SOULS'),
  1396. title: I18N('ARCHDEMON_TITLE'),
  1397. func: function () {
  1398. confShow(`${I18N('RUN_SCRIPT')} ${I18N('FURNACE_OF_SOULS')}?`, bossRatingEventSouls);
  1399. },
  1400. hide: true,
  1401. },
  1402. rewardsAndMailFarm: {
  1403. name: I18N('REWARDS_AND_MAIL'),
  1404. title: I18N('REWARDS_AND_MAIL_TITLE'),
  1405. func: function () {
  1406. confShow(`${I18N('RUN_SCRIPT')} ${I18N('REWARDS_AND_MAIL')}?`, rewardsAndMailFarm);
  1407. },
  1408. },
  1409. testAdventure: {
  1410. name: I18N('ADVENTURE'),
  1411. title: I18N('ADVENTURE_TITLE'),
  1412. func: () => {
  1413. testAdventure();
  1414. },
  1415. },
  1416. goToSanctuary: {
  1417. name: I18N('SANCTUARY'),
  1418. title: I18N('SANCTUARY_TITLE'),
  1419. func: cheats.goSanctuary,
  1420. },
  1421. goToClanWar: {
  1422. name: I18N('GUILD_WAR'),
  1423. title: I18N('GUILD_WAR_TITLE'),
  1424. func: cheats.goClanWar,
  1425. },
  1426. dailyQuests: {
  1427. name: I18N('DAILY_QUESTS'),
  1428. title: I18N('DAILY_QUESTS_TITLE'),
  1429. func: async function () {
  1430. const quests = new dailyQuests(
  1431. () => {},
  1432. () => {}
  1433. );
  1434. await quests.autoInit();
  1435. quests.start();
  1436. },
  1437. },
  1438. newDay: {
  1439. name: I18N('SYNC'),
  1440. title: I18N('SYNC_TITLE'),
  1441. func: function () {
  1442. confShow(`${I18N('RUN_SCRIPT')} ${I18N('SYNC')}?`, cheats.refreshGame);
  1443. },
  1444. },
  1445. };
  1446. /**
  1447. * Display buttons
  1448. *
  1449. * Вывести кнопочки
  1450. */
  1451. function addControlButtons() {
  1452. for (let name in buttons) {
  1453. button = buttons[name];
  1454. if (button.hide) {
  1455. continue;
  1456. }
  1457. button['button'] = scriptMenu.addButton(button.name, button.func, button.title);
  1458. }
  1459. }
  1460. /**
  1461. * Adds links
  1462. *
  1463. * Добавляет ссылки
  1464. */
  1465. function addBottomUrls() {
  1466. scriptMenu.addHeader(I18N('BOTTOM_URLS'));
  1467. }
  1468. /**
  1469. * Stop repetition of the mission
  1470. *
  1471. * Остановить повтор миссии
  1472. */
  1473. let isStopSendMission = false;
  1474. /**
  1475. * There is a repetition of the mission
  1476. *
  1477. * Идет повтор миссии
  1478. */
  1479. let isSendsMission = false;
  1480. /**
  1481. * Data on the past mission
  1482. *
  1483. * Данные о прошедшей мисии
  1484. */
  1485. let lastMissionStart = {}
  1486. /**
  1487. * Start time of the last battle in the company
  1488. *
  1489. * Время начала последнего боя в кампании
  1490. */
  1491. let lastMissionBattleStart = 0;
  1492. /**
  1493. * Data for calculating the last battle with the boss
  1494. *
  1495. * Данные для расчете последнего боя с боссом
  1496. */
  1497. let lastBossBattle = null;
  1498. /**
  1499. * Information about the last battle
  1500. *
  1501. * Данные о прошедшей битве
  1502. */
  1503. let lastBattleArg = {}
  1504. let lastBossBattleStart = null;
  1505. this.addBattleTimer = 4;
  1506. this.invasionTimer = 2500;
  1507. const invasionInfo = {
  1508. buff: 0,
  1509. bossLvl: 130,
  1510. };
  1511. const invasionDataPacks = {
  1512. 130: { buff: 0, pet: 6004, heroes: [58, 48, 16, 65, 59], favor: { 16: 6004, 48: 6001, 58: 6002, 59: 6005, 65: 6000 } },
  1513. 140: { buff: 0, pet: 6006, heroes: [1, 4, 13, 58, 65], favor: { 1: 6001, 4: 6006, 13: 6002, 58: 6005, 65: 6000 } },
  1514. 150: { buff: 0, pet: 6006, heroes: [1, 12, 17, 21, 65], favor: { 1: 6001, 12: 6003, 17: 6006, 21: 6002, 65: 6000 } },
  1515. 160: { buff: 0, pet: 6008, heroes: [12, 21, 34, 58, 65], favor: { 12: 6003, 21: 6006, 34: 6008, 58: 6002, 65: 6001 } },
  1516. 170: { buff: 0, pet: 6005, heroes: [33, 12, 65, 21, 4], favor: { 4: 6001, 12: 6003, 21: 6006, 33: 6008, 65: 6000 } },
  1517. 180: { buff: 20, pet: 6009, heroes: [58, 13, 5, 17, 65], favor: { 5: 6006, 13: 6003, 58: 6005 } },
  1518. 190: { buff: 0, pet: 6006, heroes: [1, 12, 21, 36, 65], favor: { 1: 6004, 12: 6003, 21: 6006, 36: 6005, 65: 6000 } },
  1519. 200: { buff: 0, pet: 6006, heroes: [12, 1, 13, 2, 65], favor: { 2: 6001, 12: 6003, 13: 6006, 65: 6000 } },
  1520. 210: { buff: 15, pet: 6005, heroes: [12, 21, 33, 58, 65], favor: { 12: 6003, 21: 6006, 33: 6008, 58: 6005, 65: 6001 } },
  1521. 220: { buff: 5, pet: 6006, heroes: [58, 13, 7, 34, 65], favor: { 7: 6002, 13: 6008, 34: 6006, 58: 6005, 65: 6001 } },
  1522. 230: { buff: 35, pet: 6005, heroes: [5, 7, 13, 58, 65], favor: { 5: 6006, 7: 6003, 13: 6002, 58: 6005, 65: 6000 } },
  1523. 240: { buff: 0, pet: 6005, heroes: [12, 58, 1, 36, 65], favor: { 1: 6006, 12: 6003, 36: 6005, 65: 6001 } },
  1524. 250: { buff: 15, pet: 6005, heroes: [12, 36, 4, 16, 65], favor: { 12: 6003, 16: 6004, 36: 6005, 65: 6001 } },
  1525. 260: { buff: 15, pet: 6005, heroes: [48, 12, 36, 65, 4], favor: { 4: 6006, 12: 6003, 36: 6005, 48: 6000, 65: 6007 } },
  1526. 270: { buff: 35, pet: 6005, heroes: [12, 58, 36, 4, 65], favor: { 4: 6006, 12: 6003, 36: 6005 } },
  1527. 280: { buff: 80, pet: 6005, heroes: [21, 36, 48, 7, 65], favor: { 7: 6003, 21: 6006, 36: 6005, 48: 6001, 65: 6000 } },
  1528. 290: { buff: 95, pet: 6008, heroes: [12, 21, 36, 35, 65], favor: { 12: 6003, 21: 6006, 36: 6005, 65: 6007 } },
  1529. 300: { buff: 25, pet: 6005, heroes: [12, 13, 4, 34, 65], favor: { 4: 6006, 12: 6003, 13: 6007, 34: 6002 } },
  1530. 310: { buff: 45, pet: 6005, heroes: [12, 21, 58, 33, 65], favor: { 12: 6003, 21: 6006, 33: 6002, 58: 6005, 65: 6007 } },
  1531. 320: { buff: 70, pet: 6005, heroes: [12, 48, 2, 6, 65], favor: { 6: 6005, 12: 6003 } },
  1532. 330: { buff: 70, pet: 6005, heroes: [12, 21, 36, 5, 65], favor: { 5: 6002, 12: 6003, 21: 6006, 36: 6005, 65: 6000 } },
  1533. 340: { buff: 55, pet: 6009, heroes: [12, 36, 13, 6, 65], favor: { 6: 6005, 12: 6003, 13: 6002, 36: 6006, 65: 6000 } },
  1534. 350: { buff: 100, pet: 6005, heroes: [12, 21, 58, 34, 65], favor: { 12: 6003, 21: 6006, 58: 6005 } },
  1535. 360: { buff: 85, pet: 6007, heroes: [12, 21, 36, 4, 65], favor: { 4: 6006, 12: 6003, 21: 6002, 36: 6005 } },
  1536. 370: { buff: 90, pet: 6008, heroes: [12, 21, 36, 13, 65], favor: { 12: 6003, 13: 6007, 21: 6006, 36: 6005, 65: 6001 } },
  1537. 380: { buff: 165, pet: 6005, heroes: [12, 33, 36, 4, 65], favor: { 4: 6001, 12: 6003, 33: 6006 } },
  1538. 390: { buff: 235, pet: 6005, heroes: [21, 58, 48, 2, 65], favor: { 2: 6005, 21: 6002 } },
  1539. 400: { buff: 125, pet: 6006, heroes: [12, 21, 36, 48, 65], favor: { 12: 6003, 21: 6006, 36: 6005, 48: 6001, 65: 6007 } },
  1540. };
  1541. /**
  1542. * The name of the function of the beginning of the battle
  1543. *
  1544. * Имя функции начала боя
  1545. */
  1546. let nameFuncStartBattle = '';
  1547. /**
  1548. * The name of the function of the end of the battle
  1549. *
  1550. * Имя функции конца боя
  1551. */
  1552. let nameFuncEndBattle = '';
  1553. /**
  1554. * Data for calculating the last battle
  1555. *
  1556. * Данные для расчета последнего боя
  1557. */
  1558. let lastBattleInfo = null;
  1559. /**
  1560. * The ability to cancel the battle
  1561. *
  1562. * Возможность отменить бой
  1563. */
  1564. let isCancalBattle = true;
  1565.  
  1566. function setIsCancalBattle(value) {
  1567. isCancalBattle = value;
  1568. }
  1569.  
  1570. /**
  1571. * Certificator of the last open nesting doll
  1572. *
  1573. * Идетификатор последней открытой матрешки
  1574. */
  1575. let lastRussianDollId = null;
  1576. /**
  1577. * Cancel the training guide
  1578. *
  1579. * Отменить обучающее руководство
  1580. */
  1581. this.isCanceledTutorial = false;
  1582.  
  1583. /**
  1584. * Data from the last question of the quiz
  1585. *
  1586. * Данные последнего вопроса викторины
  1587. */
  1588. let lastQuestion = null;
  1589. /**
  1590. * Answer to the last question of the quiz
  1591. *
  1592. * Ответ на последний вопрос викторины
  1593. */
  1594. let lastAnswer = null;
  1595. /**
  1596. * Flag for opening keys or titan artifact spheres
  1597. *
  1598. * Флаг открытия ключей или сфер артефактов титанов
  1599. */
  1600. let artifactChestOpen = false;
  1601. /**
  1602. * The name of the function to open keys or orbs of titan artifacts
  1603. *
  1604. * Имя функции открытия ключей или сфер артефактов титанов
  1605. */
  1606. let artifactChestOpenCallName = '';
  1607. let correctShowOpenArtifact = 0;
  1608. /**
  1609. * Data for the last battle in the dungeon
  1610. * (Fix endless cards)
  1611. *
  1612. * Данные для последнего боя в подземке
  1613. * (Исправление бесконечных карт)
  1614. */
  1615. let lastDungeonBattleData = null;
  1616. /**
  1617. * Start time of the last battle in the dungeon
  1618. *
  1619. * Время начала последнего боя в подземелье
  1620. */
  1621. let lastDungeonBattleStart = 0;
  1622. /**
  1623. * Subscription end time
  1624. *
  1625. * Время окончания подписки
  1626. */
  1627. let subEndTime = 0;
  1628. /**
  1629. * Number of prediction cards
  1630. *
  1631. * Количество карт предсказаний
  1632. */
  1633. let countPredictionCard = 0;
  1634.  
  1635. /**
  1636. * Brawl pack
  1637. *
  1638. * Пачка для потасовок
  1639. */
  1640. let brawlsPack = null;
  1641. /**
  1642. * Autobrawl started
  1643. *
  1644. * Автопотасовка запущена
  1645. */
  1646. let isBrawlsAutoStart = false;
  1647. let clanDominationGetInfo = null;
  1648. /**
  1649. * Copies the text to the clipboard
  1650. *
  1651. * Копирует тест в буфер обмена
  1652. * @param {*} text copied text // копируемый текст
  1653. */
  1654. function copyText(text) {
  1655. let copyTextarea = document.createElement("textarea");
  1656. copyTextarea.style.opacity = "0";
  1657. copyTextarea.textContent = text;
  1658. document.body.appendChild(copyTextarea);
  1659. copyTextarea.select();
  1660. document.execCommand("copy");
  1661. document.body.removeChild(copyTextarea);
  1662. delete copyTextarea;
  1663. }
  1664. /**
  1665. * Returns the history of requests
  1666. *
  1667. * Возвращает историю запросов
  1668. */
  1669. this.getRequestHistory = function() {
  1670. return requestHistory;
  1671. }
  1672. /**
  1673. * Generates a random integer from min to max
  1674. *
  1675. * Гененирует случайное целое число от min до max
  1676. */
  1677. const random = function (min, max) {
  1678. return Math.floor(Math.random() * (max - min + 1) + min);
  1679. }
  1680. const randf = function (min, max) {
  1681. return Math.random() * (max - min + 1) + min;
  1682. };
  1683. /**
  1684. * Clearing the request history
  1685. *
  1686. * Очистка истоии запросов
  1687. */
  1688. setInterval(function () {
  1689. let now = Date.now();
  1690. for (let i in requestHistory) {
  1691. const time = +i.split('_')[0];
  1692. if (now - time > 300000) {
  1693. delete requestHistory[i];
  1694. }
  1695. }
  1696. }, 300000);
  1697. /**
  1698. * Displays the dialog box
  1699. *
  1700. * Отображает диалоговое окно
  1701. */
  1702. function confShow(message, yesCallback, noCallback) {
  1703. let buts = [];
  1704. message = message || I18N('DO_YOU_WANT');
  1705. noCallback = noCallback || (() => {});
  1706. if (yesCallback) {
  1707. buts = [
  1708. { msg: I18N('BTN_RUN'), result: true},
  1709. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true},
  1710. ]
  1711. } else {
  1712. yesCallback = () => {};
  1713. buts = [
  1714. { msg: I18N('BTN_OK'), result: true},
  1715. ];
  1716. }
  1717. popup.confirm(message, buts).then((e) => {
  1718. // dialogPromice = null;
  1719. if (e) {
  1720. yesCallback();
  1721. } else {
  1722. noCallback();
  1723. }
  1724. });
  1725. }
  1726. /**
  1727. * Override/proxy the method for creating a WS package send
  1728. *
  1729. * Переопределяем/проксируем метод создания отправки WS пакета
  1730. */
  1731. WebSocket.prototype.send = function (data) {
  1732. if (!this.isSetOnMessage) {
  1733. const oldOnmessage = this.onmessage;
  1734. this.onmessage = function (event) {
  1735. try {
  1736. const data = JSON.parse(event.data);
  1737. if (!this.isWebSocketLogin && data.result.type == "iframeEvent.login") {
  1738. this.isWebSocketLogin = true;
  1739. } else if (data.result.type == "iframeEvent.login") {
  1740. return;
  1741. }
  1742. } catch (e) { }
  1743. return oldOnmessage.apply(this, arguments);
  1744. }
  1745. this.isSetOnMessage = true;
  1746. }
  1747. original.SendWebSocket.call(this, data);
  1748. }
  1749. /**
  1750. * Overriding/Proxying the Ajax Request Creation Method
  1751. *
  1752. * Переопределяем/проксируем метод создания Ajax запроса
  1753. */
  1754. XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
  1755. this.uniqid = Date.now() + '_' + random(1000000, 10000000);
  1756. this.errorRequest = false;
  1757. if (method == 'POST' && url.includes('.nextersglobal.com/api/') && /api\/$/.test(url)) {
  1758. if (!apiUrl) {
  1759. apiUrl = url;
  1760. const socialInfo = /heroes-(.+?)\./.exec(apiUrl);
  1761. console.log(socialInfo);
  1762. }
  1763. requestHistory[this.uniqid] = {
  1764. method,
  1765. url,
  1766. error: [],
  1767. headers: {},
  1768. request: null,
  1769. response: null,
  1770. signature: [],
  1771. calls: {},
  1772. };
  1773. } else if (method == 'POST' && url.includes('error.nextersglobal.com/client/')) {
  1774. this.errorRequest = true;
  1775. }
  1776. return original.open.call(this, method, url, async, user, password);
  1777. };
  1778. /**
  1779. * Overriding/Proxying the header setting method for the AJAX request
  1780. *
  1781. * Переопределяем/проксируем метод установки заголовков для AJAX запроса
  1782. */
  1783. XMLHttpRequest.prototype.setRequestHeader = function (name, value, check) {
  1784. if (this.uniqid in requestHistory) {
  1785. requestHistory[this.uniqid].headers[name] = value;
  1786. } else {
  1787. check = true;
  1788. }
  1789.  
  1790. if (name == 'X-Auth-Signature') {
  1791. requestHistory[this.uniqid].signature.push(value);
  1792. if (!check) {
  1793. return;
  1794. }
  1795. }
  1796.  
  1797. return original.setRequestHeader.call(this, name, value);
  1798. };
  1799. /**
  1800. * Overriding/Proxying the AJAX Request Sending Method
  1801. *
  1802. * Переопределяем/проксируем метод отправки AJAX запроса
  1803. */
  1804. XMLHttpRequest.prototype.send = async function (sourceData) {
  1805. if (this.uniqid in requestHistory) {
  1806. let tempData = null;
  1807. if (getClass(sourceData) == "ArrayBuffer") {
  1808. tempData = decoder.decode(sourceData);
  1809. } else {
  1810. tempData = sourceData;
  1811. }
  1812. requestHistory[this.uniqid].request = tempData;
  1813. let headers = requestHistory[this.uniqid].headers;
  1814. lastHeaders = Object.assign({}, headers);
  1815. /**
  1816. * Game loading event
  1817. *
  1818. * Событие загрузки игры
  1819. */
  1820. if (headers["X-Request-Id"] > 2 && !isLoadGame) {
  1821. isLoadGame = true;
  1822. if (cheats.libGame) {
  1823. lib.setData(cheats.libGame);
  1824. } else {
  1825. lib.setData(await cheats.LibLoad());
  1826. }
  1827. addControls();
  1828. addControlButtons();
  1829. addBottomUrls();
  1830.  
  1831. if (isChecked('sendExpedition')) {
  1832. const isTimeBetweenDays = isTimeBetweenNewDays();
  1833. if (!isTimeBetweenDays) {
  1834. checkExpedition();
  1835. } else {
  1836. setProgress(I18N('EXPEDITIONS_NOTTIME'), true);
  1837. }
  1838. }
  1839.  
  1840. getAutoGifts();
  1841.  
  1842. cheats.activateHacks();
  1843. justInfo();
  1844. if (isChecked('dailyQuests')) {
  1845. testDailyQuests();
  1846. }
  1847.  
  1848. if (isChecked('buyForGold')) {
  1849. buyInStoreForGold();
  1850. }
  1851. }
  1852. /**
  1853. * Outgoing request data processing
  1854. *
  1855. * Обработка данных исходящего запроса
  1856. */
  1857. sourceData = await checkChangeSend.call(this, sourceData, tempData);
  1858. /**
  1859. * Handling incoming request data
  1860. *
  1861. * Обработка данных входящего запроса
  1862. */
  1863. const oldReady = this.onreadystatechange;
  1864. this.onreadystatechange = async function (e) {
  1865. if (this.errorRequest) {
  1866. return oldReady.apply(this, arguments);
  1867. }
  1868. if(this.readyState == 4 && this.status == 200) {
  1869. isTextResponse = this.responseType === "text" || this.responseType === "";
  1870. let response = isTextResponse ? this.responseText : this.response;
  1871. requestHistory[this.uniqid].response = response;
  1872. /**
  1873. * Replacing incoming request data
  1874. *
  1875. * Заменна данных входящего запроса
  1876. */
  1877. if (isTextResponse) {
  1878. await checkChangeResponse.call(this, response);
  1879. }
  1880. /**
  1881. * A function to run after the request is executed
  1882. *
  1883. * Функция запускаемая после выполения запроса
  1884. */
  1885. if (typeof this.onReadySuccess == 'function') {
  1886. setTimeout(this.onReadySuccess, 500);
  1887. }
  1888. /** Удаляем из истории запросов битвы с боссом */
  1889. if ('invasion_bossStart' in requestHistory[this.uniqid].calls) delete requestHistory[this.uniqid];
  1890. }
  1891. if (oldReady) {
  1892. return oldReady.apply(this, arguments);
  1893. }
  1894. }
  1895. }
  1896. if (this.errorRequest) {
  1897. const oldReady = this.onreadystatechange;
  1898. this.onreadystatechange = function () {
  1899. Object.defineProperty(this, 'status', {
  1900. writable: true
  1901. });
  1902. this.status = 200;
  1903. Object.defineProperty(this, 'readyState', {
  1904. writable: true
  1905. });
  1906. this.readyState = 4;
  1907. Object.defineProperty(this, 'responseText', {
  1908. writable: true
  1909. });
  1910. this.responseText = JSON.stringify({
  1911. "result": true
  1912. });
  1913. if (typeof this.onReadySuccess == 'function') {
  1914. setTimeout(this.onReadySuccess, 200);
  1915. }
  1916. return oldReady.apply(this, arguments);
  1917. }
  1918. this.onreadystatechange();
  1919. } else {
  1920. try {
  1921. return original.send.call(this, sourceData);
  1922. } catch(e) {
  1923. debugger;
  1924. }
  1925. }
  1926. };
  1927. /**
  1928. * Processing and substitution of outgoing data
  1929. *
  1930. * Обработка и подмена исходящих данных
  1931. */
  1932. async function checkChangeSend(sourceData, tempData) {
  1933. try {
  1934. /**
  1935. * A function that replaces battle data with incorrect ones to cancel combatя
  1936. *
  1937. * Функция заменяющая данные боя на неверные для отмены боя
  1938. */
  1939. const fixBattle = function (heroes) {
  1940. for (const ids in heroes) {
  1941. hero = heroes[ids];
  1942. hero.energy = random(1, 999);
  1943. if (hero.hp > 0) {
  1944. hero.hp = random(1, hero.hp);
  1945. }
  1946. }
  1947. }
  1948. /**
  1949. * Dialog window 2
  1950. *
  1951. * Диалоговое окно 2
  1952. */
  1953. const showMsg = async function (msg, ansF, ansS) {
  1954. if (typeof popup == 'object') {
  1955. return await popup.confirm(msg, [
  1956. {msg: ansF, result: false},
  1957. {msg: ansS, result: true},
  1958. ]);
  1959. } else {
  1960. return !confirm(`${msg}\n ${ansF} (${I18N('BTN_OK')})\n ${ansS} (${I18N('BTN_CANCEL')})`);
  1961. }
  1962. }
  1963. /**
  1964. * Dialog window 3
  1965. *
  1966. * Диалоговое окно 3
  1967. */
  1968. const showMsgs = async function (msg, ansF, ansS, ansT) {
  1969. return await popup.confirm(msg, [
  1970. {msg: ansF, result: 0},
  1971. {msg: ansS, result: 1},
  1972. {msg: ansT, result: 2},
  1973. ]);
  1974. }
  1975.  
  1976. let changeRequest = false;
  1977. testData = JSON.parse(tempData);
  1978. for (const call of testData.calls) {
  1979. if (!artifactChestOpen) {
  1980. requestHistory[this.uniqid].calls[call.name] = call.ident;
  1981. }
  1982. /**
  1983. * Cancellation of the battle in adventures, on VG and with minions of Asgard
  1984. * Отмена боя в приключениях, на ВГ и с прислужниками Асгарда
  1985. */
  1986. if ((call.name == 'adventure_endBattle' ||
  1987. call.name == 'adventureSolo_endBattle' ||
  1988. call.name == 'clanWarEndBattle' &&
  1989. isChecked('cancelBattle') ||
  1990. call.name == 'crossClanWar_endBattle' &&
  1991. isChecked('cancelBattle') ||
  1992. call.name == 'brawl_endBattle' ||
  1993. call.name == 'towerEndBattle' ||
  1994. call.name == 'invasion_bossEnd' ||
  1995. call.name == 'titanArenaEndBattle' ||
  1996. call.name == 'bossEndBattle' ||
  1997. call.name == 'clanRaid_endNodeBattle') &&
  1998. isCancalBattle) {
  1999. nameFuncEndBattle = call.name;
  2000.  
  2001. if (isChecked('tryFixIt_v2') &&
  2002. !call.args.result.win &&
  2003. (call.name == 'brawl_endBattle' ||
  2004. //call.name == 'crossClanWar_endBattle' ||
  2005. call.name == 'epicBrawl_endBattle' ||
  2006. //call.name == 'clanWarEndBattle' ||
  2007. call.name == 'adventure_endBattle' ||
  2008. call.name == 'titanArenaEndBattle' ||
  2009. call.name == 'bossEndBattle' ||
  2010. call.name == 'adventureSolo_endBattle') &&
  2011. lastBattleInfo) {
  2012. const noFixWin = call.name == 'clanWarEndBattle' || call.name == 'crossClanWar_endBattle';
  2013. const cloneBattle = structuredClone(lastBattleInfo);
  2014. lastBattleInfo = null;
  2015. try {
  2016. const { BestOrWinFixBattle } = HWHClasses;
  2017. const bFix = new BestOrWinFixBattle(cloneBattle);
  2018. bFix.setNoMakeWin(noFixWin);
  2019. let endTime = Date.now() + 3e4;
  2020. if (endTime < cloneBattle.endTime) {
  2021. endTime = cloneBattle.endTime;
  2022. }
  2023. const result = await bFix.start(cloneBattle.endTime, 150);
  2024.  
  2025. if (result.result.win) {
  2026. call.args.result = result.result;
  2027. call.args.progress = result.progress;
  2028. changeRequest = true;
  2029. } else if (result.value) {
  2030. if (
  2031. await popup.confirm('Поражение<br>Лучший результат: ' + result.value + '%', [
  2032. { msg: 'Отмена', result: 0 },
  2033. { msg: 'Принять', result: 1 },
  2034. ])
  2035. ) {
  2036. call.args.result = result.result;
  2037. call.args.progress = result.progress;
  2038. changeRequest = true;
  2039. }
  2040. }
  2041. } catch (error) {
  2042. console.error(error);
  2043. }
  2044. }
  2045.  
  2046. if (!call.args.result.win) {
  2047. let resultPopup = false;
  2048. if (call.name == 'adventure_endBattle' ||
  2049. //call.name == 'invasion_bossEnd' ||
  2050. call.name == 'bossEndBattle' ||
  2051. call.name == 'adventureSolo_endBattle') {
  2052. resultPopup = await showMsgs(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_CANCEL'), I18N('BTN_AUTO'));
  2053. } else if (call.name == 'clanWarEndBattle' ||
  2054. call.name == 'crossClanWar_endBattle') {
  2055. resultPopup = await showMsg(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_AUTO_F5'));
  2056. } else if (call.name !== 'epicBrawl_endBattle' && call.name !== 'titanArenaEndBattle') {
  2057. resultPopup = await showMsg(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_CANCEL'));
  2058. }
  2059. if (resultPopup) {
  2060. if (call.name == 'invasion_bossEnd') {
  2061. this.errorRequest = true;
  2062. }
  2063. fixBattle(call.args.progress[0].attackers.heroes);
  2064. fixBattle(call.args.progress[0].defenders.heroes);
  2065. changeRequest = true;
  2066. if (resultPopup > 1) {
  2067. this.onReadySuccess = testAutoBattle;
  2068. // setTimeout(bossBattle, 1000);
  2069. }
  2070. }
  2071. } else if (call.args.result.stars < 3 && call.name == 'towerEndBattle') {
  2072. resultPopup = await showMsg(I18N('LOST_HEROES'), I18N('BTN_OK'), I18N('BTN_CANCEL'), I18N('BTN_AUTO'));
  2073. if (resultPopup) {
  2074. fixBattle(call.args.progress[0].attackers.heroes);
  2075. fixBattle(call.args.progress[0].defenders.heroes);
  2076. changeRequest = true;
  2077. if (resultPopup > 1) {
  2078. this.onReadySuccess = testAutoBattle;
  2079. }
  2080. }
  2081. }
  2082. // Потасовки
  2083. if (isChecked('autoBrawls') && !isBrawlsAutoStart && call.name == 'brawl_endBattle') {}
  2084. }
  2085. /**
  2086. * Save pack for Brawls
  2087. *
  2088. * Сохраняем пачку для потасовок
  2089. */
  2090. if (isChecked('autoBrawls') && !isBrawlsAutoStart && call.name == 'brawl_startBattle') {
  2091. console.log(JSON.stringify(call.args));
  2092. brawlsPack = call.args;
  2093. if (
  2094. await popup.confirm(
  2095. I18N('START_AUTO_BRAWLS'),
  2096. [
  2097. { msg: I18N('BTN_NO'), result: false },
  2098. { msg: I18N('BTN_YES'), result: true },
  2099. ],
  2100. [
  2101. {
  2102. name: 'isAuto',
  2103. label: I18N('BRAWL_AUTO_PACK'),
  2104. checked: false,
  2105. },
  2106. ]
  2107. )
  2108. ) {
  2109. isBrawlsAutoStart = true;
  2110. const isAuto = popup.getCheckBoxes().find((e) => e.name === 'isAuto');
  2111. this.errorRequest = true;
  2112. testBrawls(isAuto.checked);
  2113. }
  2114. }
  2115. /**
  2116. * Canceled fight in Asgard
  2117. * Отмена боя в Асгарде
  2118. */
  2119. if (call.name == 'clanRaid_endBossBattle' && isChecked('cancelBattle')) {
  2120. const bossDamage = call.args.progress[0].defenders.heroes[1].extra;
  2121. let maxDamage = bossDamage.damageTaken + bossDamage.damageTakenNextLevel;
  2122. const lastDamage = maxDamage;
  2123.  
  2124. const testFunc = [];
  2125.  
  2126. if (testFuntions.masterFix) {
  2127. testFunc.push({ msg: 'masterFix', isInput: true, default: 100 });
  2128. }
  2129.  
  2130. const resultPopup = await popup.confirm(
  2131. `${I18N('MSG_YOU_APPLIED')} ${lastDamage.toLocaleString()} ${I18N('MSG_DAMAGE')}.`,
  2132. [
  2133. { msg: I18N('BTN_OK'), result: false },
  2134. { msg: I18N('BTN_AUTO_F5'), result: 1 },
  2135. { msg: I18N('BTN_TRY_FIX_IT'), result: 2 },
  2136. ...testFunc,
  2137. ],
  2138. [
  2139. {
  2140. name: 'isStat',
  2141. label: I18N('CALC_STAT'),
  2142. checked: false,
  2143. },
  2144. ]
  2145. );
  2146. if (resultPopup) {
  2147. if (resultPopup == 2) {
  2148. setProgress(I18N('LETS_FIX'), false);
  2149. await new Promise((e) => setTimeout(e, 0));
  2150. const cloneBattle = structuredClone(lastBossBattle);
  2151. const endTime = cloneBattle.endTime - 1e4;
  2152. console.log('fixBossBattleStart');
  2153.  
  2154. const { BossFixBattle } = HWHClasses;
  2155. const bFix = new BossFixBattle(cloneBattle);
  2156. const result = await bFix.start(endTime, 300);
  2157. console.log(result);
  2158.  
  2159. let msgResult = I18N('DAMAGE_NO_FIXED', {
  2160. lastDamage: lastDamage.toLocaleString()
  2161. });
  2162. if (result.value > lastDamage) {
  2163. call.args.result = result.result;
  2164. call.args.progress = result.progress;
  2165. msgResult = I18N('DAMAGE_FIXED', {
  2166. lastDamage: lastDamage.toLocaleString(),
  2167. maxDamage: result.value.toLocaleString(),
  2168. });
  2169. }
  2170. console.log(lastDamage, '>', result.value);
  2171. setProgress(
  2172. msgResult +
  2173. '<br/>' +
  2174. I18N('COUNT_FIXED', {
  2175. count: result.maxCount,
  2176. }),
  2177. false,
  2178. hideProgress
  2179. );
  2180. } else if (resultPopup > 3) {
  2181. const cloneBattle = structuredClone(lastBossBattle);
  2182. const { masterFixBattle } = HWHClasses;
  2183. const mFix = new masterFixBattle(cloneBattle);
  2184. const result = await mFix.start(cloneBattle.endTime, resultPopup);
  2185. console.log(result);
  2186. let msgResult = I18N('DAMAGE_NO_FIXED', {
  2187. lastDamage: lastDamage.toLocaleString(),
  2188. });
  2189. if (result.value > lastDamage) {
  2190. maxDamage = result.value;
  2191. call.args.result = result.result;
  2192. call.args.progress = result.progress;
  2193. msgResult = I18N('DAMAGE_FIXED', {
  2194. lastDamage: lastDamage.toLocaleString(),
  2195. maxDamage: maxDamage.toLocaleString(),
  2196. });
  2197. }
  2198. console.log('Урон:', lastDamage, maxDamage);
  2199. setProgress(msgResult, false, hideProgress);
  2200. } else {
  2201. fixBattle(call.args.progress[0].attackers.heroes);
  2202. fixBattle(call.args.progress[0].defenders.heroes);
  2203. }
  2204. changeRequest = true;
  2205. }
  2206. const isStat = popup.getCheckBoxes().find((e) => e.name === 'isStat');
  2207. if (isStat.checked) {
  2208. this.onReadySuccess = testBossBattle;
  2209. }
  2210. }
  2211. /**
  2212. * Save the Asgard Boss Attack Pack
  2213. * Сохраняем пачку для атаки босса Асгарда
  2214. */
  2215. if (call.name == 'clanRaid_startBossBattle') {
  2216. console.log(JSON.stringify(call.args));
  2217. }
  2218. /**
  2219. * Saving the request to start the last battle
  2220. * Сохранение запроса начала последнего боя
  2221. */
  2222. if (
  2223. call.name == 'clanWarAttack' ||
  2224. call.name == 'crossClanWar_startBattle' ||
  2225. call.name == 'adventure_turnStartBattle' ||
  2226. call.name == 'adventureSolo_turnStartBattle' ||
  2227. call.name == 'bossAttack' ||
  2228. call.name == 'invasion_bossStart' ||
  2229. call.name == 'towerStartBattle'
  2230. ) {
  2231. nameFuncStartBattle = call.name;
  2232. lastBattleArg = call.args;
  2233.  
  2234. if (call.name == 'invasion_bossStart') {
  2235. const timePassed = Date.now() - lastBossBattleStart;
  2236. if (timePassed < invasionTimer) {
  2237. await new Promise((e) => setTimeout(e, invasionTimer - timePassed));
  2238. }
  2239. invasionTimer -= 1;
  2240. }
  2241. lastBossBattleStart = Date.now();
  2242. }
  2243. if (call.name == 'invasion_bossEnd') {
  2244. const lastBattle = lastBattleInfo;
  2245. if (lastBattle && call.args.result.win) {
  2246. lastBattle.progress = call.args.progress;
  2247. const result = await Calc(lastBattle);
  2248. let timer = getTimer(result.battleTime, 1) + addBattleTimer;
  2249. const period = Math.ceil((Date.now() - lastBossBattleStart) / 1000);
  2250. console.log(timer, period);
  2251. if (period < timer) {
  2252. timer = timer - period;
  2253. await countdownTimer(timer);
  2254. }
  2255. }
  2256. }
  2257. /**
  2258. * Disable spending divination cards
  2259. * Отключить трату карт предсказаний
  2260. */
  2261. if (call.name == 'dungeonEndBattle') {
  2262. if (call.args.isRaid) {
  2263. if (countPredictionCard <= 0) {
  2264. delete call.args.isRaid;
  2265. changeRequest = true;
  2266. } else if (countPredictionCard > 0) {
  2267. countPredictionCard--;
  2268. }
  2269. }
  2270. console.log(`Cards: ${countPredictionCard}`);
  2271. /**
  2272. * Fix endless cards
  2273. * Исправление бесконечных карт
  2274. */
  2275. const lastBattle = lastDungeonBattleData;
  2276. if (lastBattle && !call.args.isRaid) {
  2277. if (changeRequest) {
  2278. lastBattle.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  2279. } else {
  2280. lastBattle.progress = call.args.progress;
  2281. }
  2282. const result = await Calc(lastBattle);
  2283.  
  2284. if (changeRequest) {
  2285. call.args.progress = result.progress;
  2286. call.args.result = result.result;
  2287. }
  2288. let timer = result.battleTimer + addBattleTimer;
  2289. const period = Math.ceil((Date.now() - lastDungeonBattleStart) / 1000);
  2290. console.log(timer, period);
  2291. if (period < timer) {
  2292. timer = timer - period;
  2293. await countdownTimer(timer);
  2294. }
  2295. }
  2296. }
  2297. /**
  2298. * Quiz Answer
  2299. * Ответ на викторину
  2300. */
  2301. if (call.name == 'quizAnswer') {
  2302. /**
  2303. * Automatically changes the answer to the correct one if there is one.
  2304. * Автоматически меняет ответ на правильный если он есть
  2305. */
  2306. if (lastAnswer && isChecked('getAnswer')) {
  2307. call.args.answerId = lastAnswer;
  2308. lastAnswer = null;
  2309. changeRequest = true;
  2310. }
  2311. }
  2312. /**
  2313. * Present
  2314. * Подарки
  2315. */
  2316. if (call.name == 'freebieCheck') {
  2317. freebieCheckInfo = call;
  2318. }
  2319. /** missionTimer */
  2320. if (call.name == 'missionEnd' && missionBattle) {
  2321. let startTimer = false;
  2322. if (!call.args.result.win) {
  2323. startTimer = await popup.confirm(I18N('DEFEAT_TURN_TIMER'), [
  2324. { msg: I18N('BTN_NO'), result: false },
  2325. { msg: I18N('BTN_YES'), result: true },
  2326. ]);
  2327. }
  2328.  
  2329. if (call.args.result.win || startTimer) {
  2330. missionBattle.progress = call.args.progress;
  2331. missionBattle.result = call.args.result;
  2332. const result = await Calc(missionBattle);
  2333.  
  2334. let timer = result.battleTimer + addBattleTimer;
  2335. const period = Math.ceil((Date.now() - lastMissionBattleStart) / 1000);
  2336. if (period < timer) {
  2337. timer = timer - period;
  2338. await countdownTimer(timer);
  2339. }
  2340. missionBattle = null;
  2341. } else {
  2342. this.errorRequest = true;
  2343. }
  2344. }
  2345. /**
  2346. * Getting mission data for auto-repeat
  2347. * Получение данных миссии для автоповтора
  2348. */
  2349. if (isChecked('repeatMission') &&
  2350. call.name == 'missionEnd') {
  2351. let missionInfo = {
  2352. id: call.args.id,
  2353. result: call.args.result,
  2354. heroes: call.args.progress[0].attackers.heroes,
  2355. count: 0,
  2356. }
  2357. setTimeout(async () => {
  2358. if (!isSendsMission && await popup.confirm(I18N('MSG_REPEAT_MISSION'), [
  2359. { msg: I18N('BTN_REPEAT'), result: true},
  2360. { msg: I18N('BTN_NO'), result: false},
  2361. ])) {
  2362. isStopSendMission = false;
  2363. isSendsMission = true;
  2364. sendsMission(missionInfo);
  2365. }
  2366. }, 0);
  2367. }
  2368. /**
  2369. * Getting mission data
  2370. * Получение данных миссии
  2371. * missionTimer
  2372. */
  2373. if (call.name == 'missionStart') {
  2374. lastMissionStart = call.args;
  2375. lastMissionBattleStart = Date.now();
  2376. }
  2377. /**
  2378. * Specify the quantity for Titan Orbs and Pet Eggs
  2379. * Указать количество для сфер титанов и яиц петов
  2380. */
  2381. if (isChecked('countControl') &&
  2382. (call.name == 'pet_chestOpen' ||
  2383. call.name == 'titanUseSummonCircle') &&
  2384. call.args.amount > 1) {
  2385. const startAmount = call.args.amount;
  2386. const result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2387. { msg: I18N('BTN_OPEN'), isInput: true, default: 1},
  2388. ]);
  2389. if (result) {
  2390. const item = call.name == 'pet_chestOpen' ? { id: 90, type: 'consumable' } : { id: 13, type: 'coin' };
  2391. cheats.updateInventory({
  2392. [item.type]: {
  2393. [item.id]: -(result - startAmount),
  2394. },
  2395. });
  2396. call.args.amount = result;
  2397. changeRequest = true;
  2398. }
  2399. }
  2400. /**
  2401. * Specify the amount for keys and spheres of titan artifacts
  2402. * Указать колличество для ключей и сфер артефактов титанов
  2403. */
  2404. if (isChecked('countControl') &&
  2405. (call.name == 'artifactChestOpen' ||
  2406. call.name == 'titanArtifactChestOpen') &&
  2407. call.args.amount > 1 &&
  2408. call.args.free &&
  2409. !changeRequest) {
  2410. artifactChestOpenCallName = call.name;
  2411. const startAmount = call.args.amount;
  2412. let result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2413. { msg: I18N('BTN_OPEN'), isInput: true, default: 1 },
  2414. ]);
  2415. if (result) {
  2416. const openChests = result;
  2417. let sphere = result < 10 ? 1 : 10;
  2418. call.args.amount = sphere;
  2419. for (let count = openChests - sphere; count > 0; count -= sphere) {
  2420. if (count < 10) sphere = 1;
  2421. const ident = artifactChestOpenCallName + "_" + count;
  2422. testData.calls.push({
  2423. name: artifactChestOpenCallName,
  2424. args: {
  2425. amount: sphere,
  2426. free: true,
  2427. },
  2428. ident: ident
  2429. });
  2430. if (!Array.isArray(requestHistory[this.uniqid].calls[call.name])) {
  2431. requestHistory[this.uniqid].calls[call.name] = [requestHistory[this.uniqid].calls[call.name]];
  2432. }
  2433. requestHistory[this.uniqid].calls[call.name].push(ident);
  2434. }
  2435.  
  2436. const consumableId = call.name == 'artifactChestOpen' ? 45 : 55;
  2437. cheats.updateInventory({
  2438. consumable: {
  2439. [consumableId]: -(openChests - startAmount),
  2440. },
  2441. });
  2442. artifactChestOpen = true;
  2443. changeRequest = true;
  2444. }
  2445. }
  2446. if (call.name == 'consumableUseLootBox') {
  2447. lastRussianDollId = call.args.libId;
  2448. /**
  2449. * Specify quantity for gold caskets
  2450. * Указать количество для золотых шкатулок
  2451. */
  2452. if (isChecked('countControl') &&
  2453. call.args.libId == 148 &&
  2454. call.args.amount > 1) {
  2455. const result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2456. { msg: I18N('BTN_OPEN'), isInput: true, default: call.args.amount},
  2457. ]);
  2458. call.args.amount = result;
  2459. changeRequest = true;
  2460. }
  2461. if (isChecked('countControl') && call.args.libId >= 362 && call.args.libId <= 389) {
  2462. this.massOpen = call.args.libId;
  2463. }
  2464. }
  2465. if (call.name == 'invasion_bossStart' && isChecked('tryFixIt_v2') && call.args.id == 217) {
  2466. const pack = invasionDataPacks[invasionInfo.bossLvl];
  2467. if (pack.buff != invasionInfo.buff) {
  2468. setProgress(
  2469. I18N('INVASION_BOSS_BUFF', {
  2470. bossLvl: invasionInfo.bossLvl,
  2471. needBuff: pack.buff,
  2472. haveBuff: invasionInfo.buff,
  2473. }),
  2474. false
  2475. );
  2476. } else {
  2477. call.args.pet = pack.pet;
  2478. call.args.heroes = pack.heroes;
  2479. call.args.favor = pack.favor;
  2480. changeRequest = true;
  2481. }
  2482. }
  2483. /**
  2484. * Changing the maximum number of raids in the campaign
  2485. * Изменение максимального количества рейдов в кампании
  2486. */
  2487. // if (call.name == 'missionRaid') {
  2488. // if (isChecked('countControl') && call.args.times > 1) {
  2489. // const result = +(await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2490. // { msg: I18N('BTN_RUN'), isInput: true, default: call.args.times },
  2491. // ]));
  2492. // call.args.times = result > call.args.times ? call.args.times : result;
  2493. // changeRequest = true;
  2494. // }
  2495. // }
  2496. }
  2497.  
  2498. let headers = requestHistory[this.uniqid].headers;
  2499. if (changeRequest) {
  2500. sourceData = JSON.stringify(testData);
  2501. headers['X-Auth-Signature'] = getSignature(headers, sourceData);
  2502. }
  2503.  
  2504. let signature = headers['X-Auth-Signature'];
  2505. if (signature) {
  2506. original.setRequestHeader.call(this, 'X-Auth-Signature', signature);
  2507. }
  2508. } catch (err) {
  2509. console.log("Request(send, " + this.uniqid + "):\n", sourceData, "Error:\n", err);
  2510. }
  2511. return sourceData;
  2512. }
  2513. /**
  2514. * Processing and substitution of incoming data
  2515. *
  2516. * Обработка и подмена входящих данных
  2517. */
  2518. async function checkChangeResponse(response) {
  2519. try {
  2520. isChange = false;
  2521. let nowTime = Math.round(Date.now() / 1000);
  2522. callsIdent = requestHistory[this.uniqid].calls;
  2523. respond = JSON.parse(response);
  2524. /**
  2525. * If the request returned an error removes the error (removes synchronization errors)
  2526. * Если запрос вернул ошибку удаляет ошибку (убирает ошибки синхронизации)
  2527. */
  2528. if (respond.error) {
  2529. isChange = true;
  2530. console.error(respond.error);
  2531. if (isChecked('showErrors')) {
  2532. popup.confirm(I18N('ERROR_MSG', {
  2533. name: respond.error.name,
  2534. description: respond.error.description,
  2535. }));
  2536. }
  2537. if (respond.error.name != 'AccountBan') {
  2538. delete respond.error;
  2539. respond.results = [];
  2540. }
  2541. }
  2542. let mainReward = null;
  2543. const allReward = {};
  2544. let countTypeReward = 0;
  2545. let readQuestInfo = false;
  2546. for (const call of respond.results) {
  2547. /**
  2548. * Obtaining initial data for completing quests
  2549. * Получение исходных данных для выполнения квестов
  2550. */
  2551. if (readQuestInfo) {
  2552. questsInfo[call.ident] = call.result.response;
  2553. }
  2554. /**
  2555. * Getting a user ID
  2556. * Получение идетификатора пользователя
  2557. */
  2558. if (call.ident == callsIdent['registration']) {
  2559. userId = call.result.response.userId;
  2560. if (localStorage['userId'] != userId) {
  2561. localStorage['newGiftSendIds'] = '';
  2562. localStorage['userId'] = userId;
  2563. }
  2564. await openOrMigrateDatabase(userId);
  2565. readQuestInfo = true;
  2566. }
  2567. /**
  2568. * Hiding donation offers 1
  2569. * Скрываем предложения доната 1
  2570. */
  2571. if (call.ident == callsIdent['billingGetAll'] && getSaveVal('noOfferDonat')) {
  2572. const billings = call.result.response?.billings;
  2573. const bundle = call.result.response?.bundle;
  2574. if (billings && bundle) {
  2575. call.result.response.billings = call.result.response.billings.filter((e) => ['repeatableOffer'].includes(e.type));
  2576. call.result.response.bundle = [];
  2577. isChange = true;
  2578. }
  2579. }
  2580. /**
  2581. * Hiding donation offers 2
  2582. * Скрываем предложения доната 2
  2583. */
  2584. if (getSaveVal('noOfferDonat') &&
  2585. (call.ident == callsIdent['offerGetAll'] ||
  2586. call.ident == callsIdent['specialOffer_getAll'])) {
  2587. let offers = call.result.response;
  2588. if (offers) {
  2589. call.result.response = offers.filter(
  2590. (e) => !['addBilling', 'bundleCarousel'].includes(e.type) || ['idleResource', 'stagesOffer'].includes(e.offerType)
  2591. );
  2592. isChange = true;
  2593. }
  2594. }
  2595. /**
  2596. * Hiding donation offers 3
  2597. * Скрываем предложения доната 3
  2598. */
  2599. if (getSaveVal('noOfferDonat') && call.result?.bundleUpdate) {
  2600. delete call.result.bundleUpdate;
  2601. isChange = true;
  2602. }
  2603. /**
  2604. * Hiding donation offers 4
  2605. * Скрываем предложения доната 4
  2606. */
  2607. if (call.result?.specialOffers) {
  2608. const offers = call.result.specialOffers;
  2609. call.result.specialOffers = offers.filter(
  2610. (e) => !['addBilling', 'bundleCarousel'].includes(e.type) || ['idleResource', 'stagesOffer'].includes(e.offerType)
  2611. );
  2612. isChange = true;
  2613. }
  2614. /**
  2615. * Copies a quiz question to the clipboard
  2616. * Копирует вопрос викторины в буфер обмена и получает на него ответ если есть
  2617. */
  2618. if (call.ident == callsIdent['quizGetNewQuestion']) {
  2619. let quest = call.result.response;
  2620. console.log(quest.question);
  2621. copyText(quest.question);
  2622. setProgress(I18N('QUESTION_COPY'), true);
  2623. quest.lang = null;
  2624. if (typeof NXFlashVars !== 'undefined') {
  2625. quest.lang = NXFlashVars.interface_lang;
  2626. }
  2627. lastQuestion = quest;
  2628. if (isChecked('getAnswer')) {
  2629. const answer = await getAnswer(lastQuestion);
  2630. let showText = '';
  2631. if (answer) {
  2632. lastAnswer = answer;
  2633. console.log(answer);
  2634. showText = `${I18N('ANSWER_KNOWN')}: ${answer}`;
  2635. } else {
  2636. showText = I18N('ANSWER_NOT_KNOWN');
  2637. }
  2638.  
  2639. try {
  2640. const hint = hintQuest(quest);
  2641. if (hint) {
  2642. showText += I18N('HINT') + hint;
  2643. }
  2644. } catch(e) {}
  2645.  
  2646. setProgress(showText, true);
  2647. }
  2648. }
  2649. /**
  2650. * Submits a question with an answer to the database
  2651. * Отправляет вопрос с ответом в базу данных
  2652. */
  2653. if (call.ident == callsIdent['quizAnswer']) {
  2654. const answer = call.result.response;
  2655. if (lastQuestion) {
  2656. const answerInfo = {
  2657. answer,
  2658. question: lastQuestion,
  2659. lang: null,
  2660. }
  2661. if (typeof NXFlashVars !== 'undefined') {
  2662. answerInfo.lang = NXFlashVars.interface_lang;
  2663. }
  2664. lastQuestion = null;
  2665. setTimeout(sendAnswerInfo, 0, answerInfo);
  2666. }
  2667. }
  2668. /**
  2669. * Get user data
  2670. * Получить даныне пользователя
  2671. */
  2672. if (call.ident == callsIdent['userGetInfo']) {
  2673. let user = call.result.response;
  2674. document.title = user.name;
  2675. userInfo = Object.assign({}, user);
  2676. delete userInfo.refillable;
  2677. if (!questsInfo['userGetInfo']) {
  2678. questsInfo['userGetInfo'] = user;
  2679. }
  2680. }
  2681. /**
  2682. * Start of the battle for recalculation
  2683. * Начало боя для прерасчета
  2684. */
  2685. if (call.ident == callsIdent['clanWarAttack'] ||
  2686. call.ident == callsIdent['crossClanWar_startBattle'] ||
  2687. call.ident == callsIdent['bossAttack'] ||
  2688. call.ident == callsIdent['battleGetReplay'] ||
  2689. call.ident == callsIdent['brawl_startBattle'] ||
  2690. call.ident == callsIdent['adventureSolo_turnStartBattle'] ||
  2691. call.ident == callsIdent['invasion_bossStart'] ||
  2692. call.ident == callsIdent['titanArenaStartBattle'] ||
  2693. call.ident == callsIdent['towerStartBattle'] ||
  2694. call.ident == callsIdent['epicBrawl_startBattle'] ||
  2695. call.ident == callsIdent['adventure_turnStartBattle']) {
  2696. let battle = call.result.response.battle || call.result.response.replay;
  2697. if (call.ident == callsIdent['brawl_startBattle'] ||
  2698. call.ident == callsIdent['bossAttack'] ||
  2699. call.ident == callsIdent['towerStartBattle'] ||
  2700. call.ident == callsIdent['invasion_bossStart']) {
  2701. battle = call.result.response;
  2702. }
  2703. lastBattleInfo = battle;
  2704. if (call.ident == callsIdent['battleGetReplay'] && call.result.response.replay.type === "clan_raid") {
  2705. if (call?.result?.response?.replay?.result?.damage) {
  2706. const damages = Object.values(call.result.response.replay.result.damage);
  2707. const bossDamage = damages.reduce((a, v) => a + v, 0);
  2708. setProgress(I18N('BOSS_DAMAGE') + bossDamage.toLocaleString(), false, hideProgress);
  2709. continue;
  2710. }
  2711. }
  2712. if (!isChecked('preCalcBattle')) {
  2713. continue;
  2714. }
  2715. const preCalcBattle = structuredClone(battle);
  2716. setProgress(I18N('BEING_RECALC'));
  2717. let battleDuration = 120;
  2718. try {
  2719. const typeBattle = getBattleType(preCalcBattle.type);
  2720. battleDuration = +lib.data.battleConfig[typeBattle.split('_')[1]].config.battleDuration;
  2721. } catch (e) { }
  2722. //console.log(battle.type);
  2723. function getBattleInfo(battle, isRandSeed) {
  2724. return new Promise(function (resolve) {
  2725. if (isRandSeed) {
  2726. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  2727. }
  2728. BattleCalc(battle, getBattleType(battle.type), e => resolve(e));
  2729. });
  2730. }
  2731. let actions = [getBattleInfo(preCalcBattle, false)];
  2732. let countTestBattle = getInput('countTestBattle');
  2733. if (call.ident == callsIdent['invasion_bossStart'] ) {
  2734. countTestBattle = 0;
  2735. }
  2736. if (call.ident == callsIdent['battleGetReplay']) {
  2737. preCalcBattle.progress = [{ attackers: { input: ['auto', 0, 0, 'auto', 0, 0] } }];
  2738. }
  2739. for (let i = 0; i < countTestBattle; i++) {
  2740. actions.push(getBattleInfo(preCalcBattle, true));
  2741. }
  2742. Promise.all(actions)
  2743. .then(e => {
  2744. e = e.map(n => ({win: n.result.win, time: n.battleTime}));
  2745. let firstBattle = e.shift();
  2746. const timer = Math.floor(battleDuration - firstBattle.time);
  2747. const min = ('00' + Math.floor(timer / 60)).slice(-2);
  2748. const sec = ('00' + Math.floor(timer - min * 60)).slice(-2);
  2749. let msg = `${I18N('THIS_TIME')} ${firstBattle.win ? I18N('VICTORY') : I18N('DEFEAT')}`;
  2750. if (e.length) {
  2751. const countWin = e.reduce((w, s) => w + s.win, 0);
  2752. msg += ` ${I18N('CHANCE_TO_WIN')}: ${Math.floor((countWin / e.length) * 100)}% (${e.length})`;
  2753. }
  2754. msg += `, ${min}:${sec}`
  2755. setProgress(msg, false, hideProgress)
  2756. });
  2757. }
  2758. /**
  2759. * Start of the Asgard boss fight
  2760. * Начало боя с боссом Асгарда
  2761. */
  2762. if (call.ident == callsIdent['clanRaid_startBossBattle']) {
  2763. lastBossBattle = call.result.response.battle;
  2764. lastBossBattle.endTime = Date.now() + 160 * 1000;
  2765. if (isChecked('preCalcBattle')) {
  2766. const result = await Calc(lastBossBattle).then(e => e.progress[0].defenders.heroes[1].extra);
  2767. const bossDamage = result.damageTaken + result.damageTakenNextLevel;
  2768. setProgress(I18N('BOSS_DAMAGE') + bossDamage.toLocaleString(), false, hideProgress);
  2769. }
  2770. }
  2771. /**
  2772. * Cancel tutorial
  2773. * Отмена туториала
  2774. */
  2775. if (isCanceledTutorial && call.ident == callsIdent['tutorialGetInfo']) {
  2776. let chains = call.result.response.chains;
  2777. for (let n in chains) {
  2778. chains[n] = 9999;
  2779. }
  2780. isChange = true;
  2781. }
  2782. /**
  2783. * Opening keys and spheres of titan artifacts
  2784. * Открытие ключей и сфер артефактов титанов
  2785. */
  2786. if (artifactChestOpen &&
  2787. (call.ident == callsIdent[artifactChestOpenCallName] ||
  2788. (callsIdent[artifactChestOpenCallName] && callsIdent[artifactChestOpenCallName].includes(call.ident)))) {
  2789. let reward = call.result.response[artifactChestOpenCallName == 'artifactChestOpen' ? 'chestReward' : 'reward'];
  2790.  
  2791. reward.forEach(e => {
  2792. for (let f in e) {
  2793. if (!allReward[f]) {
  2794. allReward[f] = {};
  2795. }
  2796. for (let o in e[f]) {
  2797. if (!allReward[f][o]) {
  2798. allReward[f][o] = e[f][o];
  2799. countTypeReward++;
  2800. } else {
  2801. allReward[f][o] += e[f][o];
  2802. }
  2803. }
  2804. }
  2805. });
  2806.  
  2807. if (!call.ident.includes(artifactChestOpenCallName)) {
  2808. mainReward = call.result.response;
  2809. }
  2810. }
  2811.  
  2812. if (countTypeReward > 20) {
  2813. correctShowOpenArtifact = 3;
  2814. } else {
  2815. correctShowOpenArtifact = 0;
  2816. }
  2817. /**
  2818. * Sum the result of opening Pet Eggs
  2819. * Суммирование результата открытия яиц питомцев
  2820. */
  2821. if (isChecked('countControl') && call.ident == callsIdent['pet_chestOpen']) {
  2822. const rewards = call.result.response.rewards;
  2823. if (rewards.length > 10) {
  2824. /**
  2825. * Removing pet cards
  2826. * Убираем карточки петов
  2827. */
  2828. for (const reward of rewards) {
  2829. if (reward.petCard) {
  2830. delete reward.petCard;
  2831. }
  2832. }
  2833. }
  2834. rewards.forEach(e => {
  2835. for (let f in e) {
  2836. if (!allReward[f]) {
  2837. allReward[f] = {};
  2838. }
  2839. for (let o in e[f]) {
  2840. if (!allReward[f][o]) {
  2841. allReward[f][o] = e[f][o];
  2842. } else {
  2843. allReward[f][o] += e[f][o];
  2844. }
  2845. }
  2846. }
  2847. });
  2848. call.result.response.rewards = [allReward];
  2849. isChange = true;
  2850. }
  2851. /**
  2852. * Removing titan cards
  2853. * Убираем карточки титанов
  2854. */
  2855. if (call.ident == callsIdent['titanUseSummonCircle']) {
  2856. if (call.result.response.rewards.length > 10) {
  2857. for (const reward of call.result.response.rewards) {
  2858. if (reward.titanCard) {
  2859. delete reward.titanCard;
  2860. }
  2861. }
  2862. isChange = true;
  2863. }
  2864. }
  2865. /**
  2866. * Auto-repeat opening matryoshkas
  2867. * АвтоПовтор открытия матрешек
  2868. */
  2869. if (isChecked('countControl') && call.ident == callsIdent['consumableUseLootBox']) {
  2870. let [countLootBox, lootBox] = Object.entries(call.result.response).pop();
  2871. countLootBox = +countLootBox;
  2872. let newCount = 0;
  2873. if (lootBox?.consumable && lootBox.consumable[lastRussianDollId]) {
  2874. newCount += lootBox.consumable[lastRussianDollId];
  2875. delete lootBox.consumable[lastRussianDollId];
  2876. }
  2877. if (
  2878. newCount &&
  2879. (await popup.confirm(`${I18N('BTN_OPEN')} ${newCount} ${I18N('OPEN_DOLLS')}?`, [
  2880. { msg: I18N('BTN_OPEN'), result: true },
  2881. { msg: I18N('BTN_NO'), result: false, isClose: true },
  2882. ]))
  2883. ) {
  2884. const [count, recursionResult] = await openRussianDolls(lastRussianDollId, newCount);
  2885. countLootBox += +count;
  2886. mergeItemsObj(lootBox, recursionResult);
  2887. isChange = true;
  2888. }
  2889.  
  2890. if (this.massOpen) {
  2891. if (
  2892. await popup.confirm(I18N('OPEN_ALL_EQUIP_BOXES'), [
  2893. { msg: I18N('BTN_OPEN'), result: true },
  2894. { msg: I18N('BTN_NO'), result: false, isClose: true },
  2895. ])
  2896. ) {
  2897. const consumable = await Send({ calls: [{ name: 'inventoryGet', args: {}, ident: 'inventoryGet' }] }).then((e) =>
  2898. Object.entries(e.results[0].result.response.consumable)
  2899. );
  2900. const calls = [];
  2901. const deleteItems = {};
  2902. for (const [libId, amount] of consumable) {
  2903. if (libId != this.massOpen && libId >= 362 && libId <= 389) {
  2904. calls.push({
  2905. name: 'consumableUseLootBox',
  2906. args: { libId, amount },
  2907. ident: 'consumableUseLootBox_' + libId,
  2908. });
  2909. deleteItems[libId] = -amount;
  2910. }
  2911. }
  2912. const responses = await Send({ calls }).then((e) => e.results.map((r) => r.result.response).flat());
  2913.  
  2914. for (const loot of responses) {
  2915. const [count, result] = Object.entries(loot).pop();
  2916. countLootBox += +count;
  2917.  
  2918. mergeItemsObj(lootBox, result);
  2919. }
  2920. isChange = true;
  2921.  
  2922. this.onReadySuccess = () => {
  2923. cheats.updateInventory({ consumable: deleteItems });
  2924. cheats.refreshInventory();
  2925. };
  2926. }
  2927. }
  2928.  
  2929. if (isChange) {
  2930. call.result.response = {
  2931. [countLootBox]: lootBox,
  2932. };
  2933. }
  2934. }
  2935. /**
  2936. * Dungeon recalculation (fix endless cards)
  2937. * Прерасчет подземки (исправление бесконечных карт)
  2938. */
  2939. if (call.ident == callsIdent['dungeonStartBattle']) {
  2940. lastDungeonBattleData = call.result.response;
  2941. lastDungeonBattleStart = Date.now();
  2942. }
  2943. /**
  2944. * Getting the number of prediction cards
  2945. * Получение количества карт предсказаний
  2946. */
  2947. if (call.ident == callsIdent['inventoryGet']) {
  2948. countPredictionCard = call.result.response.consumable[81] || 0;
  2949. }
  2950. /**
  2951. * Getting subscription status
  2952. * Получение состояния подписки
  2953. */
  2954. if (call.ident == callsIdent['subscriptionGetInfo']) {
  2955. const subscription = call.result.response.subscription;
  2956. if (subscription) {
  2957. subEndTime = subscription.endTime * 1000;
  2958. }
  2959. }
  2960. /**
  2961. * Getting prediction cards
  2962. * Получение карт предсказаний
  2963. */
  2964. if (call.ident == callsIdent['questFarm']) {
  2965. const consumable = call.result.response?.consumable;
  2966. if (consumable && consumable[81]) {
  2967. countPredictionCard += consumable[81];
  2968. console.log(`Cards: ${countPredictionCard}`);
  2969. }
  2970. }
  2971. /**
  2972. * Hiding extra servers
  2973. * Скрытие лишних серверов
  2974. */
  2975. if (call.ident == callsIdent['serverGetAll'] && isChecked('hideServers')) {
  2976. let servers = call.result.response.users.map(s => s.serverId)
  2977. call.result.response.servers = call.result.response.servers.filter(s => servers.includes(s.id));
  2978. isChange = true;
  2979. }
  2980. /**
  2981. * Displays player positions in the adventure
  2982. * Отображает позиции игроков в приключении
  2983. */
  2984. if (call.ident == callsIdent['adventure_getLobbyInfo']) {
  2985. const users = Object.values(call.result.response.users);
  2986. const mapIdent = call.result.response.mapIdent;
  2987. const adventureId = call.result.response.adventureId;
  2988. const maps = {
  2989. adv_strongford_3pl_hell: 9,
  2990. adv_valley_3pl_hell: 10,
  2991. adv_ghirwil_3pl_hell: 11,
  2992. adv_angels_3pl_hell: 12,
  2993. }
  2994. let msg = I18N('MAP') + (mapIdent in maps ? maps[mapIdent] : adventureId);
  2995. msg += '<br>' + I18N('PLAYER_POS');
  2996. for (const user of users) {
  2997. msg += `<br>${user.user.name} - ${user.currentNode}`;
  2998. }
  2999. setProgress(msg, false, hideProgress);
  3000. }
  3001. /**
  3002. * Automatic launch of a raid at the end of the adventure
  3003. * Автоматический запуск рейда при окончании приключения
  3004. */
  3005. if (call.ident == callsIdent['adventure_end']) {
  3006. autoRaidAdventure()
  3007. }
  3008. /** Удаление лавки редкостей */
  3009. if (call.ident == callsIdent['missionRaid']) {
  3010. if (call.result?.heroesMerchant) {
  3011. delete call.result.heroesMerchant;
  3012. isChange = true;
  3013. }
  3014. }
  3015. /** missionTimer */
  3016. if (call.ident == callsIdent['missionStart']) {
  3017. missionBattle = call.result.response;
  3018. }
  3019. /** Награды турнира стихий */
  3020. if (call.ident == callsIdent['hallOfFameGetTrophies']) {
  3021. const trophys = call.result.response;
  3022. const calls = [];
  3023. for (const week in trophys) {
  3024. const trophy = trophys[week];
  3025. if (!trophy.championRewardFarmed) {
  3026. calls.push({
  3027. name: 'hallOfFameFarmTrophyReward',
  3028. args: { trophyId: week, rewardType: 'champion' },
  3029. ident: 'body_champion_' + week,
  3030. });
  3031. }
  3032. if (Object.keys(trophy.clanReward).length && !trophy.clanRewardFarmed) {
  3033. calls.push({
  3034. name: 'hallOfFameFarmTrophyReward',
  3035. args: { trophyId: week, rewardType: 'clan' },
  3036. ident: 'body_clan_' + week,
  3037. });
  3038. }
  3039. }
  3040. if (calls.length) {
  3041. Send({ calls })
  3042. .then((e) => e.results.map((e) => e.result.response))
  3043. .then(async results => {
  3044. let coin18 = 0,
  3045. coin19 = 0,
  3046. gold = 0,
  3047. starmoney = 0;
  3048. for (const r of results) {
  3049. coin18 += r?.coin ? +r.coin[18] : 0;
  3050. coin19 += r?.coin ? +r.coin[19] : 0;
  3051. gold += r?.gold ? +r.gold : 0;
  3052. starmoney += r?.starmoney ? +r.starmoney : 0;
  3053. }
  3054.  
  3055. let msg = I18N('ELEMENT_TOURNAMENT_REWARD') + '<br>';
  3056. if (coin18) {
  3057. msg += cheats.translate('LIB_COIN_NAME_18') + `: ${coin18}<br>`;
  3058. }
  3059. if (coin19) {
  3060. msg += cheats.translate('LIB_COIN_NAME_19') + `: ${coin19}<br>`;
  3061. }
  3062. if (gold) {
  3063. msg += cheats.translate('LIB_PSEUDO_COIN') + `: ${gold}<br>`;
  3064. }
  3065. if (starmoney) {
  3066. msg += cheats.translate('LIB_PSEUDO_STARMONEY') + `: ${starmoney}<br>`;
  3067. }
  3068.  
  3069. await popup.confirm(msg, [{ msg: I18N('BTN_OK'), result: 0 }]);
  3070. });
  3071. }
  3072. }
  3073. if (call.ident == callsIdent['clanDomination_getInfo']) {
  3074. clanDominationGetInfo = call.result.response;
  3075. }
  3076. if (call.ident == callsIdent['clanRaid_endBossBattle']) {
  3077. console.log(call.result.response);
  3078. const damage = Object.values(call.result.response.damage).reduce((a, e) => a + e);
  3079. if (call.result.response.result.afterInvalid) {
  3080. addProgress('<br>' + I18N('SERVER_NOT_ACCEPT'));
  3081. }
  3082. addProgress('<br>Server > ' + I18N('BOSS_DAMAGE') + damage.toLocaleString());
  3083. }
  3084. if (call.ident == callsIdent['invasion_getInfo']) {
  3085. const r = call.result.response;
  3086. if (r?.actions?.length) {
  3087. const boss = r.actions.find((e) => e.payload.id === 217);
  3088. invasionInfo.buff = r.buffAmount;
  3089. invasionInfo.bossLvl = boss.payload.level;
  3090. if (isChecked('tryFixIt_v2')) {
  3091. const pack = invasionDataPacks[invasionInfo.bossLvl];
  3092. setProgress(
  3093. I18N('INVASION_BOSS_BUFF', {
  3094. bossLvl: invasionInfo.bossLvl,
  3095. needBuff: pack.buff,
  3096. haveBuff: invasionInfo.buff
  3097. }),
  3098. false
  3099. );
  3100. }
  3101. }
  3102. }
  3103. if (call.ident == callsIdent['workshopBuff_create']) {
  3104. const r = call.result.response;
  3105. if (r.id == 1) {
  3106. invasionInfo.buff = r.amount;
  3107. if (isChecked('tryFixIt_v2')) {
  3108. const pack = invasionDataPacks[invasionInfo.bossLvl];
  3109. setProgress(
  3110. I18N('INVASION_BOSS_BUFF', {
  3111. bossLvl: invasionInfo.bossLvl,
  3112. needBuff: pack.buff,
  3113. haveBuff: invasionInfo.buff,
  3114. }),
  3115. false
  3116. );
  3117. }
  3118. }
  3119. }
  3120. /*
  3121. if (call.ident == callsIdent['chatGetAll'] && call.args.chatType == 'clanDomination' && !callsIdent['clanDomination_mapState']) {
  3122. this.onReadySuccess = async function () {
  3123. const result = await Send({
  3124. calls: [
  3125. {
  3126. name: 'clanDomination_mapState',
  3127. args: {},
  3128. ident: 'clanDomination_mapState',
  3129. },
  3130. ],
  3131. }).then((e) => e.results[0].result.response);
  3132. let townPositions = result.townPositions;
  3133. let positions = {};
  3134. for (let pos in townPositions) {
  3135. let townPosition = townPositions[pos];
  3136. positions[townPosition.position] = townPosition;
  3137. }
  3138. Object.assign(clanDominationGetInfo, {
  3139. townPositions: positions,
  3140. });
  3141. let userPositions = result.userPositions;
  3142. for (let pos in clanDominationGetInfo.townPositions) {
  3143. let townPosition = clanDominationGetInfo.townPositions[pos];
  3144. if (townPosition.status) {
  3145. userPositions[townPosition.userId] = +pos;
  3146. }
  3147. }
  3148. cheats.updateMap(result);
  3149. };
  3150. }
  3151. if (call.ident == callsIdent['clanDomination_mapState']) {
  3152. const townPositions = call.result.response.townPositions;
  3153. const userPositions = call.result.response.userPositions;
  3154. for (let pos in townPositions) {
  3155. let townPos = townPositions[pos];
  3156. if (townPos.status) {
  3157. userPositions[townPos.userId] = townPos.position;
  3158. }
  3159. }
  3160. isChange = true;
  3161. }
  3162. */
  3163. }
  3164.  
  3165. if (mainReward && artifactChestOpen) {
  3166. console.log(allReward);
  3167. mainReward[artifactChestOpenCallName == 'artifactChestOpen' ? 'chestReward' : 'reward'] = [allReward];
  3168. artifactChestOpen = false;
  3169. artifactChestOpenCallName = '';
  3170. isChange = true;
  3171. }
  3172. } catch(err) {
  3173. console.log("Request(response, " + this.uniqid + "):\n", "Error:\n", response, err);
  3174. }
  3175.  
  3176. if (isChange) {
  3177. Object.defineProperty(this, 'responseText', {
  3178. writable: true
  3179. });
  3180. this.responseText = JSON.stringify(respond);
  3181. }
  3182. }
  3183.  
  3184. /**
  3185. * Request an answer to a question
  3186. *
  3187. * Запрос ответа на вопрос
  3188. */
  3189. async function getAnswer(question) {
  3190. // c29tZSBzdHJhbmdlIHN5bWJvbHM=
  3191. const quizAPI = new ZingerYWebsiteAPI('getAnswer.php', arguments, { question });
  3192. return new Promise((resolve, reject) => {
  3193. quizAPI.request().then((data) => {
  3194. if (data.result) {
  3195. resolve(data.result);
  3196. } else {
  3197. resolve(false);
  3198. }
  3199. }).catch((error) => {
  3200. console.error(error);
  3201. resolve(false);
  3202. });
  3203. })
  3204. }
  3205.  
  3206. /**
  3207. * Submitting a question and answer to a database
  3208. *
  3209. * Отправка вопроса и ответа в базу данных
  3210. */
  3211. function sendAnswerInfo(answerInfo) {
  3212. // c29tZSBub25zZW5zZQ==
  3213. const quizAPI = new ZingerYWebsiteAPI('setAnswer.php', arguments, { answerInfo });
  3214. quizAPI.request().then((data) => {
  3215. if (data.result) {
  3216. console.log(I18N('SENT_QUESTION'));
  3217. }
  3218. });
  3219. }
  3220.  
  3221. /**
  3222. * Returns the battle type by preset type
  3223. *
  3224. * Возвращает тип боя по типу пресета
  3225. */
  3226. function getBattleType(strBattleType) {
  3227. if (!strBattleType) {
  3228. return null;
  3229. }
  3230. switch (strBattleType) {
  3231. case 'titan_pvp':
  3232. return 'get_titanPvp';
  3233. case 'titan_pvp_manual':
  3234. case 'titan_clan_pvp':
  3235. case 'clan_pvp_titan':
  3236. case 'clan_global_pvp_titan':
  3237. case 'brawl_titan':
  3238. case 'challenge_titan':
  3239. case 'titan_mission':
  3240. return 'get_titanPvpManual';
  3241. case 'clan_raid': // Asgard Boss // Босс асгарда
  3242. case 'adventure': // Adventures // Приключения
  3243. case 'clan_global_pvp':
  3244. case 'epic_brawl':
  3245. case 'clan_pvp':
  3246. return 'get_clanPvp';
  3247. case 'dungeon_titan':
  3248. case 'titan_tower':
  3249. return 'get_titan';
  3250. case 'tower':
  3251. case 'clan_dungeon':
  3252. return 'get_tower';
  3253. case 'pve':
  3254. case 'mission':
  3255. return 'get_pve';
  3256. case 'mission_boss':
  3257. return 'get_missionBoss';
  3258. case 'challenge':
  3259. case 'pvp_manual':
  3260. return 'get_pvpManual';
  3261. case 'grand':
  3262. case 'arena':
  3263. case 'pvp':
  3264. case 'clan_domination':
  3265. return 'get_pvp';
  3266. case 'core':
  3267. return 'get_core';
  3268. default: {
  3269. if (strBattleType.includes('invasion')) {
  3270. return 'get_invasion';
  3271. }
  3272. if (strBattleType.includes('boss')) {
  3273. return 'get_boss';
  3274. }
  3275. if (strBattleType.includes('titan_arena')) {
  3276. return 'get_titanPvpManual';
  3277. }
  3278. return 'get_clanPvp';
  3279. }
  3280. }
  3281. }
  3282. /**
  3283. * Returns the class name of the passed object
  3284. *
  3285. * Возвращает название класса переданного объекта
  3286. */
  3287. function getClass(obj) {
  3288. return {}.toString.call(obj).slice(8, -1);
  3289. }
  3290. /**
  3291. * Calculates the request signature
  3292. *
  3293. * Расчитывает сигнатуру запроса
  3294. */
  3295. this.getSignature = function(headers, data) {
  3296. const sign = {
  3297. signature: '',
  3298. length: 0,
  3299. add: function (text) {
  3300. this.signature += text;
  3301. if (this.length < this.signature.length) {
  3302. this.length = 3 * (this.signature.length + 1) >> 1;
  3303. }
  3304. },
  3305. }
  3306. sign.add(headers["X-Request-Id"]);
  3307. sign.add(':');
  3308. sign.add(headers["X-Auth-Token"]);
  3309. sign.add(':');
  3310. sign.add(headers["X-Auth-Session-Id"]);
  3311. sign.add(':');
  3312. sign.add(data);
  3313. sign.add(':');
  3314. sign.add('LIBRARY-VERSION=1');
  3315. sign.add('UNIQUE-SESSION-ID=' + headers["X-Env-Unique-Session-Id"]);
  3316.  
  3317. return md5(sign.signature);
  3318. }
  3319.  
  3320. let extintionsList = [];
  3321. /**
  3322. * Creates an interface
  3323. *
  3324. * Создает интерфейс
  3325. */
  3326. function createInterface() {
  3327. popup.init();
  3328. scriptMenu.init({
  3329. showMenu: true
  3330. });
  3331. scriptMenu.addHeader(GM_info.script.name, justInfo);
  3332. const versionHeader = scriptMenu.addHeader('v' + GM_info.script.version);
  3333. if (extintionsList.length) {
  3334. versionHeader.title = '';
  3335. versionHeader.style.color = 'red';
  3336. for (const extintion of extintionsList) {
  3337. const { name, ver, author } = extintion;
  3338. versionHeader.title += name + ', v' + ver + ' by ' + author + '\n';
  3339. }
  3340. }
  3341. }
  3342.  
  3343. function addExtentionName(name, ver, author) {
  3344. extintionsList.push({
  3345. name,
  3346. ver,
  3347. author,
  3348. });
  3349. }
  3350.  
  3351. function addControls() {
  3352. createInterface();
  3353. const checkboxDetails = scriptMenu.addDetails(I18N('SETTINGS'));
  3354. for (let name in checkboxes) {
  3355. if (checkboxes[name].hide) {
  3356. continue;
  3357. }
  3358. checkboxes[name].cbox = scriptMenu.addCheckbox(checkboxes[name].label, checkboxes[name].title, checkboxDetails);
  3359. /**
  3360. * Getting the state of checkboxes from storage
  3361. * Получаем состояние чекбоксов из storage
  3362. */
  3363. let val = storage.get(name, null);
  3364. if (val != null) {
  3365. checkboxes[name].cbox.checked = val;
  3366. } else {
  3367. storage.set(name, checkboxes[name].default);
  3368. checkboxes[name].cbox.checked = checkboxes[name].default;
  3369. }
  3370. /**
  3371. * Tracing the change event of the checkbox for writing to storage
  3372. * Отсеживание события изменения чекбокса для записи в storage
  3373. */
  3374. checkboxes[name].cbox.dataset['name'] = name;
  3375. checkboxes[name].cbox.addEventListener('change', async function (event) {
  3376. const nameCheckbox = this.dataset['name'];
  3377. /*
  3378. if (this.checked && nameCheckbox == 'cancelBattle') {
  3379. this.checked = false;
  3380. if (await popup.confirm(I18N('MSG_BAN_ATTENTION'), [
  3381. { msg: I18N('BTN_NO_I_AM_AGAINST'), result: true },
  3382. { msg: I18N('BTN_YES_I_AGREE'), result: false },
  3383. ])) {
  3384. return;
  3385. }
  3386. this.checked = true;
  3387. }
  3388. */
  3389. storage.set(nameCheckbox, this.checked);
  3390. })
  3391. }
  3392.  
  3393. const inputDetails = scriptMenu.addDetails(I18N('VALUES'));
  3394. for (let name in inputs) {
  3395. inputs[name].input = scriptMenu.addInputText(inputs[name].title, false, inputDetails);
  3396. /**
  3397. * Get inputText state from storage
  3398. * Получаем состояние inputText из storage
  3399. */
  3400. let val = storage.get(name, null);
  3401. if (val != null) {
  3402. inputs[name].input.value = val;
  3403. } else {
  3404. storage.set(name, inputs[name].default);
  3405. inputs[name].input.value = inputs[name].default;
  3406. }
  3407. /**
  3408. * Tracing a field change event for a record in storage
  3409. * Отсеживание события изменения поля для записи в storage
  3410. */
  3411. inputs[name].input.dataset['name'] = name;
  3412. inputs[name].input.addEventListener('input', function () {
  3413. const inputName = this.dataset['name'];
  3414. let value = +this.value;
  3415. if (!value || Number.isNaN(value)) {
  3416. value = storage.get(inputName, inputs[inputName].default);
  3417. inputs[name].input.value = value;
  3418. }
  3419. storage.set(inputName, value);
  3420. })
  3421. }
  3422. }
  3423.  
  3424. /**
  3425. * Sending a request
  3426. *
  3427. * Отправка запроса
  3428. */
  3429. function send(json, callback, pr) {
  3430. if (typeof json == 'string') {
  3431. json = JSON.parse(json);
  3432. }
  3433. for (const call of json.calls) {
  3434. if (!call?.context?.actionTs) {
  3435. call.context = {
  3436. actionTs: Math.floor(performance.now())
  3437. }
  3438. }
  3439. }
  3440. json = JSON.stringify(json);
  3441. /**
  3442. * We get the headlines of the previous intercepted request
  3443. * Получаем заголовки предыдущего перехваченого запроса
  3444. */
  3445. let headers = lastHeaders;
  3446. /**
  3447. * We increase the header of the query Certifier by 1
  3448. * Увеличиваем заголовок идетификатора запроса на 1
  3449. */
  3450. headers["X-Request-Id"]++;
  3451. /**
  3452. * We calculate the title with the signature
  3453. * Расчитываем заголовок с сигнатурой
  3454. */
  3455. headers["X-Auth-Signature"] = getSignature(headers, json);
  3456. /**
  3457. * Create a new ajax request
  3458. * Создаем новый AJAX запрос
  3459. */
  3460. let xhr = new XMLHttpRequest;
  3461. /**
  3462. * Indicate the previously saved URL for API queries
  3463. * Указываем ранее сохраненный URL для API запросов
  3464. */
  3465. xhr.open('POST', apiUrl, true);
  3466. /**
  3467. * Add the function to the event change event
  3468. * Добавляем функцию к событию смены статуса запроса
  3469. */
  3470. xhr.onreadystatechange = function() {
  3471. /**
  3472. * If the result of the request is obtained, we call the flask function
  3473. * Если результат запроса получен вызываем колбек функцию
  3474. */
  3475. if(xhr.readyState == 4) {
  3476. callback(xhr.response, pr);
  3477. }
  3478. };
  3479. /**
  3480. * Indicate the type of request
  3481. * Указываем тип запроса
  3482. */
  3483. xhr.responseType = 'json';
  3484. /**
  3485. * We set the request headers
  3486. * Задаем заголовки запроса
  3487. */
  3488. for(let nameHeader in headers) {
  3489. let head = headers[nameHeader];
  3490. xhr.setRequestHeader(nameHeader, head);
  3491. }
  3492. /**
  3493. * Sending a request
  3494. * Отправляем запрос
  3495. */
  3496. xhr.send(json);
  3497. }
  3498.  
  3499. let hideTimeoutProgress = 0;
  3500. /**
  3501. * Hide progress
  3502. *
  3503. * Скрыть прогресс
  3504. */
  3505. function hideProgress(timeout) {
  3506. timeout = timeout || 0;
  3507. clearTimeout(hideTimeoutProgress);
  3508. hideTimeoutProgress = setTimeout(function () {
  3509. scriptMenu.setStatus('');
  3510. }, timeout);
  3511. }
  3512. /**
  3513. * Progress display
  3514. *
  3515. * Отображение прогресса
  3516. */
  3517. function setProgress(text, hide, onclick) {
  3518. scriptMenu.setStatus(text, onclick);
  3519. hide = hide || false;
  3520. if (hide) {
  3521. hideProgress(3000);
  3522. }
  3523. }
  3524.  
  3525. /**
  3526. * Progress added
  3527. *
  3528. * Дополнение прогресса
  3529. */
  3530. function addProgress(text) {
  3531. scriptMenu.addStatus(text);
  3532. }
  3533.  
  3534. /**
  3535. * Returns the timer value depending on the subscription
  3536. *
  3537. * Возвращает значение таймера в зависимости от подписки
  3538. */
  3539. function getTimer(time, div) {
  3540. let speedDiv = 5;
  3541. if (subEndTime < Date.now()) {
  3542. speedDiv = div || 1.5;
  3543. }
  3544. return Math.max(Math.ceil(time / speedDiv + 1.5), 4);
  3545. }
  3546.  
  3547. function startSlave() {
  3548. const { slaveFixBattle } = HWHClasses;
  3549. const sFix = new slaveFixBattle();
  3550. sFix.wsStart();
  3551. }
  3552.  
  3553. this.testFuntions = {
  3554. hideProgress,
  3555. setProgress,
  3556. addProgress,
  3557. masterFix: false,
  3558. startSlave,
  3559. };
  3560.  
  3561. this.HWHFuncs = {
  3562. send,
  3563. I18N,
  3564. isChecked,
  3565. getInput,
  3566. copyText,
  3567. confShow,
  3568. hideProgress,
  3569. setProgress,
  3570. addProgress,
  3571. getTimer,
  3572. addExtentionName,
  3573. getUserInfo,
  3574. setIsCancalBattle,
  3575. random,
  3576. };
  3577.  
  3578. this.HWHClasses = {
  3579. checkChangeSend,
  3580. checkChangeResponse,
  3581. };
  3582. /**
  3583. * Calculates HASH MD5 from string
  3584. *
  3585. * Расчитывает HASH MD5 из строки
  3586. *
  3587. * [js-md5]{@link https://github.com/emn178/js-md5}
  3588. *
  3589. * @namespace md5
  3590. * @version 0.7.3
  3591. * @author Chen, Yi-Cyuan [emn178@gmail.com]
  3592. * @copyright Chen, Yi-Cyuan 2014-2017
  3593. * @license MIT
  3594. */
  3595. !function(){"use strict";function t(t){if(t)d[0]=d[16]=d[1]=d[2]=d[3]=d[4]=d[5]=d[6]=d[7]=d[8]=d[9]=d[10]=d[11]=d[12]=d[13]=d[14]=d[15]=0,this.blocks=d,this.buffer8=l;else if(a){var r=new ArrayBuffer(68);this.buffer8=new Uint8Array(r),this.blocks=new Uint32Array(r)}else this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];this.h0=this.h1=this.h2=this.h3=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}var r="input is invalid type",e="object"==typeof window,i=e?window:{};i.JS_MD5_NO_WINDOW&&(e=!1);var s=!e&&"object"==typeof self,h=!i.JS_MD5_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node;h?i=global:s&&(i=self);var f=!i.JS_MD5_NO_COMMON_JS&&"object"==typeof module&&module.exports,o="function"==typeof define&&define.amd,a=!i.JS_MD5_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,n="0123456789abcdef".split(""),u=[128,32768,8388608,-2147483648],y=[0,8,16,24],c=["hex","array","digest","buffer","arrayBuffer","base64"],p="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),d=[],l;if(a){var A=new ArrayBuffer(68);l=new Uint8Array(A),d=new Uint32Array(A)}!i.JS_MD5_NO_NODE_JS&&Array.isArray||(Array.isArray=function(t){return"[object Array]"===Object.prototype.toString.call(t)}),!a||!i.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW&&ArrayBuffer.isView||(ArrayBuffer.isView=function(t){return"object"==typeof t&&t.buffer&&t.buffer.constructor===ArrayBuffer});var b=function(r){return function(e){return new t(!0).update(e)[r]()}},v=function(){var r=b("hex");h&&(r=w(r)),r.create=function(){return new t},r.update=function(t){return r.create().update(t)};for(var e=0;e<c.length;++e){var i=c[e];r[i]=b(i)}return r},w=function(t){var e=eval("require('crypto')"),i=eval("require('buffer').Buffer"),s=function(s){if("string"==typeof s)return e.createHash("md5").update(s,"utf8").digest("hex");if(null===s||void 0===s)throw r;return s.constructor===ArrayBuffer&&(s=new Uint8Array(s)),Array.isArray(s)||ArrayBuffer.isView(s)||s.constructor===i?e.createHash("md5").update(new i(s)).digest("hex"):t(s)};return s};t.prototype.update=function(t){if(!this.finalized){var e,i=typeof t;if("string"!==i){if("object"!==i)throw r;if(null===t)throw r;if(a&&t.constructor===ArrayBuffer)t=new Uint8Array(t);else if(!(Array.isArray(t)||a&&ArrayBuffer.isView(t)))throw r;e=!0}for(var s,h,f=0,o=t.length,n=this.blocks,u=this.buffer8;f<o;){if(this.hashed&&(this.hashed=!1,n[0]=n[16],n[16]=n[1]=n[2]=n[3]=n[4]=n[5]=n[6]=n[7]=n[8]=n[9]=n[10]=n[11]=n[12]=n[13]=n[14]=n[15]=0),e)if(a)for(h=this.start;f<o&&h<64;++f)u[h++]=t[f];else for(h=this.start;f<o&&h<64;++f)n[h>>2]|=t[f]<<y[3&h++];else if(a)for(h=this.start;f<o&&h<64;++f)(s=t.charCodeAt(f))<128?u[h++]=s:s<2048?(u[h++]=192|s>>6,u[h++]=128|63&s):s<55296||s>=57344?(u[h++]=224|s>>12,u[h++]=128|s>>6&63,u[h++]=128|63&s):(s=65536+((1023&s)<<10|1023&t.charCodeAt(++f)),u[h++]=240|s>>18,u[h++]=128|s>>12&63,u[h++]=128|s>>6&63,u[h++]=128|63&s);else for(h=this.start;f<o&&h<64;++f)(s=t.charCodeAt(f))<128?n[h>>2]|=s<<y[3&h++]:s<2048?(n[h>>2]|=(192|s>>6)<<y[3&h++],n[h>>2]|=(128|63&s)<<y[3&h++]):s<55296||s>=57344?(n[h>>2]|=(224|s>>12)<<y[3&h++],n[h>>2]|=(128|s>>6&63)<<y[3&h++],n[h>>2]|=(128|63&s)<<y[3&h++]):(s=65536+((1023&s)<<10|1023&t.charCodeAt(++f)),n[h>>2]|=(240|s>>18)<<y[3&h++],n[h>>2]|=(128|s>>12&63)<<y[3&h++],n[h>>2]|=(128|s>>6&63)<<y[3&h++],n[h>>2]|=(128|63&s)<<y[3&h++]);this.lastByteIndex=h,this.bytes+=h-this.start,h>=64?(this.start=h-64,this.hash(),this.hashed=!0):this.start=h}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}},t.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var t=this.blocks,r=this.lastByteIndex;t[r>>2]|=u[3&r],r>=56&&(this.hashed||this.hash(),t[0]=t[16],t[16]=t[1]=t[2]=t[3]=t[4]=t[5]=t[6]=t[7]=t[8]=t[9]=t[10]=t[11]=t[12]=t[13]=t[14]=t[15]=0),t[14]=this.bytes<<3,t[15]=this.hBytes<<3|this.bytes>>>29,this.hash()}},t.prototype.hash=function(){var t,r,e,i,s,h,f=this.blocks;this.first?r=((r=((t=((t=f[0]-680876937)<<7|t>>>25)-271733879<<0)^(e=((e=(-271733879^(i=((i=(-1732584194^2004318071&t)+f[1]-117830708)<<12|i>>>20)+t<<0)&(-271733879^t))+f[2]-1126478375)<<17|e>>>15)+i<<0)&(i^t))+f[3]-1316259209)<<22|r>>>10)+e<<0:(t=this.h0,r=this.h1,e=this.h2,r=((r+=((t=((t+=((i=this.h3)^r&(e^i))+f[0]-680876936)<<7|t>>>25)+r<<0)^(e=((e+=(r^(i=((i+=(e^t&(r^e))+f[1]-389564586)<<12|i>>>20)+t<<0)&(t^r))+f[2]+606105819)<<17|e>>>15)+i<<0)&(i^t))+f[3]-1044525330)<<22|r>>>10)+e<<0),r=((r+=((t=((t+=(i^r&(e^i))+f[4]-176418897)<<7|t>>>25)+r<<0)^(e=((e+=(r^(i=((i+=(e^t&(r^e))+f[5]+1200080426)<<12|i>>>20)+t<<0)&(t^r))+f[6]-1473231341)<<17|e>>>15)+i<<0)&(i^t))+f[7]-45705983)<<22|r>>>10)+e<<0,r=((r+=((t=((t+=(i^r&(e^i))+f[8]+1770035416)<<7|t>>>25)+r<<0)^(e=((e+=(r^(i=((i+=(e^t&(r^e))+f[9]-1958414417)<<12|i>>>20)+t<<0)&(t^r))+f[10]-42063)<<17|e>>>15)+i<<0)&(i^t))+f[11]-1990404162)<<22|r>>>10)+e<<0,r=((r+=((t=((t+=(i^r&(e^i))+f[12]+1804603682)<<7|t>>>25)+r<<0)^(e=((e+=(r^(i=((i+=(e^t&(r^e))+f[13]-40341101)<<12|i>>>20)+t<<0)&(t^r))+f[14]-1502002290)<<17|e>>>15)+i<<0)&(i^t))+f[15]+1236535329)<<22|r>>>10)+e<<0,r=((r+=((i=((i+=(r^e&((t=((t+=(e^i&(r^e))+f[1]-165796510)<<5|t>>>27)+r<<0)^r))+f[6]-1069501632)<<9|i>>>23)+t<<0)^t&((e=((e+=(t^r&(i^t))+f[11]+643717713)<<14|e>>>18)+i<<0)^i))+f[0]-373897302)<<20|r>>>12)+e<<0,r=((r+=((i=((i+=(r^e&((t=((t+=(e^i&(r^e))+f[5]-701558691)<<5|t>>>27)+r<<0)^r))+f[10]+38016083)<<9|i>>>23)+t<<0)^t&((e=((e+=(t^r&(i^t))+f[15]-660478335)<<14|e>>>18)+i<<0)^i))+f[4]-405537848)<<20|r>>>12)+e<<0,r=((r+=((i=((i+=(r^e&((t=((t+=(e^i&(r^e))+f[9]+568446438)<<5|t>>>27)+r<<0)^r))+f[14]-1019803690)<<9|i>>>23)+t<<0)^t&((e=((e+=(t^r&(i^t))+f[3]-187363961)<<14|e>>>18)+i<<0)^i))+f[8]+1163531501)<<20|r>>>12)+e<<0,r=((r+=((i=((i+=(r^e&((t=((t+=(e^i&(r^e))+f[13]-1444681467)<<5|t>>>27)+r<<0)^r))+f[2]-51403784)<<9|i>>>23)+t<<0)^t&((e=((e+=(t^r&(i^t))+f[7]+1735328473)<<14|e>>>18)+i<<0)^i))+f[12]-1926607734)<<20|r>>>12)+e<<0,r=((r+=((h=(i=((i+=((s=r^e)^(t=((t+=(s^i)+f[5]-378558)<<4|t>>>28)+r<<0))+f[8]-2022574463)<<11|i>>>21)+t<<0)^t)^(e=((e+=(h^r)+f[11]+1839030562)<<16|e>>>16)+i<<0))+f[14]-35309556)<<23|r>>>9)+e<<0,r=((r+=((h=(i=((i+=((s=r^e)^(t=((t+=(s^i)+f[1]-1530992060)<<4|t>>>28)+r<<0))+f[4]+1272893353)<<11|i>>>21)+t<<0)^t)^(e=((e+=(h^r)+f[7]-155497632)<<16|e>>>16)+i<<0))+f[10]-1094730640)<<23|r>>>9)+e<<0,r=((r+=((h=(i=((i+=((s=r^e)^(t=((t+=(s^i)+f[13]+681279174)<<4|t>>>28)+r<<0))+f[0]-358537222)<<11|i>>>21)+t<<0)^t)^(e=((e+=(h^r)+f[3]-722521979)<<16|e>>>16)+i<<0))+f[6]+76029189)<<23|r>>>9)+e<<0,r=((r+=((h=(i=((i+=((s=r^e)^(t=((t+=(s^i)+f[9]-640364487)<<4|t>>>28)+r<<0))+f[12]-421815835)<<11|i>>>21)+t<<0)^t)^(e=((e+=(h^r)+f[15]+530742520)<<16|e>>>16)+i<<0))+f[2]-995338651)<<23|r>>>9)+e<<0,r=((r+=((i=((i+=(r^((t=((t+=(e^(r|~i))+f[0]-198630844)<<6|t>>>26)+r<<0)|~e))+f[7]+1126891415)<<10|i>>>22)+t<<0)^((e=((e+=(t^(i|~r))+f[14]-1416354905)<<15|e>>>17)+i<<0)|~t))+f[5]-57434055)<<21|r>>>11)+e<<0,r=((r+=((i=((i+=(r^((t=((t+=(e^(r|~i))+f[12]+1700485571)<<6|t>>>26)+r<<0)|~e))+f[3]-1894986606)<<10|i>>>22)+t<<0)^((e=((e+=(t^(i|~r))+f[10]-1051523)<<15|e>>>17)+i<<0)|~t))+f[1]-2054922799)<<21|r>>>11)+e<<0,r=((r+=((i=((i+=(r^((t=((t+=(e^(r|~i))+f[8]+1873313359)<<6|t>>>26)+r<<0)|~e))+f[15]-30611744)<<10|i>>>22)+t<<0)^((e=((e+=(t^(i|~r))+f[6]-1560198380)<<15|e>>>17)+i<<0)|~t))+f[13]+1309151649)<<21|r>>>11)+e<<0,r=((r+=((i=((i+=(r^((t=((t+=(e^(r|~i))+f[4]-145523070)<<6|t>>>26)+r<<0)|~e))+f[11]-1120210379)<<10|i>>>22)+t<<0)^((e=((e+=(t^(i|~r))+f[2]+718787259)<<15|e>>>17)+i<<0)|~t))+f[9]-343485551)<<21|r>>>11)+e<<0,this.first?(this.h0=t+1732584193<<0,this.h1=r-271733879<<0,this.h2=e-1732584194<<0,this.h3=i+271733878<<0,this.first=!1):(this.h0=this.h0+t<<0,this.h1=this.h1+r<<0,this.h2=this.h2+e<<0,this.h3=this.h3+i<<0)},t.prototype.hex=function(){this.finalize();var t=this.h0,r=this.h1,e=this.h2,i=this.h3;return n[t>>4&15]+n[15&t]+n[t>>12&15]+n[t>>8&15]+n[t>>20&15]+n[t>>16&15]+n[t>>28&15]+n[t>>24&15]+n[r>>4&15]+n[15&r]+n[r>>12&15]+n[r>>8&15]+n[r>>20&15]+n[r>>16&15]+n[r>>28&15]+n[r>>24&15]+n[e>>4&15]+n[15&e]+n[e>>12&15]+n[e>>8&15]+n[e>>20&15]+n[e>>16&15]+n[e>>28&15]+n[e>>24&15]+n[i>>4&15]+n[15&i]+n[i>>12&15]+n[i>>8&15]+n[i>>20&15]+n[i>>16&15]+n[i>>28&15]+n[i>>24&15]},t.prototype.toString=t.prototype.hex,t.prototype.digest=function(){this.finalize();var t=this.h0,r=this.h1,e=this.h2,i=this.h3;return[255&t,t>>8&255,t>>16&255,t>>24&255,255&r,r>>8&255,r>>16&255,r>>24&255,255&e,e>>8&255,e>>16&255,e>>24&255,255&i,i>>8&255,i>>16&255,i>>24&255]},t.prototype.array=t.prototype.digest,t.prototype.arrayBuffer=function(){this.finalize();var t=new ArrayBuffer(16),r=new Uint32Array(t);return r[0]=this.h0,r[1]=this.h1,r[2]=this.h2,r[3]=this.h3,t},t.prototype.buffer=t.prototype.arrayBuffer,t.prototype.base64=function(){for(var t,r,e,i="",s=this.array(),h=0;h<15;)t=s[h++],r=s[h++],e=s[h++],i+=p[t>>>2]+p[63&(t<<4|r>>>4)]+p[63&(r<<2|e>>>6)]+p[63&e];return t=s[h],i+=p[t>>>2]+p[t<<4&63]+"=="};var _=v();f?module.exports=_:(i.md5=_,o&&define(function(){return _}))}();
  3596.  
  3597. /**
  3598. * Script for beautiful dialog boxes
  3599. *
  3600. * Скрипт для красивых диалоговых окошек
  3601. */
  3602. const popup = new (function () {
  3603. this.popUp,
  3604. this.downer,
  3605. this.middle,
  3606. this.msgText,
  3607. this.buttons = [];
  3608. this.checkboxes = [];
  3609. this.dialogPromice = null;
  3610. this.isInit = false;
  3611.  
  3612. this.init = function () {
  3613. if (this.isInit) {
  3614. return;
  3615. }
  3616. addStyle();
  3617. addBlocks();
  3618. addEventListeners();
  3619. this.isInit = true;
  3620. }
  3621.  
  3622. const addEventListeners = () => {
  3623. document.addEventListener('keyup', (e) => {
  3624. if (e.key == 'Escape') {
  3625. if (this.dialogPromice) {
  3626. const { func, result } = this.dialogPromice;
  3627. this.dialogPromice = null;
  3628. popup.hide();
  3629. func(result);
  3630. }
  3631. }
  3632. });
  3633. }
  3634.  
  3635. const addStyle = () => {
  3636. let style = document.createElement('style');
  3637. style.innerText = `
  3638. .PopUp_ {
  3639. position: absolute;
  3640. min-width: 300px;
  3641. max-width: 500px;
  3642. max-height: 600px;
  3643. background-color: #190e08e6;
  3644. z-index: 10001;
  3645. top: 169px;
  3646. left: 345px;
  3647. border: 3px #ce9767 solid;
  3648. border-radius: 10px;
  3649. display: flex;
  3650. flex-direction: column;
  3651. justify-content: space-around;
  3652. padding: 15px 9px;
  3653. box-sizing: border-box;
  3654. }
  3655.  
  3656. .PopUp_back {
  3657. position: absolute;
  3658. background-color: #00000066;
  3659. width: 100%;
  3660. height: 100%;
  3661. z-index: 10000;
  3662. top: 0;
  3663. left: 0;
  3664. }
  3665.  
  3666. .PopUp_close {
  3667. width: 40px;
  3668. height: 40px;
  3669. position: absolute;
  3670. right: -18px;
  3671. top: -18px;
  3672. border: 3px solid #c18550;
  3673. border-radius: 20px;
  3674. background: radial-gradient(circle, rgba(190,30,35,1) 0%, rgba(0,0,0,1) 100%);
  3675. background-position-y: 3px;
  3676. box-shadow: -1px 1px 3px black;
  3677. cursor: pointer;
  3678. box-sizing: border-box;
  3679. }
  3680.  
  3681. .PopUp_close:hover {
  3682. filter: brightness(1.2);
  3683. }
  3684.  
  3685. .PopUp_crossClose {
  3686. width: 100%;
  3687. height: 100%;
  3688. background-size: 65%;
  3689. background-position: center;
  3690. background-repeat: no-repeat;
  3691. background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='%23f4cd73' d='M 0.826 12.559 C 0.431 12.963 3.346 15.374 3.74 14.97 C 4.215 15.173 8.167 10.457 7.804 10.302 C 7.893 10.376 11.454 14.64 11.525 14.372 C 12.134 15.042 15.118 12.086 14.638 11.689 C 14.416 11.21 10.263 7.477 10.402 7.832 C 10.358 7.815 11.731 7.101 14.872 3.114 C 14.698 2.145 13.024 1.074 12.093 1.019 C 11.438 0.861 8.014 5.259 8.035 5.531 C 7.86 5.082 3.61 1.186 3.522 1.59 C 2.973 1.027 0.916 4.611 1.17 4.873 C 0.728 4.914 5.088 7.961 5.61 7.995 C 5.225 7.532 0.622 12.315 0.826 12.559 Z'/%3e%3c/svg%3e")
  3692. }
  3693.  
  3694. .PopUp_blocks {
  3695. width: 100%;
  3696. height: 50%;
  3697. display: flex;
  3698. justify-content: space-evenly;
  3699. align-items: center;
  3700. flex-wrap: wrap;
  3701. justify-content: center;
  3702. }
  3703.  
  3704. .PopUp_blocks:last-child {
  3705. margin-top: 25px;
  3706. }
  3707.  
  3708. .PopUp_buttons {
  3709. display: flex;
  3710. margin: 7px 10px;
  3711. flex-direction: column;
  3712. }
  3713.  
  3714. .PopUp_button {
  3715. background-color: #52A81C;
  3716. border-radius: 5px;
  3717. box-shadow: inset 0px -4px 10px, inset 0px 3px 2px #99fe20, 0px 0px 4px, 0px -3px 1px #d7b275, 0px 0px 0px 3px #ce9767;
  3718. cursor: pointer;
  3719. padding: 4px 12px 6px;
  3720. }
  3721.  
  3722. .PopUp_input {
  3723. text-align: center;
  3724. font-size: 16px;
  3725. height: 27px;
  3726. border: 1px solid #cf9250;
  3727. border-radius: 9px 9px 0px 0px;
  3728. background: transparent;
  3729. color: #fce1ac;
  3730. padding: 1px 10px;
  3731. box-sizing: border-box;
  3732. box-shadow: 0px 0px 4px, 0px 0px 0px 3px #ce9767;
  3733. }
  3734.  
  3735. .PopUp_checkboxes {
  3736. display: flex;
  3737. flex-direction: column;
  3738. margin: 15px 15px -5px 15px;
  3739. align-items: flex-start;
  3740. }
  3741.  
  3742. .PopUp_ContCheckbox {
  3743. margin: 2px 0px;
  3744. }
  3745.  
  3746. .PopUp_checkbox {
  3747. position: absolute;
  3748. z-index: -1;
  3749. opacity: 0;
  3750. }
  3751. .PopUp_checkbox+label {
  3752. display: inline-flex;
  3753. align-items: center;
  3754. user-select: none;
  3755.  
  3756. font-size: 15px;
  3757. font-family: sans-serif;
  3758. font-weight: 600;
  3759. font-stretch: condensed;
  3760. letter-spacing: 1px;
  3761. color: #fce1ac;
  3762. text-shadow: 0px 0px 1px;
  3763. }
  3764. .PopUp_checkbox+label::before {
  3765. content: '';
  3766. display: inline-block;
  3767. width: 20px;
  3768. height: 20px;
  3769. border: 1px solid #cf9250;
  3770. border-radius: 7px;
  3771. margin-right: 7px;
  3772. }
  3773. .PopUp_checkbox:checked+label::before {
  3774. background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3e%3cpath fill='%2388cb13' d='M6.564.75l-3.59 3.612-1.538-1.55L0 4.26 2.974 7.25 8 2.193z'/%3e%3c/svg%3e");
  3775. }
  3776.  
  3777. .PopUp_input::placeholder {
  3778. color: #fce1ac75;
  3779. }
  3780.  
  3781. .PopUp_input:focus {
  3782. outline: 0;
  3783. }
  3784.  
  3785. .PopUp_input + .PopUp_button {
  3786. border-radius: 0px 0px 5px 5px;
  3787. padding: 2px 18px 5px;
  3788. }
  3789.  
  3790. .PopUp_button:hover {
  3791. filter: brightness(1.2);
  3792. }
  3793.  
  3794. .PopUp_button:active {
  3795. box-shadow: inset 0px 5px 10px, inset 0px 1px 2px #99fe20, 0px 0px 4px, 0px -3px 1px #d7b275, 0px 0px 0px 3px #ce9767;
  3796. }
  3797.  
  3798. .PopUp_text {
  3799. font-size: 22px;
  3800. font-family: sans-serif;
  3801. font-weight: 600;
  3802. font-stretch: condensed;
  3803. letter-spacing: 1px;
  3804. text-align: center;
  3805. }
  3806.  
  3807. .PopUp_buttonText {
  3808. color: #E4FF4C;
  3809. text-shadow: 0px 1px 2px black;
  3810. }
  3811.  
  3812. .PopUp_msgText {
  3813. color: #FDE5B6;
  3814. text-shadow: 0px 0px 2px;
  3815. }
  3816.  
  3817. .PopUp_hideBlock {
  3818. display: none;
  3819. }
  3820. `;
  3821. document.head.appendChild(style);
  3822. }
  3823.  
  3824. const addBlocks = () => {
  3825. this.back = document.createElement('div');
  3826. this.back.classList.add('PopUp_back');
  3827. this.back.classList.add('PopUp_hideBlock');
  3828. document.body.append(this.back);
  3829.  
  3830. this.popUp = document.createElement('div');
  3831. this.popUp.classList.add('PopUp_');
  3832. this.back.append(this.popUp);
  3833.  
  3834. let upper = document.createElement('div')
  3835. upper.classList.add('PopUp_blocks');
  3836. this.popUp.append(upper);
  3837.  
  3838. this.middle = document.createElement('div')
  3839. this.middle.classList.add('PopUp_blocks');
  3840. this.middle.classList.add('PopUp_checkboxes');
  3841. this.popUp.append(this.middle);
  3842.  
  3843. this.downer = document.createElement('div')
  3844. this.downer.classList.add('PopUp_blocks');
  3845. this.popUp.append(this.downer);
  3846.  
  3847. this.msgText = document.createElement('div');
  3848. this.msgText.classList.add('PopUp_text', 'PopUp_msgText');
  3849. upper.append(this.msgText);
  3850. }
  3851.  
  3852. this.showBack = function () {
  3853. this.back.classList.remove('PopUp_hideBlock');
  3854. }
  3855.  
  3856. this.hideBack = function () {
  3857. this.back.classList.add('PopUp_hideBlock');
  3858. }
  3859.  
  3860. this.show = function () {
  3861. if (this.checkboxes.length) {
  3862. this.middle.classList.remove('PopUp_hideBlock');
  3863. }
  3864. this.showBack();
  3865. this.popUp.classList.remove('PopUp_hideBlock');
  3866. this.popUp.style.left = (window.innerWidth - this.popUp.offsetWidth) / 2 + 'px';
  3867. this.popUp.style.top = (window.innerHeight - this.popUp.offsetHeight) / 3 + 'px';
  3868. }
  3869.  
  3870. this.hide = function () {
  3871. this.hideBack();
  3872. this.popUp.classList.add('PopUp_hideBlock');
  3873. }
  3874.  
  3875. this.addAnyButton = (option) => {
  3876. const contButton = document.createElement('div');
  3877. contButton.classList.add('PopUp_buttons');
  3878. this.downer.append(contButton);
  3879.  
  3880. let inputField = {
  3881. value: option.result || option.default
  3882. }
  3883. if (option.isInput) {
  3884. inputField = document.createElement('input');
  3885. inputField.type = 'text';
  3886. if (option.placeholder) {
  3887. inputField.placeholder = option.placeholder;
  3888. }
  3889. if (option.default) {
  3890. inputField.value = option.default;
  3891. }
  3892. inputField.classList.add('PopUp_input');
  3893. contButton.append(inputField);
  3894. }
  3895.  
  3896. const button = document.createElement('div');
  3897. button.classList.add('PopUp_button');
  3898. button.title = option.title || '';
  3899. contButton.append(button);
  3900.  
  3901. const buttonText = document.createElement('div');
  3902. buttonText.classList.add('PopUp_text', 'PopUp_buttonText');
  3903. buttonText.innerHTML = option.msg;
  3904. button.append(buttonText);
  3905.  
  3906. return { button, contButton, inputField };
  3907. }
  3908.  
  3909. this.addCloseButton = () => {
  3910. let button = document.createElement('div')
  3911. button.classList.add('PopUp_close');
  3912. this.popUp.append(button);
  3913.  
  3914. let crossClose = document.createElement('div')
  3915. crossClose.classList.add('PopUp_crossClose');
  3916. button.append(crossClose);
  3917.  
  3918. return { button, contButton: button };
  3919. }
  3920.  
  3921. this.addButton = (option, buttonClick) => {
  3922.  
  3923. const { button, contButton, inputField } = option.isClose ? this.addCloseButton() : this.addAnyButton(option);
  3924. if (option.isClose) {
  3925. this.dialogPromice = { func: buttonClick, result: option.result };
  3926. }
  3927. button.addEventListener('click', () => {
  3928. let result = '';
  3929. if (option.isInput) {
  3930. result = inputField.value;
  3931. }
  3932. if (option.isClose || option.isCancel) {
  3933. this.dialogPromice = null;
  3934. }
  3935. buttonClick(result);
  3936. });
  3937.  
  3938. this.buttons.push(contButton);
  3939. }
  3940.  
  3941. this.clearButtons = () => {
  3942. while (this.buttons.length) {
  3943. this.buttons.pop().remove();
  3944. }
  3945. }
  3946.  
  3947. this.addCheckBox = (checkBox) => {
  3948. const contCheckbox = document.createElement('div');
  3949. contCheckbox.classList.add('PopUp_ContCheckbox');
  3950. this.middle.append(contCheckbox);
  3951.  
  3952. const checkbox = document.createElement('input');
  3953. checkbox.type = 'checkbox';
  3954. checkbox.id = 'PopUpCheckbox' + this.checkboxes.length;
  3955. checkbox.dataset.name = checkBox.name;
  3956. checkbox.checked = checkBox.checked;
  3957. checkbox.label = checkBox.label;
  3958. checkbox.title = checkBox.title || '';
  3959. checkbox.classList.add('PopUp_checkbox');
  3960. contCheckbox.appendChild(checkbox)
  3961.  
  3962. const checkboxLabel = document.createElement('label');
  3963. checkboxLabel.innerText = checkBox.label;
  3964. checkboxLabel.title = checkBox.title || '';
  3965. checkboxLabel.setAttribute('for', checkbox.id);
  3966. contCheckbox.appendChild(checkboxLabel);
  3967.  
  3968. this.checkboxes.push(checkbox);
  3969. }
  3970.  
  3971. this.clearCheckBox = () => {
  3972. this.middle.classList.add('PopUp_hideBlock');
  3973. while (this.checkboxes.length) {
  3974. this.checkboxes.pop().parentNode.remove();
  3975. }
  3976. }
  3977.  
  3978. this.setMsgText = (text) => {
  3979. this.msgText.innerHTML = text;
  3980. }
  3981.  
  3982. this.getCheckBoxes = () => {
  3983. const checkBoxes = [];
  3984.  
  3985. for (const checkBox of this.checkboxes) {
  3986. checkBoxes.push({
  3987. name: checkBox.dataset.name,
  3988. label: checkBox.label,
  3989. checked: checkBox.checked
  3990. });
  3991. }
  3992.  
  3993. return checkBoxes;
  3994. }
  3995.  
  3996. this.confirm = async (msg, buttOpt, checkBoxes = []) => {
  3997. if (!this.isInit) {
  3998. this.init();
  3999. }
  4000. this.clearButtons();
  4001. this.clearCheckBox();
  4002. return new Promise((complete, failed) => {
  4003. this.setMsgText(msg);
  4004. if (!buttOpt) {
  4005. buttOpt = [{ msg: 'Ok', result: true, isInput: false }];
  4006. }
  4007. for (const checkBox of checkBoxes) {
  4008. this.addCheckBox(checkBox);
  4009. }
  4010. for (let butt of buttOpt) {
  4011. this.addButton(butt, (result) => {
  4012. result = result || butt.result;
  4013. complete(result);
  4014. popup.hide();
  4015. });
  4016. if (butt.isCancel) {
  4017. this.dialogPromice = { func: complete, result: butt.result };
  4018. }
  4019. }
  4020. this.show();
  4021. });
  4022. }
  4023. });
  4024.  
  4025. this.HWHFuncs.popup = popup;
  4026.  
  4027. /**
  4028. * Script control panel
  4029. *
  4030. * Панель управления скриптом
  4031. */
  4032. const scriptMenu = new (function () {
  4033.  
  4034. this.mainMenu,
  4035. this.buttons = [],
  4036. this.checkboxes = [];
  4037. this.option = {
  4038. showMenu: false,
  4039. showDetails: {}
  4040. };
  4041.  
  4042. this.init = function (option = {}) {
  4043. this.option = Object.assign(this.option, option);
  4044. this.option.showDetails = this.loadShowDetails();
  4045. addStyle();
  4046. addBlocks();
  4047. }
  4048.  
  4049. const addStyle = () => {
  4050. style = document.createElement('style');
  4051. style.innerText = `
  4052. .scriptMenu_status {
  4053. position: absolute;
  4054. z-index: 10001;
  4055. /* max-height: 30px; */
  4056. top: -1px;
  4057. left: 30%;
  4058. cursor: pointer;
  4059. border-radius: 0px 0px 10px 10px;
  4060. background: #190e08e6;
  4061. border: 1px #ce9767 solid;
  4062. font-size: 18px;
  4063. font-family: sans-serif;
  4064. font-weight: 600;
  4065. font-stretch: condensed;
  4066. letter-spacing: 1px;
  4067. color: #fce1ac;
  4068. text-shadow: 0px 0px 1px;
  4069. transition: 0.5s;
  4070. padding: 2px 10px 3px;
  4071. }
  4072. .scriptMenu_statusHide {
  4073. top: -35px;
  4074. height: 30px;
  4075. overflow: hidden;
  4076. }
  4077. .scriptMenu_label {
  4078. position: absolute;
  4079. top: 30%;
  4080. left: -4px;
  4081. z-index: 9999;
  4082. cursor: pointer;
  4083. width: 30px;
  4084. height: 30px;
  4085. background: radial-gradient(circle, #47a41b 0%, #1a2f04 100%);
  4086. border: 1px solid #1a2f04;
  4087. border-radius: 5px;
  4088. box-shadow:
  4089. inset 0px 2px 4px #83ce26,
  4090. inset 0px -4px 6px #1a2f04,
  4091. 0px 0px 2px black,
  4092. 0px 0px 0px 2px #ce9767;
  4093. }
  4094. .scriptMenu_label:hover {
  4095. filter: brightness(1.2);
  4096. }
  4097. .scriptMenu_arrowLabel {
  4098. width: 100%;
  4099. height: 100%;
  4100. background-size: 75%;
  4101. background-position: center;
  4102. background-repeat: no-repeat;
  4103. background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='%2388cb13' d='M7.596 7.304a.802.802 0 0 1 0 1.392l-6.363 3.692C.713 12.69 0 12.345 0 11.692V4.308c0-.653.713-.998 1.233-.696l6.363 3.692Z'/%3e%3cpath fill='%2388cb13' d='M15.596 7.304a.802.802 0 0 1 0 1.392l-6.363 3.692C8.713 12.69 8 12.345 8 11.692V4.308c0-.653.713-.998 1.233-.696l6.363 3.692Z'/%3e%3c/svg%3e");
  4104. box-shadow: 0px 1px 2px #000;
  4105. border-radius: 5px;
  4106. filter: drop-shadow(0px 1px 2px #000D);
  4107. }
  4108. .scriptMenu_main {
  4109. position: absolute;
  4110. max-width: 285px;
  4111. z-index: 9999;
  4112. top: 50%;
  4113. transform: translateY(-40%);
  4114. background: #190e08e6;
  4115. border: 1px #ce9767 solid;
  4116. border-radius: 0px 10px 10px 0px;
  4117. border-left: none;
  4118. padding: 5px 10px 5px 5px;
  4119. box-sizing: border-box;
  4120. font-size: 15px;
  4121. font-family: sans-serif;
  4122. font-weight: 600;
  4123. font-stretch: condensed;
  4124. letter-spacing: 1px;
  4125. color: #fce1ac;
  4126. text-shadow: 0px 0px 1px;
  4127. transition: 1s;
  4128. display: flex;
  4129. flex-direction: column;
  4130. flex-wrap: nowrap;
  4131. }
  4132. .scriptMenu_showMenu {
  4133. display: none;
  4134. }
  4135. .scriptMenu_showMenu:checked~.scriptMenu_main {
  4136. left: 0px;
  4137. }
  4138. .scriptMenu_showMenu:not(:checked)~.scriptMenu_main {
  4139. left: -300px;
  4140. }
  4141. .scriptMenu_divInput {
  4142. margin: 2px;
  4143. }
  4144. .scriptMenu_divInputText {
  4145. margin: 2px;
  4146. align-self: center;
  4147. display: flex;
  4148. }
  4149. .scriptMenu_checkbox {
  4150. position: absolute;
  4151. z-index: -1;
  4152. opacity: 0;
  4153. }
  4154. .scriptMenu_checkbox+label {
  4155. display: inline-flex;
  4156. align-items: center;
  4157. user-select: none;
  4158. }
  4159. .scriptMenu_checkbox+label::before {
  4160. content: '';
  4161. display: inline-block;
  4162. width: 20px;
  4163. height: 20px;
  4164. border: 1px solid #cf9250;
  4165. border-radius: 7px;
  4166. margin-right: 7px;
  4167. }
  4168. .scriptMenu_checkbox:checked+label::before {
  4169. background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3e%3cpath fill='%2388cb13' d='M6.564.75l-3.59 3.612-1.538-1.55L0 4.26 2.974 7.25 8 2.193z'/%3e%3c/svg%3e");
  4170. }
  4171. .scriptMenu_close {
  4172. width: 40px;
  4173. height: 40px;
  4174. position: absolute;
  4175. right: -18px;
  4176. top: -18px;
  4177. border: 3px solid #c18550;
  4178. border-radius: 20px;
  4179. background: radial-gradient(circle, rgba(190,30,35,1) 0%, rgba(0,0,0,1) 100%);
  4180. background-position-y: 3px;
  4181. box-shadow: -1px 1px 3px black;
  4182. cursor: pointer;
  4183. box-sizing: border-box;
  4184. }
  4185. .scriptMenu_close:hover {
  4186. filter: brightness(1.2);
  4187. }
  4188. .scriptMenu_crossClose {
  4189. width: 100%;
  4190. height: 100%;
  4191. background-size: 65%;
  4192. background-position: center;
  4193. background-repeat: no-repeat;
  4194. background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='%23f4cd73' d='M 0.826 12.559 C 0.431 12.963 3.346 15.374 3.74 14.97 C 4.215 15.173 8.167 10.457 7.804 10.302 C 7.893 10.376 11.454 14.64 11.525 14.372 C 12.134 15.042 15.118 12.086 14.638 11.689 C 14.416 11.21 10.263 7.477 10.402 7.832 C 10.358 7.815 11.731 7.101 14.872 3.114 C 14.698 2.145 13.024 1.074 12.093 1.019 C 11.438 0.861 8.014 5.259 8.035 5.531 C 7.86 5.082 3.61 1.186 3.522 1.59 C 2.973 1.027 0.916 4.611 1.17 4.873 C 0.728 4.914 5.088 7.961 5.61 7.995 C 5.225 7.532 0.622 12.315 0.826 12.559 Z'/%3e%3c/svg%3e")
  4195. }
  4196. .scriptMenu_button {
  4197. user-select: none;
  4198. border-radius: 5px;
  4199. cursor: pointer;
  4200. padding: 5px 14px 8px;
  4201. margin: 4px;
  4202. background: radial-gradient(circle, rgba(165,120,56,1) 80%, rgba(0,0,0,1) 110%);
  4203. box-shadow: inset 0px -4px 6px #442901, inset 0px 1px 6px #442901, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 2px #ce9767;
  4204. }
  4205. .scriptMenu_button:hover {
  4206. filter: brightness(1.2);
  4207. }
  4208. .scriptMenu_button:active {
  4209. box-shadow: inset 0px 4px 6px #442901, inset 0px 4px 6px #442901, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 2px #ce9767;
  4210. }
  4211. .scriptMenu_buttonText {
  4212. color: #fce5b7;
  4213. text-shadow: 0px 1px 2px black;
  4214. text-align: center;
  4215. }
  4216. .scriptMenu_header {
  4217. text-align: center;
  4218. align-self: center;
  4219. font-size: 15px;
  4220. margin: 0px 15px;
  4221. }
  4222. .scriptMenu_header a {
  4223. color: #fce5b7;
  4224. text-decoration: none;
  4225. }
  4226. .scriptMenu_InputText {
  4227. text-align: center;
  4228. width: 130px;
  4229. height: 24px;
  4230. border: 1px solid #cf9250;
  4231. border-radius: 9px;
  4232. background: transparent;
  4233. color: #fce1ac;
  4234. padding: 0px 10px;
  4235. box-sizing: border-box;
  4236. }
  4237. .scriptMenu_InputText:focus {
  4238. filter: brightness(1.2);
  4239. outline: 0;
  4240. }
  4241. .scriptMenu_InputText::placeholder {
  4242. color: #fce1ac75;
  4243. }
  4244. .scriptMenu_Summary {
  4245. cursor: pointer;
  4246. margin-left: 7px;
  4247. }
  4248. .scriptMenu_Details {
  4249. align-self: center;
  4250. }
  4251. `;
  4252. document.head.appendChild(style);
  4253. }
  4254.  
  4255. const addBlocks = () => {
  4256. const main = document.createElement('div');
  4257. document.body.appendChild(main);
  4258.  
  4259. this.status = document.createElement('div');
  4260. this.status.classList.add('scriptMenu_status');
  4261. this.setStatus('');
  4262. main.appendChild(this.status);
  4263.  
  4264. const label = document.createElement('label');
  4265. label.classList.add('scriptMenu_label');
  4266. label.setAttribute('for', 'checkbox_showMenu');
  4267. main.appendChild(label);
  4268.  
  4269. const arrowLabel = document.createElement('div');
  4270. arrowLabel.classList.add('scriptMenu_arrowLabel');
  4271. label.appendChild(arrowLabel);
  4272.  
  4273. const checkbox = document.createElement('input');
  4274. checkbox.type = 'checkbox';
  4275. checkbox.id = 'checkbox_showMenu';
  4276. checkbox.checked = this.option.showMenu;
  4277. checkbox.classList.add('scriptMenu_showMenu');
  4278. main.appendChild(checkbox);
  4279.  
  4280. this.mainMenu = document.createElement('div');
  4281. this.mainMenu.classList.add('scriptMenu_main');
  4282. main.appendChild(this.mainMenu);
  4283.  
  4284. const closeButton = document.createElement('label');
  4285. closeButton.classList.add('scriptMenu_close');
  4286. closeButton.setAttribute('for', 'checkbox_showMenu');
  4287. this.mainMenu.appendChild(closeButton);
  4288.  
  4289. const crossClose = document.createElement('div');
  4290. crossClose.classList.add('scriptMenu_crossClose');
  4291. closeButton.appendChild(crossClose);
  4292. }
  4293.  
  4294. this.setStatus = (text, onclick) => {
  4295. if (!text) {
  4296. this.status.classList.add('scriptMenu_statusHide');
  4297. this.status.innerHTML = '';
  4298. } else {
  4299. this.status.classList.remove('scriptMenu_statusHide');
  4300. this.status.innerHTML = text;
  4301. }
  4302.  
  4303. if (typeof onclick == 'function') {
  4304. this.status.addEventListener("click", onclick, {
  4305. once: true
  4306. });
  4307. }
  4308. }
  4309.  
  4310. this.addStatus = (text) => {
  4311. if (!this.status.innerHTML) {
  4312. this.status.classList.remove('scriptMenu_statusHide');
  4313. }
  4314. this.status.innerHTML += text;
  4315. }
  4316.  
  4317. /**
  4318. * Adding a text element
  4319. *
  4320. * Добавление текстового элемента
  4321. * @param {String} text text // текст
  4322. * @param {Function} func Click function // функция по клику
  4323. * @param {HTMLDivElement} main parent // родитель
  4324. */
  4325. this.addHeader = (text, func, main) => {
  4326. main = main || this.mainMenu;
  4327. const header = document.createElement('div');
  4328. header.classList.add('scriptMenu_header');
  4329. header.innerHTML = text;
  4330. if (typeof func == 'function') {
  4331. header.addEventListener('click', func);
  4332. }
  4333. main.appendChild(header);
  4334. return header;
  4335. }
  4336.  
  4337. /**
  4338. * Adding a button
  4339. *
  4340. * Добавление кнопки
  4341. * @param {String} text
  4342. * @param {Function} func
  4343. * @param {String} title
  4344. * @param {HTMLDivElement} main parent // родитель
  4345. */
  4346. this.addButton = (text, func, title, main) => {
  4347. main = main || this.mainMenu;
  4348. const button = document.createElement('div');
  4349. button.classList.add('scriptMenu_button');
  4350. button.title = title;
  4351. button.addEventListener('click', func);
  4352. main.appendChild(button);
  4353.  
  4354. const buttonText = document.createElement('div');
  4355. buttonText.classList.add('scriptMenu_buttonText');
  4356. buttonText.innerText = text;
  4357. button.appendChild(buttonText);
  4358. this.buttons.push(button);
  4359.  
  4360. return button;
  4361. }
  4362.  
  4363. /**
  4364. * Adding checkbox
  4365. *
  4366. * Добавление чекбокса
  4367. * @param {String} label
  4368. * @param {String} title
  4369. * @param {HTMLDivElement} main parent // родитель
  4370. * @returns
  4371. */
  4372. this.addCheckbox = (label, title, main) => {
  4373. main = main || this.mainMenu;
  4374. const divCheckbox = document.createElement('div');
  4375. divCheckbox.classList.add('scriptMenu_divInput');
  4376. divCheckbox.title = title;
  4377. main.appendChild(divCheckbox);
  4378.  
  4379. const checkbox = document.createElement('input');
  4380. checkbox.type = 'checkbox';
  4381. checkbox.id = 'scriptMenuCheckbox' + this.checkboxes.length;
  4382. checkbox.classList.add('scriptMenu_checkbox');
  4383. divCheckbox.appendChild(checkbox)
  4384.  
  4385. const checkboxLabel = document.createElement('label');
  4386. checkboxLabel.innerText = label;
  4387. checkboxLabel.setAttribute('for', checkbox.id);
  4388. divCheckbox.appendChild(checkboxLabel);
  4389.  
  4390. this.checkboxes.push(checkbox);
  4391. return checkbox;
  4392. }
  4393.  
  4394. /**
  4395. * Adding input field
  4396. *
  4397. * Добавление поля ввода
  4398. * @param {String} title
  4399. * @param {String} placeholder
  4400. * @param {HTMLDivElement} main parent // родитель
  4401. * @returns
  4402. */
  4403. this.addInputText = (title, placeholder, main) => {
  4404. main = main || this.mainMenu;
  4405. const divInputText = document.createElement('div');
  4406. divInputText.classList.add('scriptMenu_divInputText');
  4407. divInputText.title = title;
  4408. main.appendChild(divInputText);
  4409.  
  4410. const newInputText = document.createElement('input');
  4411. newInputText.type = 'text';
  4412. if (placeholder) {
  4413. newInputText.placeholder = placeholder;
  4414. }
  4415. newInputText.classList.add('scriptMenu_InputText');
  4416. divInputText.appendChild(newInputText)
  4417. return newInputText;
  4418. }
  4419.  
  4420. /**
  4421. * Adds a dropdown block
  4422. *
  4423. * Добавляет раскрывающийся блок
  4424. * @param {String} summary
  4425. * @param {String} name
  4426. * @returns
  4427. */
  4428. this.addDetails = (summaryText, name = null) => {
  4429. const details = document.createElement('details');
  4430. details.classList.add('scriptMenu_Details');
  4431. this.mainMenu.appendChild(details);
  4432.  
  4433. const summary = document.createElement('summary');
  4434. summary.classList.add('scriptMenu_Summary');
  4435. summary.innerText = summaryText;
  4436. if (name) {
  4437. const self = this;
  4438. details.open = this.option.showDetails[name];
  4439. details.dataset.name = name;
  4440. summary.addEventListener('click', () => {
  4441. self.option.showDetails[details.dataset.name] = !details.open;
  4442. self.saveShowDetails(self.option.showDetails);
  4443. });
  4444. }
  4445. details.appendChild(summary);
  4446.  
  4447. return details;
  4448. }
  4449.  
  4450. /**
  4451. * Saving the expanded state of the details blocks
  4452. *
  4453. * Сохранение состояния развенутости блоков details
  4454. * @param {*} value
  4455. */
  4456. this.saveShowDetails = (value) => {
  4457. localStorage.setItem('scriptMenu_showDetails', JSON.stringify(value));
  4458. }
  4459.  
  4460. /**
  4461. * Loading the state of expanded blocks details
  4462. *
  4463. * Загрузка состояния развенутости блоков details
  4464. * @returns
  4465. */
  4466. this.loadShowDetails = () => {
  4467. let showDetails = localStorage.getItem('scriptMenu_showDetails');
  4468.  
  4469. if (!showDetails) {
  4470. return {};
  4471. }
  4472.  
  4473. try {
  4474. showDetails = JSON.parse(showDetails);
  4475. } catch (e) {
  4476. return {};
  4477. }
  4478.  
  4479. return showDetails;
  4480. }
  4481. });
  4482.  
  4483. /**
  4484. * Пример использования
  4485. scriptMenu.init();
  4486. scriptMenu.addHeader('v1.508');
  4487. scriptMenu.addCheckbox('testHack', 'Тестовый взлом игры!');
  4488. scriptMenu.addButton('Запуск!', () => console.log('click'), 'подсказака');
  4489. scriptMenu.addInputText('input подсказака');
  4490. */
  4491. /**
  4492. * Game Library
  4493. *
  4494. * Игровая библиотека
  4495. */
  4496. class Library {
  4497. defaultLibUrl = 'https://heroesru-a.akamaihd.net/vk/v1101/lib/lib.json';
  4498.  
  4499. constructor() {
  4500. if (!Library.instance) {
  4501. Library.instance = this;
  4502. }
  4503.  
  4504. return Library.instance;
  4505. }
  4506.  
  4507. async load() {
  4508. try {
  4509. await this.getUrlLib();
  4510. console.log(this.defaultLibUrl);
  4511. this.data = await fetch(this.defaultLibUrl).then(e => e.json())
  4512. } catch (error) {
  4513. console.error('Не удалось загрузить библиотеку', error)
  4514. }
  4515. }
  4516.  
  4517. async getUrlLib() {
  4518. try {
  4519. const db = new Database('hw_cache', 'cache');
  4520. await db.open();
  4521. const cacheLibFullUrl = await db.get('lib/lib.json.gz', false);
  4522. this.defaultLibUrl = cacheLibFullUrl.fullUrl.split('.gz').shift();
  4523. } catch(e) {}
  4524. }
  4525.  
  4526. getData(id) {
  4527. return this.data[id];
  4528. }
  4529.  
  4530. setData(data) {
  4531. this.data = data;
  4532. }
  4533. }
  4534.  
  4535. this.lib = new Library();
  4536. /**
  4537. * Database
  4538. *
  4539. * База данных
  4540. */
  4541. class Database {
  4542. constructor(dbName, storeName) {
  4543. this.dbName = dbName;
  4544. this.storeName = storeName;
  4545. this.db = null;
  4546. }
  4547.  
  4548. async open() {
  4549. return new Promise((resolve, reject) => {
  4550. const request = indexedDB.open(this.dbName);
  4551.  
  4552. request.onerror = () => {
  4553. reject(new Error(`Failed to open database ${this.dbName}`));
  4554. };
  4555.  
  4556. request.onsuccess = () => {
  4557. this.db = request.result;
  4558. resolve();
  4559. };
  4560.  
  4561. request.onupgradeneeded = (event) => {
  4562. const db = event.target.result;
  4563. if (!db.objectStoreNames.contains(this.storeName)) {
  4564. db.createObjectStore(this.storeName);
  4565. }
  4566. };
  4567. });
  4568. }
  4569.  
  4570. async set(key, value) {
  4571. return new Promise((resolve, reject) => {
  4572. const transaction = this.db.transaction([this.storeName], 'readwrite');
  4573. const store = transaction.objectStore(this.storeName);
  4574. const request = store.put(value, key);
  4575.  
  4576. request.onerror = () => {
  4577. reject(new Error(`Failed to save value with key ${key}`));
  4578. };
  4579.  
  4580. request.onsuccess = () => {
  4581. resolve();
  4582. };
  4583. });
  4584. }
  4585.  
  4586. async get(key, def) {
  4587. return new Promise((resolve, reject) => {
  4588. const transaction = this.db.transaction([this.storeName], 'readonly');
  4589. const store = transaction.objectStore(this.storeName);
  4590. const request = store.get(key);
  4591.  
  4592. request.onerror = () => {
  4593. resolve(def);
  4594. };
  4595.  
  4596. request.onsuccess = () => {
  4597. resolve(request.result);
  4598. };
  4599. });
  4600. }
  4601.  
  4602. async delete(key) {
  4603. return new Promise((resolve, reject) => {
  4604. const transaction = this.db.transaction([this.storeName], 'readwrite');
  4605. const store = transaction.objectStore(this.storeName);
  4606. const request = store.delete(key);
  4607.  
  4608. request.onerror = () => {
  4609. reject(new Error(`Failed to delete value with key ${key}`));
  4610. };
  4611.  
  4612. request.onsuccess = () => {
  4613. resolve();
  4614. };
  4615. });
  4616. }
  4617. }
  4618.  
  4619. /**
  4620. * Returns the stored value
  4621. *
  4622. * Возвращает сохраненное значение
  4623. */
  4624. function getSaveVal(saveName, def) {
  4625. const result = storage.get(saveName, def);
  4626. return result;
  4627. }
  4628. this.HWHFuncs.getSaveVal = getSaveVal;
  4629.  
  4630. /**
  4631. * Stores value
  4632. *
  4633. * Сохраняет значение
  4634. */
  4635. function setSaveVal(saveName, value) {
  4636. storage.set(saveName, value);
  4637. }
  4638. this.HWHFuncs.setSaveVal = setSaveVal;
  4639.  
  4640. /**
  4641. * Database initialization
  4642. *
  4643. * Инициализация базы данных
  4644. */
  4645. const db = new Database(GM_info.script.name, 'settings');
  4646.  
  4647. /**
  4648. * Data store
  4649. *
  4650. * Хранилище данных
  4651. */
  4652. const storage = {
  4653. userId: 0,
  4654. /**
  4655. * Default values
  4656. *
  4657. * Значения по умолчанию
  4658. */
  4659. values: [
  4660. ...Object.entries(checkboxes).map(e => ({ [e[0]]: e[1].default })),
  4661. ...Object.entries(inputs).map(e => ({ [e[0]]: e[1].default })),
  4662. ].reduce((acc, obj) => ({ ...acc, ...obj }), {}),
  4663. name: GM_info.script.name,
  4664. get: function (key, def) {
  4665. if (key in this.values) {
  4666. return this.values[key];
  4667. }
  4668. return def;
  4669. },
  4670. set: function (key, value) {
  4671. this.values[key] = value;
  4672. db.set(this.userId, this.values).catch(
  4673. e => null
  4674. );
  4675. localStorage[this.name + ':' + key] = value;
  4676. },
  4677. delete: function (key) {
  4678. delete this.values[key];
  4679. db.set(this.userId, this.values);
  4680. delete localStorage[this.name + ':' + key];
  4681. }
  4682. }
  4683.  
  4684. /**
  4685. * Returns all keys from localStorage that start with prefix (for migration)
  4686. *
  4687. * Возвращает все ключи из localStorage которые начинаются с prefix (для миграции)
  4688. */
  4689. function getAllValuesStartingWith(prefix) {
  4690. const values = [];
  4691. for (let i = 0; i < localStorage.length; i++) {
  4692. const key = localStorage.key(i);
  4693. if (key.startsWith(prefix)) {
  4694. const val = localStorage.getItem(key);
  4695. const keyValue = key.split(':')[1];
  4696. values.push({ key: keyValue, val });
  4697. }
  4698. }
  4699. return values;
  4700. }
  4701.  
  4702. /**
  4703. * Opens or migrates to a database
  4704. *
  4705. * Открывает или мигрирует в базу данных
  4706. */
  4707. async function openOrMigrateDatabase(userId) {
  4708. storage.userId = userId;
  4709. try {
  4710. await db.open();
  4711. } catch(e) {
  4712. return;
  4713. }
  4714. let settings = await db.get(userId, false);
  4715.  
  4716. if (settings) {
  4717. storage.values = settings;
  4718. return;
  4719. }
  4720.  
  4721. const values = getAllValuesStartingWith(GM_info.script.name);
  4722. for (const value of values) {
  4723. let val = null;
  4724. try {
  4725. val = JSON.parse(value.val);
  4726. } catch {
  4727. break;
  4728. }
  4729. storage.values[value.key] = val;
  4730. }
  4731. await db.set(userId, storage.values);
  4732. }
  4733.  
  4734. class ZingerYWebsiteAPI {
  4735. /**
  4736. * Class for interaction with the API of the zingery.ru website
  4737. * Intended only for use with the HeroWarsHelper script:
  4738. * https://greasyfork.org/ru/scripts/450693-herowarshelper
  4739. * Copyright ZingerY
  4740. */
  4741. url = 'https://zingery.ru/heroes/';
  4742. // YWJzb2x1dGVseSB1c2VsZXNzIGxpbmU=
  4743. constructor(urn, env, data = {}) {
  4744. this.urn = urn;
  4745. this.fd = {
  4746. now: Date.now(),
  4747. fp: this.constructor.toString().replaceAll(/\s/g, ''),
  4748. env: env.callee.toString().replaceAll(/\s/g, ''),
  4749. info: (({ name, version, author }) => [name, version, author])(GM_info.script),
  4750. ...data,
  4751. };
  4752. }
  4753.  
  4754. sign() {
  4755. return md5([...this.fd.info, ~(this.fd.now % 1e3), this.fd.fp].join('_'));
  4756. }
  4757.  
  4758. encode(data) {
  4759. return btoa(encodeURIComponent(JSON.stringify(data)));
  4760. }
  4761.  
  4762. decode(data) {
  4763. return JSON.parse(decodeURIComponent(atob(data)));
  4764. }
  4765.  
  4766. headers() {
  4767. return {
  4768. 'X-Request-Signature': this.sign(),
  4769. 'X-Script-Name': GM_info.script.name,
  4770. 'X-Script-Version': GM_info.script.version,
  4771. 'X-Script-Author': GM_info.script.author,
  4772. 'X-Script-ZingerY': 42,
  4773. };
  4774. }
  4775.  
  4776. async request() {
  4777. try {
  4778. const response = await fetch(this.url + this.urn, {
  4779. method: 'POST',
  4780. headers: this.headers(),
  4781. body: this.encode(this.fd),
  4782. });
  4783. const text = await response.text();
  4784. return this.decode(text);
  4785. } catch (e) {
  4786. console.error(e);
  4787. return [];
  4788. }
  4789. }
  4790. /**
  4791. * Класс для взаимодействия с API сайта zingery.ru
  4792. * Предназначен только для использования со скриптом HeroWarsHelper:
  4793. * https://greasyfork.org/ru/scripts/450693-herowarshelper
  4794. * Copyright ZingerY
  4795. */
  4796. }
  4797.  
  4798. /**
  4799. * Sending expeditions
  4800. *
  4801. * Отправка экспедиций
  4802. */
  4803. function checkExpedition() {
  4804. const { Expedition } = HWHClasses;
  4805. return new Promise((resolve, reject) => {
  4806. const expedition = new Expedition(resolve, reject);
  4807. expedition.start();
  4808. });
  4809. }
  4810.  
  4811. class Expedition {
  4812. checkExpedInfo = {
  4813. calls: [
  4814. {
  4815. name: 'expeditionGet',
  4816. args: {},
  4817. ident: 'expeditionGet',
  4818. },
  4819. {
  4820. name: 'heroGetAll',
  4821. args: {},
  4822. ident: 'heroGetAll',
  4823. },
  4824. ],
  4825. };
  4826.  
  4827. constructor(resolve, reject) {
  4828. this.resolve = resolve;
  4829. this.reject = reject;
  4830. }
  4831.  
  4832. async start() {
  4833. const data = await Send(JSON.stringify(this.checkExpedInfo));
  4834.  
  4835. const expedInfo = data.results[0].result.response;
  4836. const dataHeroes = data.results[1].result.response;
  4837. const dataExped = { useHeroes: [], exped: [] };
  4838. const calls = [];
  4839.  
  4840. /**
  4841. * Adding expeditions to collect
  4842. * Добавляем экспедиции для сбора
  4843. */
  4844. let countGet = 0;
  4845. for (var n in expedInfo) {
  4846. const exped = expedInfo[n];
  4847. const dateNow = Date.now() / 1000;
  4848. if (exped.status == 2 && exped.endTime != 0 && dateNow > exped.endTime) {
  4849. countGet++;
  4850. calls.push({
  4851. name: 'expeditionFarm',
  4852. args: { expeditionId: exped.id },
  4853. ident: 'expeditionFarm_' + exped.id,
  4854. });
  4855. } else {
  4856. dataExped.useHeroes = dataExped.useHeroes.concat(exped.heroes);
  4857. }
  4858. if (exped.status == 1) {
  4859. dataExped.exped.push({ id: exped.id, power: exped.power });
  4860. }
  4861. }
  4862. dataExped.exped = dataExped.exped.sort((a, b) => b.power - a.power);
  4863.  
  4864. /**
  4865. * Putting together a list of heroes
  4866. * Собираем список героев
  4867. */
  4868. const heroesArr = [];
  4869. for (let n in dataHeroes) {
  4870. const hero = dataHeroes[n];
  4871. if (hero.xp > 0 && !dataExped.useHeroes.includes(hero.id)) {
  4872. let heroPower = hero.power;
  4873. // Лара Крофт * 3
  4874. if (hero.id == 63 && hero.color >= 16) {
  4875. heroPower *= 3;
  4876. }
  4877. heroesArr.push({ id: hero.id, power: heroPower });
  4878. }
  4879. }
  4880.  
  4881. /**
  4882. * Adding expeditions to send
  4883. * Добавляем экспедиции для отправки
  4884. */
  4885. let countSend = 0;
  4886. heroesArr.sort((a, b) => a.power - b.power);
  4887. for (const exped of dataExped.exped) {
  4888. let heroesIds = this.selectionHeroes(heroesArr, exped.power);
  4889. if (heroesIds && heroesIds.length > 4) {
  4890. for (let q in heroesArr) {
  4891. if (heroesIds.includes(heroesArr[q].id)) {
  4892. delete heroesArr[q];
  4893. }
  4894. }
  4895. countSend++;
  4896. calls.push({
  4897. name: 'expeditionSendHeroes',
  4898. args: {
  4899. expeditionId: exped.id,
  4900. heroes: heroesIds,
  4901. },
  4902. ident: 'expeditionSendHeroes_' + exped.id,
  4903. });
  4904. }
  4905. }
  4906.  
  4907. if (calls.length) {
  4908. await Send({ calls });
  4909. this.end(I18N('EXPEDITIONS_SENT', {countGet, countSend}));
  4910. return;
  4911. }
  4912.  
  4913. this.end(I18N('EXPEDITIONS_NOTHING'));
  4914. }
  4915.  
  4916. /**
  4917. * Selection of heroes for expeditions
  4918. *
  4919. * Подбор героев для экспедиций
  4920. */
  4921. selectionHeroes(heroes, power) {
  4922. const resultHeroers = [];
  4923. const heroesIds = [];
  4924. for (let q = 0; q < 5; q++) {
  4925. for (let i in heroes) {
  4926. let hero = heroes[i];
  4927. if (heroesIds.includes(hero.id)) {
  4928. continue;
  4929. }
  4930.  
  4931. const summ = resultHeroers.reduce((acc, hero) => acc + hero.power, 0);
  4932. const need = Math.round((power - summ) / (5 - resultHeroers.length));
  4933. if (hero.power > need) {
  4934. resultHeroers.push(hero);
  4935. heroesIds.push(hero.id);
  4936. break;
  4937. }
  4938. }
  4939. }
  4940.  
  4941. const summ = resultHeroers.reduce((acc, hero) => acc + hero.power, 0);
  4942. if (summ < power) {
  4943. return false;
  4944. }
  4945. return heroesIds;
  4946. }
  4947.  
  4948. /**
  4949. * Ends expedition script
  4950. *
  4951. * Завершает скрипт экспедиции
  4952. */
  4953. end(msg) {
  4954. setProgress(msg, true);
  4955. this.resolve();
  4956. }
  4957. }
  4958.  
  4959. this.HWHClasses.Expedition = Expedition;
  4960.  
  4961. /**
  4962. * Walkthrough of the dungeon
  4963. *
  4964. * Прохождение подземелья
  4965. */
  4966. function testDungeon() {
  4967. const { executeDungeon } = HWHClasses;
  4968. return new Promise((resolve, reject) => {
  4969. const dung = new executeDungeon(resolve, reject);
  4970. const titanit = getInput('countTitanit');
  4971. dung.start(titanit);
  4972. });
  4973. }
  4974.  
  4975. /**
  4976. * Walkthrough of the dungeon
  4977. *
  4978. * Прохождение подземелья
  4979. */
  4980. function executeDungeon(resolve, reject) {
  4981. dungeonActivity = 0;
  4982. maxDungeonActivity = 150;
  4983.  
  4984. titanGetAll = [];
  4985.  
  4986. teams = {
  4987. heroes: [],
  4988. earth: [],
  4989. fire: [],
  4990. neutral: [],
  4991. water: [],
  4992. }
  4993.  
  4994. titanStats = [];
  4995.  
  4996. titansStates = {};
  4997.  
  4998. let talentMsg = '';
  4999. let talentMsgReward = '';
  5000.  
  5001. callsExecuteDungeon = {
  5002. calls: [{
  5003. name: "dungeonGetInfo",
  5004. args: {},
  5005. ident: "dungeonGetInfo"
  5006. }, {
  5007. name: "teamGetAll",
  5008. args: {},
  5009. ident: "teamGetAll"
  5010. }, {
  5011. name: "teamGetFavor",
  5012. args: {},
  5013. ident: "teamGetFavor"
  5014. }, {
  5015. name: "clanGetInfo",
  5016. args: {},
  5017. ident: "clanGetInfo"
  5018. }, {
  5019. name: "titanGetAll",
  5020. args: {},
  5021. ident: "titanGetAll"
  5022. }, {
  5023. name: "inventoryGet",
  5024. args: {},
  5025. ident: "inventoryGet"
  5026. }]
  5027. }
  5028.  
  5029. this.start = function(titanit) {
  5030. maxDungeonActivity = titanit || getInput('countTitanit');
  5031. send(JSON.stringify(callsExecuteDungeon), startDungeon);
  5032. }
  5033.  
  5034. /**
  5035. * Getting data on the dungeon
  5036. *
  5037. * Получаем данные по подземелью
  5038. */
  5039. function startDungeon(e) {
  5040. res = e.results;
  5041. dungeonGetInfo = res[0].result.response;
  5042. if (!dungeonGetInfo) {
  5043. endDungeon('noDungeon', res);
  5044. return;
  5045. }
  5046. teamGetAll = res[1].result.response;
  5047. teamGetFavor = res[2].result.response;
  5048. dungeonActivity = res[3].result.response.stat.todayDungeonActivity;
  5049. titanGetAll = Object.values(res[4].result.response);
  5050. countPredictionCard = res[5].result.response.consumable[81];
  5051.  
  5052. teams.hero = {
  5053. favor: teamGetFavor.dungeon_hero,
  5054. heroes: teamGetAll.dungeon_hero.filter(id => id < 6000),
  5055. teamNum: 0,
  5056. }
  5057. heroPet = teamGetAll.dungeon_hero.filter(id => id >= 6000).pop();
  5058. if (heroPet) {
  5059. teams.hero.pet = heroPet;
  5060. }
  5061.  
  5062. teams.neutral = {
  5063. favor: {},
  5064. heroes: getTitanTeam(titanGetAll, 'neutral'),
  5065. teamNum: 0,
  5066. };
  5067. teams.water = {
  5068. favor: {},
  5069. heroes: getTitanTeam(titanGetAll, 'water'),
  5070. teamNum: 0,
  5071. };
  5072. teams.fire = {
  5073. favor: {},
  5074. heroes: getTitanTeam(titanGetAll, 'fire'),
  5075. teamNum: 0,
  5076. };
  5077. teams.earth = {
  5078. favor: {},
  5079. heroes: getTitanTeam(titanGetAll, 'earth'),
  5080. teamNum: 0,
  5081. };
  5082.  
  5083.  
  5084. checkFloor(dungeonGetInfo);
  5085. }
  5086.  
  5087. function getTitanTeam(titans, type) {
  5088. switch (type) {
  5089. case 'neutral':
  5090. return titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5091. case 'water':
  5092. return titans.filter(e => e.id.toString().slice(2, 3) == '0').map(e => e.id);
  5093. case 'fire':
  5094. return titans.filter(e => e.id.toString().slice(2, 3) == '1').map(e => e.id);
  5095. case 'earth':
  5096. return titans.filter(e => e.id.toString().slice(2, 3) == '2').map(e => e.id);
  5097. }
  5098. }
  5099.  
  5100. function getNeutralTeam() {
  5101. const titans = titanGetAll.filter(e => !titansStates[e.id]?.isDead)
  5102. return titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5103. }
  5104.  
  5105. function fixTitanTeam(titans) {
  5106. titans.heroes = titans.heroes.filter(e => !titansStates[e]?.isDead);
  5107. return titans;
  5108. }
  5109.  
  5110. /**
  5111. * Checking the floor
  5112. *
  5113. * Проверяем этаж
  5114. */
  5115. async function checkFloor(dungeonInfo) {
  5116. if (!('floor' in dungeonInfo) || dungeonInfo.floor?.state == 2) {
  5117. saveProgress();
  5118. return;
  5119. }
  5120. checkTalent(dungeonInfo);
  5121. // console.log(dungeonInfo, dungeonActivity);
  5122. setProgress(`${I18N('DUNGEON')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity} ${talentMsg}`);
  5123. if (dungeonActivity >= maxDungeonActivity) {
  5124. endDungeon('endDungeon', 'maxActive ' + dungeonActivity + '/' + maxDungeonActivity);
  5125. return;
  5126. }
  5127. titansStates = dungeonInfo.states.titans;
  5128. titanStats = titanObjToArray(titansStates);
  5129. const floorChoices = dungeonInfo.floor.userData;
  5130. const floorType = dungeonInfo.floorType;
  5131. //const primeElement = dungeonInfo.elements.prime;
  5132. if (floorType == "battle") {
  5133. const calls = [];
  5134. for (let teamNum in floorChoices) {
  5135. attackerType = floorChoices[teamNum].attackerType;
  5136. const args = fixTitanTeam(teams[attackerType]);
  5137. if (attackerType == 'neutral') {
  5138. args.heroes = getNeutralTeam();
  5139. }
  5140. if (!args.heroes.length) {
  5141. continue;
  5142. }
  5143. args.teamNum = teamNum;
  5144. calls.push({
  5145. name: "dungeonStartBattle",
  5146. args,
  5147. ident: "body_" + teamNum
  5148. })
  5149. }
  5150. if (!calls.length) {
  5151. endDungeon('endDungeon', 'All Dead');
  5152. return;
  5153. }
  5154. const battleDatas = await Send(JSON.stringify({ calls }))
  5155. .then(e => e.results.map(n => n.result.response))
  5156. const battleResults = [];
  5157. for (n in battleDatas) {
  5158. battleData = battleDatas[n]
  5159. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  5160. battleResults.push(await Calc(battleData).then(result => {
  5161. result.teamNum = n;
  5162. result.attackerType = floorChoices[n].attackerType;
  5163. return result;
  5164. }));
  5165. }
  5166. processingPromises(battleResults)
  5167. }
  5168. }
  5169.  
  5170. async function checkTalent(dungeonInfo) {
  5171. const talent = dungeonInfo.talent;
  5172. if (!talent) {
  5173. return;
  5174. }
  5175. const dungeonFloor = +dungeonInfo.floorNumber;
  5176. const talentFloor = +talent.floorRandValue;
  5177. let doorsAmount = 3 - talent.conditions.doorsAmount;
  5178.  
  5179. if (dungeonFloor === talentFloor && (!doorsAmount || !talent.conditions?.farmedDoors[dungeonFloor])) {
  5180. const reward = await Send({
  5181. calls: [
  5182. { name: 'heroTalent_getReward', args: { talentType: 'tmntDungeonTalent', reroll: false }, ident: 'group_0_body' },
  5183. { name: 'heroTalent_farmReward', args: { talentType: 'tmntDungeonTalent' }, ident: 'group_1_body' },
  5184. ],
  5185. }).then((e) => e.results[0].result.response);
  5186. const type = Object.keys(reward).pop();
  5187. const itemId = Object.keys(reward[type]).pop();
  5188. const count = reward[type][itemId];
  5189. const itemName = cheats.translate(`LIB_${type.toUpperCase()}_NAME_${itemId}`);
  5190. talentMsgReward += `<br> ${count} ${itemName}`;
  5191. doorsAmount++;
  5192. }
  5193. talentMsg = `<br>TMNT Talent: ${doorsAmount}/3 ${talentMsgReward}<br>`;
  5194. }
  5195.  
  5196. function processingPromises(results) {
  5197. let selectBattle = results[0];
  5198. if (results.length < 2) {
  5199. // console.log(selectBattle);
  5200. if (!selectBattle.result.win) {
  5201. endDungeon('dungeonEndBattle\n', selectBattle);
  5202. return;
  5203. }
  5204. endBattle(selectBattle);
  5205. return;
  5206. }
  5207.  
  5208. selectBattle = false;
  5209. let bestState = -1000;
  5210. for (const result of results) {
  5211. const recovery = getState(result);
  5212. if (recovery > bestState) {
  5213. bestState = recovery;
  5214. selectBattle = result
  5215. }
  5216. }
  5217. // console.log(selectBattle.teamNum, results);
  5218. if (!selectBattle || bestState <= -1000) {
  5219. endDungeon('dungeonEndBattle\n', results);
  5220. return;
  5221. }
  5222.  
  5223. startBattle(selectBattle.teamNum, selectBattle.attackerType)
  5224. .then(endBattle);
  5225. }
  5226.  
  5227. /**
  5228. * Let's start the fight
  5229. *
  5230. * Начинаем бой
  5231. */
  5232. function startBattle(teamNum, attackerType) {
  5233. return new Promise(function (resolve, reject) {
  5234. args = fixTitanTeam(teams[attackerType]);
  5235. args.teamNum = teamNum;
  5236. if (attackerType == 'neutral') {
  5237. const titans = titanGetAll.filter(e => !titansStates[e.id]?.isDead)
  5238. args.heroes = titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5239. }
  5240. startBattleCall = {
  5241. calls: [{
  5242. name: "dungeonStartBattle",
  5243. args,
  5244. ident: "body"
  5245. }]
  5246. }
  5247. send(JSON.stringify(startBattleCall), resultBattle, {
  5248. resolve,
  5249. teamNum,
  5250. attackerType
  5251. });
  5252. });
  5253. }
  5254. /**
  5255. * Returns the result of the battle in a promise
  5256. *
  5257. * Возращает резульат боя в промис
  5258. */
  5259. function resultBattle(resultBattles, args) {
  5260. battleData = resultBattles.results[0].result.response;
  5261. battleType = "get_tower";
  5262. if (battleData.type == "dungeon_titan") {
  5263. battleType = "get_titan";
  5264. }
  5265. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  5266. BattleCalc(battleData, battleType, function (result) {
  5267. result.teamNum = args.teamNum;
  5268. result.attackerType = args.attackerType;
  5269. args.resolve(result);
  5270. });
  5271. }
  5272. /**
  5273. * Finishing the fight
  5274. *
  5275. * Заканчиваем бой
  5276. */
  5277. async function endBattle(battleInfo) {
  5278. if (battleInfo.result.win) {
  5279. const args = {
  5280. result: battleInfo.result,
  5281. progress: battleInfo.progress,
  5282. }
  5283. if (countPredictionCard > 0) {
  5284. args.isRaid = true;
  5285. } else {
  5286. const timer = getTimer(battleInfo.battleTime);
  5287. console.log(timer);
  5288. await countdownTimer(timer, `${I18N('DUNGEON')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity} ${talentMsg}`);
  5289. }
  5290. const calls = [{
  5291. name: "dungeonEndBattle",
  5292. args,
  5293. ident: "body"
  5294. }];
  5295. lastDungeonBattleData = null;
  5296. send(JSON.stringify({ calls }), resultEndBattle);
  5297. } else {
  5298. endDungeon('dungeonEndBattle win: false\n', battleInfo);
  5299. }
  5300. }
  5301.  
  5302. /**
  5303. * Getting and processing battle results
  5304. *
  5305. * Получаем и обрабатываем результаты боя
  5306. */
  5307. function resultEndBattle(e) {
  5308. if ('error' in e) {
  5309. popup.confirm(I18N('ERROR_MSG', {
  5310. name: e.error.name,
  5311. description: e.error.description,
  5312. }));
  5313. endDungeon('errorRequest', e);
  5314. return;
  5315. }
  5316. battleResult = e.results[0].result.response;
  5317. if ('error' in battleResult) {
  5318. endDungeon('errorBattleResult', battleResult);
  5319. return;
  5320. }
  5321. dungeonGetInfo = battleResult.dungeon ?? battleResult;
  5322. dungeonActivity += battleResult.reward.dungeonActivity ?? 0;
  5323. checkFloor(dungeonGetInfo);
  5324. }
  5325.  
  5326. /**
  5327. * Returns the coefficient of condition of the
  5328. * difference in titanium before and after the battle
  5329. *
  5330. * Возвращает коэффициент состояния титанов после боя
  5331. */
  5332. function getState(result) {
  5333. if (!result.result.win) {
  5334. return -1000;
  5335. }
  5336.  
  5337. let beforeSumFactor = 0;
  5338. const beforeTitans = result.battleData.attackers;
  5339. for (let titanId in beforeTitans) {
  5340. const titan = beforeTitans[titanId];
  5341. const state = titan.state;
  5342. let factor = 1;
  5343. if (state) {
  5344. const hp = state.hp / titan.hp;
  5345. const energy = state.energy / 1e3;
  5346. factor = hp + energy / 20
  5347. }
  5348. beforeSumFactor += factor;
  5349. }
  5350.  
  5351. let afterSumFactor = 0;
  5352. const afterTitans = result.progress[0].attackers.heroes;
  5353. for (let titanId in afterTitans) {
  5354. const titan = afterTitans[titanId];
  5355. const hp = titan.hp / beforeTitans[titanId].hp;
  5356. const energy = titan.energy / 1e3;
  5357. const factor = hp + energy / 20;
  5358. afterSumFactor += factor;
  5359. }
  5360. return afterSumFactor - beforeSumFactor;
  5361. }
  5362.  
  5363. /**
  5364. * Converts an object with IDs to an array with IDs
  5365. *
  5366. * Преобразует объект с идетификаторами в массив с идетификаторами
  5367. */
  5368. function titanObjToArray(obj) {
  5369. let titans = [];
  5370. for (let id in obj) {
  5371. obj[id].id = id;
  5372. titans.push(obj[id]);
  5373. }
  5374. return titans;
  5375. }
  5376.  
  5377. function saveProgress() {
  5378. let saveProgressCall = {
  5379. calls: [{
  5380. name: "dungeonSaveProgress",
  5381. args: {},
  5382. ident: "body"
  5383. }]
  5384. }
  5385. send(JSON.stringify(saveProgressCall), resultEndBattle);
  5386. }
  5387.  
  5388. function endDungeon(reason, info) {
  5389. console.warn(reason, info);
  5390. setProgress(`${I18N('DUNGEON')} ${I18N('COMPLETED')}`, true);
  5391. resolve();
  5392. }
  5393. }
  5394.  
  5395. this.HWHClasses.executeDungeon = executeDungeon;
  5396.  
  5397. /**
  5398. * Passing the tower
  5399. *
  5400. * Прохождение башни
  5401. */
  5402. function testTower() {
  5403. const { executeTower } = HWHClasses;
  5404. return new Promise((resolve, reject) => {
  5405. tower = new executeTower(resolve, reject);
  5406. tower.start();
  5407. });
  5408. }
  5409.  
  5410. /**
  5411. * Passing the tower
  5412. *
  5413. * Прохождение башни
  5414. */
  5415. function executeTower(resolve, reject) {
  5416. lastTowerInfo = {};
  5417.  
  5418. scullCoin = 0;
  5419.  
  5420. heroGetAll = [];
  5421.  
  5422. heroesStates = {};
  5423.  
  5424. argsBattle = {
  5425. heroes: [],
  5426. favor: {},
  5427. };
  5428.  
  5429. callsExecuteTower = {
  5430. calls: [{
  5431. name: "towerGetInfo",
  5432. args: {},
  5433. ident: "towerGetInfo"
  5434. }, {
  5435. name: "teamGetAll",
  5436. args: {},
  5437. ident: "teamGetAll"
  5438. }, {
  5439. name: "teamGetFavor",
  5440. args: {},
  5441. ident: "teamGetFavor"
  5442. }, {
  5443. name: "inventoryGet",
  5444. args: {},
  5445. ident: "inventoryGet"
  5446. }, {
  5447. name: "heroGetAll",
  5448. args: {},
  5449. ident: "heroGetAll"
  5450. }]
  5451. }
  5452.  
  5453. buffIds = [
  5454. {id: 0, cost: 0, isBuy: false}, // plug // заглушка
  5455. {id: 1, cost: 1, isBuy: true}, // 3% attack // 3% атака
  5456. {id: 2, cost: 6, isBuy: true}, // 2% attack // 2% атака
  5457. {id: 3, cost: 16, isBuy: true}, // 4% attack // 4% атака
  5458. {id: 4, cost: 40, isBuy: true}, // 8% attack // 8% атака
  5459. {id: 5, cost: 1, isBuy: true}, // 10% armor // 10% броня
  5460. {id: 6, cost: 6, isBuy: true}, // 5% armor // 5% броня
  5461. {id: 7, cost: 16, isBuy: true}, // 10% armor // 10% броня
  5462. {id: 8, cost: 40, isBuy: true}, // 20% armor // 20% броня
  5463. { id: 9, cost: 1, isBuy: true }, // 10% protection from magic // 10% защита от магии
  5464. { id: 10, cost: 6, isBuy: true }, // 5% protection from magic // 5% защита от магии
  5465. { id: 11, cost: 16, isBuy: true }, // 10% protection from magic // 10% защита от магии
  5466. { id: 12, cost: 40, isBuy: true }, // 20% protection from magic // 20% защита от магии
  5467. { id: 13, cost: 1, isBuy: false }, // 40% health hero // 40% здоровья герою
  5468. { id: 14, cost: 6, isBuy: false }, // 40% health hero // 40% здоровья герою
  5469. { id: 15, cost: 16, isBuy: false }, // 80% health hero // 80% здоровья герою
  5470. { id: 16, cost: 40, isBuy: false }, // 40% health to all heroes // 40% здоровья всем героям
  5471. { id: 17, cost: 1, isBuy: false }, // 40% energy to the hero // 40% энергии герою
  5472. { id: 18, cost: 3, isBuy: false }, // 40% energy to the hero // 40% энергии герою
  5473. { id: 19, cost: 8, isBuy: false }, // 80% energy to the hero // 80% энергии герою
  5474. { id: 20, cost: 20, isBuy: false }, // 40% energy to all heroes // 40% энергии всем героям
  5475. { id: 21, cost: 40, isBuy: false }, // Hero Resurrection // Воскрешение героя
  5476. ]
  5477.  
  5478. this.start = function () {
  5479. send(JSON.stringify(callsExecuteTower), startTower);
  5480. }
  5481.  
  5482. /**
  5483. * Getting data on the Tower
  5484. *
  5485. * Получаем данные по башне
  5486. */
  5487. function startTower(e) {
  5488. res = e.results;
  5489. towerGetInfo = res[0].result.response;
  5490. if (!towerGetInfo) {
  5491. endTower('noTower', res);
  5492. return;
  5493. }
  5494. teamGetAll = res[1].result.response;
  5495. teamGetFavor = res[2].result.response;
  5496. inventoryGet = res[3].result.response;
  5497. heroGetAll = Object.values(res[4].result.response);
  5498.  
  5499. scullCoin = inventoryGet.coin[7] ?? 0;
  5500.  
  5501. argsBattle.favor = teamGetFavor.tower;
  5502. argsBattle.heroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5503. pet = teamGetAll.tower.filter(id => id >= 6000).pop();
  5504. if (pet) {
  5505. argsBattle.pet = pet;
  5506. }
  5507.  
  5508. checkFloor(towerGetInfo);
  5509. }
  5510.  
  5511. function fixHeroesTeam(argsBattle) {
  5512. let fixHeroes = argsBattle.heroes.filter(e => !heroesStates[e]?.isDead);
  5513. if (fixHeroes.length < 5) {
  5514. heroGetAll = heroGetAll.filter(e => !heroesStates[e.id]?.isDead);
  5515. fixHeroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5516. Object.keys(argsBattle.favor).forEach(e => {
  5517. if (!fixHeroes.includes(+e)) {
  5518. delete argsBattle.favor[e];
  5519. }
  5520. })
  5521. }
  5522. argsBattle.heroes = fixHeroes;
  5523. return argsBattle;
  5524. }
  5525.  
  5526. /**
  5527. * Check the floor
  5528. *
  5529. * Проверяем этаж
  5530. */
  5531. function checkFloor(towerInfo) {
  5532. lastTowerInfo = towerInfo;
  5533. maySkipFloor = +towerInfo.maySkipFloor;
  5534. floorNumber = +towerInfo.floorNumber;
  5535. heroesStates = towerInfo.states.heroes;
  5536. floorInfo = towerInfo.floor;
  5537.  
  5538. /**
  5539. * Is there at least one chest open on the floor
  5540. * Открыт ли на этаже хоть один сундук
  5541. */
  5542. isOpenChest = false;
  5543. if (towerInfo.floorType == "chest") {
  5544. isOpenChest = towerInfo.floor.chests.reduce((n, e) => n + e.opened, 0);
  5545. }
  5546.  
  5547. setProgress(`${I18N('TOWER')}: ${I18N('FLOOR')} ${floorNumber}`);
  5548. if (floorNumber > 49) {
  5549. if (isOpenChest) {
  5550. endTower('alreadyOpenChest 50 floor', floorNumber);
  5551. return;
  5552. }
  5553. }
  5554. /**
  5555. * If the chest is open and you can skip floors, then move on
  5556. * Если сундук открыт и можно скипать этажи, то переходим дальше
  5557. */
  5558. if (towerInfo.mayFullSkip && +towerInfo.teamLevel == 130) {
  5559. if (floorNumber == 1) {
  5560. fullSkipTower();
  5561. return;
  5562. }
  5563. if (isOpenChest) {
  5564. nextOpenChest(floorNumber);
  5565. } else {
  5566. nextChestOpen(floorNumber);
  5567. }
  5568. return;
  5569. }
  5570.  
  5571. // console.log(towerInfo, scullCoin);
  5572. switch (towerInfo.floorType) {
  5573. case "battle":
  5574. if (floorNumber <= maySkipFloor) {
  5575. skipFloor();
  5576. return;
  5577. }
  5578. if (floorInfo.state == 2) {
  5579. nextFloor();
  5580. return;
  5581. }
  5582. startBattle().then(endBattle);
  5583. return;
  5584. case "buff":
  5585. checkBuff(towerInfo);
  5586. return;
  5587. case "chest":
  5588. openChest(floorNumber);
  5589. return;
  5590. default:
  5591. console.log('!', towerInfo.floorType, towerInfo);
  5592. break;
  5593. }
  5594. }
  5595.  
  5596. /**
  5597. * Let's start the fight
  5598. *
  5599. * Начинаем бой
  5600. */
  5601. function startBattle() {
  5602. return new Promise(function (resolve, reject) {
  5603. towerStartBattle = {
  5604. calls: [{
  5605. name: "towerStartBattle",
  5606. args: fixHeroesTeam(argsBattle),
  5607. ident: "body"
  5608. }]
  5609. }
  5610. send(JSON.stringify(towerStartBattle), resultBattle, resolve);
  5611. });
  5612. }
  5613. /**
  5614. * Returns the result of the battle in a promise
  5615. *
  5616. * Возращает резульат боя в промис
  5617. */
  5618. function resultBattle(resultBattles, resolve) {
  5619. battleData = resultBattles.results[0].result.response;
  5620. battleType = "get_tower";
  5621. BattleCalc(battleData, battleType, function (result) {
  5622. resolve(result);
  5623. });
  5624. }
  5625. /**
  5626. * Finishing the fight
  5627. *
  5628. * Заканчиваем бой
  5629. */
  5630. function endBattle(battleInfo) {
  5631. if (battleInfo.result.stars >= 3) {
  5632. endBattleCall = {
  5633. calls: [{
  5634. name: "towerEndBattle",
  5635. args: {
  5636. result: battleInfo.result,
  5637. progress: battleInfo.progress,
  5638. },
  5639. ident: "body"
  5640. }]
  5641. }
  5642. send(JSON.stringify(endBattleCall), resultEndBattle);
  5643. } else {
  5644. endTower('towerEndBattle win: false\n', battleInfo);
  5645. }
  5646. }
  5647.  
  5648. /**
  5649. * Getting and processing battle results
  5650. *
  5651. * Получаем и обрабатываем результаты боя
  5652. */
  5653. function resultEndBattle(e) {
  5654. battleResult = e.results[0].result.response;
  5655. if ('error' in battleResult) {
  5656. endTower('errorBattleResult', battleResult);
  5657. return;
  5658. }
  5659. if ('reward' in battleResult) {
  5660. scullCoin += battleResult.reward?.coin[7] ?? 0;
  5661. }
  5662. nextFloor();
  5663. }
  5664.  
  5665. function nextFloor() {
  5666. nextFloorCall = {
  5667. calls: [{
  5668. name: "towerNextFloor",
  5669. args: {},
  5670. ident: "body"
  5671. }]
  5672. }
  5673. send(JSON.stringify(nextFloorCall), checkDataFloor);
  5674. }
  5675.  
  5676. function openChest(floorNumber) {
  5677. floorNumber = floorNumber || 0;
  5678. openChestCall = {
  5679. calls: [{
  5680. name: "towerOpenChest",
  5681. args: {
  5682. num: 2
  5683. },
  5684. ident: "body"
  5685. }]
  5686. }
  5687. send(JSON.stringify(openChestCall), floorNumber < 50 ? nextFloor : lastChest);
  5688. }
  5689.  
  5690. function lastChest() {
  5691. endTower('openChest 50 floor', floorNumber);
  5692. }
  5693.  
  5694. function skipFloor() {
  5695. skipFloorCall = {
  5696. calls: [{
  5697. name: "towerSkipFloor",
  5698. args: {},
  5699. ident: "body"
  5700. }]
  5701. }
  5702. send(JSON.stringify(skipFloorCall), checkDataFloor);
  5703. }
  5704.  
  5705. function checkBuff(towerInfo) {
  5706. buffArr = towerInfo.floor;
  5707. promises = [];
  5708. for (let buff of buffArr) {
  5709. buffInfo = buffIds[buff.id];
  5710. if (buffInfo.isBuy && buffInfo.cost <= scullCoin) {
  5711. scullCoin -= buffInfo.cost;
  5712. promises.push(buyBuff(buff.id));
  5713. }
  5714. }
  5715. Promise.all(promises).then(nextFloor);
  5716. }
  5717.  
  5718. function buyBuff(buffId) {
  5719. return new Promise(function (resolve, reject) {
  5720. buyBuffCall = {
  5721. calls: [{
  5722. name: "towerBuyBuff",
  5723. args: {
  5724. buffId
  5725. },
  5726. ident: "body"
  5727. }]
  5728. }
  5729. send(JSON.stringify(buyBuffCall), resolve);
  5730. });
  5731. }
  5732.  
  5733. function checkDataFloor(result) {
  5734. towerInfo = result.results[0].result.response;
  5735. if ('reward' in towerInfo && towerInfo.reward?.coin) {
  5736. scullCoin += towerInfo.reward?.coin[7] ?? 0;
  5737. }
  5738. if ('tower' in towerInfo) {
  5739. towerInfo = towerInfo.tower;
  5740. }
  5741. if ('skullReward' in towerInfo) {
  5742. scullCoin += towerInfo.skullReward?.coin[7] ?? 0;
  5743. }
  5744. checkFloor(towerInfo);
  5745. }
  5746. /**
  5747. * Getting tower rewards
  5748. *
  5749. * Получаем награды башни
  5750. */
  5751. function farmTowerRewards(reason) {
  5752. let { pointRewards, points } = lastTowerInfo;
  5753. let pointsAll = Object.getOwnPropertyNames(pointRewards);
  5754. let farmPoints = pointsAll.filter(e => +e <= +points && !pointRewards[e]);
  5755. if (!farmPoints.length) {
  5756. return;
  5757. }
  5758. let farmTowerRewardsCall = {
  5759. calls: [{
  5760. name: "tower_farmPointRewards",
  5761. args: {
  5762. points: farmPoints
  5763. },
  5764. ident: "tower_farmPointRewards"
  5765. }]
  5766. }
  5767.  
  5768. if (scullCoin > 0) {
  5769. farmTowerRewardsCall.calls.push({
  5770. name: "tower_farmSkullReward",
  5771. args: {},
  5772. ident: "tower_farmSkullReward"
  5773. });
  5774. }
  5775.  
  5776. send(JSON.stringify(farmTowerRewardsCall), () => { });
  5777. }
  5778.  
  5779. function fullSkipTower() {
  5780. /**
  5781. * Next chest
  5782. *
  5783. * Следующий сундук
  5784. */
  5785. function nextChest(n) {
  5786. return {
  5787. name: "towerNextChest",
  5788. args: {},
  5789. ident: "group_" + n + "_body"
  5790. }
  5791. }
  5792. /**
  5793. * Open chest
  5794. *
  5795. * Открыть сундук
  5796. */
  5797. function openChest(n) {
  5798. return {
  5799. name: "towerOpenChest",
  5800. args: {
  5801. "num": 2
  5802. },
  5803. ident: "group_" + n + "_body"
  5804. }
  5805. }
  5806.  
  5807. const fullSkipTowerCall = {
  5808. calls: []
  5809. }
  5810.  
  5811. let n = 0;
  5812. for (let i = 0; i < 15; i++) {
  5813. // 15 сундуков
  5814. fullSkipTowerCall.calls.push(nextChest(++n));
  5815. fullSkipTowerCall.calls.push(openChest(++n));
  5816. // +5 сундуков, 250 изюма // towerOpenChest
  5817. // if (i < 5) {
  5818. // fullSkipTowerCall.calls.push(openChest(++n, 2));
  5819. // }
  5820. }
  5821.  
  5822. fullSkipTowerCall.calls.push({
  5823. name: 'towerGetInfo',
  5824. args: {},
  5825. ident: 'group_' + ++n + '_body',
  5826. });
  5827.  
  5828. send(JSON.stringify(fullSkipTowerCall), data => {
  5829. for (const r of data.results) {
  5830. const towerInfo = r?.result?.response;
  5831. if (towerInfo && 'skullReward' in towerInfo) {
  5832. scullCoin += towerInfo.skullReward?.coin[7] ?? 0;
  5833. }
  5834. }
  5835. data.results[0] = data.results[data.results.length - 1];
  5836. checkDataFloor(data);
  5837. });
  5838. }
  5839.  
  5840. function nextChestOpen(floorNumber) {
  5841. const calls = [{
  5842. name: "towerOpenChest",
  5843. args: {
  5844. num: 2
  5845. },
  5846. ident: "towerOpenChest"
  5847. }];
  5848.  
  5849. Send(JSON.stringify({ calls })).then(e => {
  5850. nextOpenChest(floorNumber);
  5851. });
  5852. }
  5853.  
  5854. function nextOpenChest(floorNumber) {
  5855. if (floorNumber > 49) {
  5856. endTower('openChest 50 floor', floorNumber);
  5857. return;
  5858. }
  5859.  
  5860. let nextOpenChestCall = {
  5861. calls: [{
  5862. name: "towerNextChest",
  5863. args: {},
  5864. ident: "towerNextChest"
  5865. }, {
  5866. name: "towerOpenChest",
  5867. args: {
  5868. num: 2
  5869. },
  5870. ident: "towerOpenChest"
  5871. }]
  5872. }
  5873. send(JSON.stringify(nextOpenChestCall), checkDataFloor);
  5874. }
  5875.  
  5876. function endTower(reason, info) {
  5877. console.log(reason, info);
  5878. if (reason != 'noTower') {
  5879. farmTowerRewards(reason);
  5880. }
  5881. setProgress(`${I18N('TOWER')} ${I18N('COMPLETED')}!`, true);
  5882. resolve();
  5883. }
  5884. }
  5885.  
  5886. this.HWHClasses.executeTower = executeTower;
  5887.  
  5888. /**
  5889. * Passage of the arena of the titans
  5890. *
  5891. * Прохождение арены титанов
  5892. */
  5893. function testTitanArena() {
  5894. const { executeTitanArena } = HWHClasses;
  5895. return new Promise((resolve, reject) => {
  5896. titAren = new executeTitanArena(resolve, reject);
  5897. titAren.start();
  5898. });
  5899. }
  5900.  
  5901. /**
  5902. * Passage of the arena of the titans
  5903. *
  5904. * Прохождение арены титанов
  5905. */
  5906. function executeTitanArena(resolve, reject) {
  5907. let titan_arena = [];
  5908. let finishListBattle = [];
  5909. /**
  5910. * ID of the current batch
  5911. *
  5912. * Идетификатор текущей пачки
  5913. */
  5914. let currentRival = 0;
  5915. /**
  5916. * Number of attempts to finish off the pack
  5917. *
  5918. * Количество попыток добития пачки
  5919. */
  5920. let attempts = 0;
  5921. /**
  5922. * Was there an attempt to finish off the current shooting range
  5923. *
  5924. * Была ли попытка добития текущего тира
  5925. */
  5926. let isCheckCurrentTier = false;
  5927. /**
  5928. * Current shooting range
  5929. *
  5930. * Текущий тир
  5931. */
  5932. let currTier = 0;
  5933. /**
  5934. * Number of battles on the current dash
  5935. *
  5936. * Количество битв на текущем тире
  5937. */
  5938. let countRivalsTier = 0;
  5939.  
  5940. let callsStart = {
  5941. calls: [{
  5942. name: "titanArenaGetStatus",
  5943. args: {},
  5944. ident: "titanArenaGetStatus"
  5945. }, {
  5946. name: "teamGetAll",
  5947. args: {},
  5948. ident: "teamGetAll"
  5949. }]
  5950. }
  5951.  
  5952. this.start = function () {
  5953. send(JSON.stringify(callsStart), startTitanArena);
  5954. }
  5955.  
  5956. function startTitanArena(data) {
  5957. let titanArena = data.results[0].result.response;
  5958. if (titanArena.status == 'disabled') {
  5959. endTitanArena('disabled', titanArena);
  5960. return;
  5961. }
  5962.  
  5963. let teamGetAll = data.results[1].result.response;
  5964. titan_arena = teamGetAll.titan_arena;
  5965.  
  5966. checkTier(titanArena)
  5967. }
  5968.  
  5969. function checkTier(titanArena) {
  5970. if (titanArena.status == "peace_time") {
  5971. endTitanArena('Peace_time', titanArena);
  5972. return;
  5973. }
  5974. currTier = titanArena.tier;
  5975. if (currTier) {
  5976. setProgress(`${I18N('TITAN_ARENA')}: ${I18N('LEVEL')} ${currTier}`);
  5977. }
  5978.  
  5979. if (titanArena.status == "completed_tier") {
  5980. titanArenaCompleteTier();
  5981. return;
  5982. }
  5983. /**
  5984. * Checking for the possibility of a raid
  5985. * Проверка на возможность рейда
  5986. */
  5987. if (titanArena.canRaid) {
  5988. titanArenaStartRaid();
  5989. return;
  5990. }
  5991. /**
  5992. * Check was an attempt to achieve the current shooting range
  5993. * Проверка была ли попытка добития текущего тира
  5994. */
  5995. if (!isCheckCurrentTier) {
  5996. checkRivals(titanArena.rivals);
  5997. return;
  5998. }
  5999.  
  6000. endTitanArena('Done or not canRaid', titanArena);
  6001. }
  6002. /**
  6003. * Submit dash information for verification
  6004. *
  6005. * Отправка информации о тире на проверку
  6006. */
  6007. function checkResultInfo(data) {
  6008. let titanArena = data.results[0].result.response;
  6009. checkTier(titanArena);
  6010. }
  6011. /**
  6012. * Finish the current tier
  6013. *
  6014. * Завершить текущий тир
  6015. */
  6016. function titanArenaCompleteTier() {
  6017. isCheckCurrentTier = false;
  6018. let calls = [{
  6019. name: "titanArenaCompleteTier",
  6020. args: {},
  6021. ident: "body"
  6022. }];
  6023. send(JSON.stringify({calls}), checkResultInfo);
  6024. }
  6025. /**
  6026. * Gathering points to be completed
  6027. *
  6028. * Собираем точки которые нужно добить
  6029. */
  6030. function checkRivals(rivals) {
  6031. finishListBattle = [];
  6032. for (let n in rivals) {
  6033. if (rivals[n].attackScore < 250) {
  6034. finishListBattle.push(n);
  6035. }
  6036. }
  6037. console.log('checkRivals', finishListBattle);
  6038. countRivalsTier = finishListBattle.length;
  6039. roundRivals();
  6040. }
  6041. /**
  6042. * Selecting the next point to finish off
  6043. *
  6044. * Выбор следующей точки для добития
  6045. */
  6046. function roundRivals() {
  6047. let countRivals = finishListBattle.length;
  6048. if (!countRivals) {
  6049. /**
  6050. * Whole range checked
  6051. *
  6052. * Весь тир проверен
  6053. */
  6054. isCheckCurrentTier = true;
  6055. titanArenaGetStatus();
  6056. return;
  6057. }
  6058. // setProgress('TitanArena: Уровень ' + currTier + ' Бои: ' + (countRivalsTier - countRivals + 1) + '/' + countRivalsTier);
  6059. currentRival = finishListBattle.pop();
  6060. attempts = +currentRival;
  6061. // console.log('roundRivals', currentRival);
  6062. titanArenaStartBattle(currentRival);
  6063. }
  6064. /**
  6065. * The start of a solo battle
  6066. *
  6067. * Начало одиночной битвы
  6068. */
  6069. function titanArenaStartBattle(rivalId) {
  6070. let calls = [{
  6071. name: "titanArenaStartBattle",
  6072. args: {
  6073. rivalId: rivalId,
  6074. titans: titan_arena
  6075. },
  6076. ident: "body"
  6077. }];
  6078. send(JSON.stringify({calls}), calcResult);
  6079. }
  6080. /**
  6081. * Calculation of the results of the battle
  6082. *
  6083. * Расчет результатов боя
  6084. */
  6085. function calcResult(data) {
  6086. let battlesInfo = data.results[0].result.response.battle;
  6087. /**
  6088. * If attempts are equal to the current battle number we make
  6089. * Если попытки равны номеру текущего боя делаем прерасчет
  6090. */
  6091. if (attempts == currentRival) {
  6092. preCalcBattle(battlesInfo);
  6093. return;
  6094. }
  6095. /**
  6096. * If there are still attempts, we calculate a new battle
  6097. * Если попытки еще есть делаем расчет нового боя
  6098. */
  6099. if (attempts > 0) {
  6100. attempts--;
  6101. calcBattleResult(battlesInfo)
  6102. .then(resultCalcBattle);
  6103. return;
  6104. }
  6105. /**
  6106. * Otherwise, go to the next opponent
  6107. * Иначе переходим к следующему сопернику
  6108. */
  6109. roundRivals();
  6110. }
  6111. /**
  6112. * Processing the results of the battle calculation
  6113. *
  6114. * Обработка результатов расчета битвы
  6115. */
  6116. function resultCalcBattle(resultBattle) {
  6117. // console.log('resultCalcBattle', currentRival, attempts, resultBattle.result.win);
  6118. /**
  6119. * If the current calculation of victory is not a chance or the attempt ended with the finish the battle
  6120. * Если текущий расчет победа или шансов нет или попытки кончились завершаем бой
  6121. */
  6122. if (resultBattle.result.win || !attempts) {
  6123. titanArenaEndBattle({
  6124. progress: resultBattle.progress,
  6125. result: resultBattle.result,
  6126. rivalId: resultBattle.battleData.typeId
  6127. });
  6128. return;
  6129. }
  6130. /**
  6131. * If not victory and there are attempts we start a new battle
  6132. * Если не победа и есть попытки начинаем новый бой
  6133. */
  6134. titanArenaStartBattle(resultBattle.battleData.typeId);
  6135. }
  6136. /**
  6137. * Returns the promise of calculating the results of the battle
  6138. *
  6139. * Возращает промис расчета результатов битвы
  6140. */
  6141. function getBattleInfo(battle, isRandSeed) {
  6142. return new Promise(function (resolve) {
  6143. if (isRandSeed) {
  6144. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  6145. }
  6146. // console.log(battle.seed);
  6147. BattleCalc(battle, "get_titanClanPvp", e => resolve(e));
  6148. });
  6149. }
  6150. /**
  6151. * Recalculate battles
  6152. *
  6153. * Прерасчтет битвы
  6154. */
  6155. function preCalcBattle(battle) {
  6156. let actions = [getBattleInfo(battle, false)];
  6157. const countTestBattle = getInput('countTestBattle');
  6158. for (let i = 0; i < countTestBattle; i++) {
  6159. actions.push(getBattleInfo(battle, true));
  6160. }
  6161. Promise.all(actions)
  6162. .then(resultPreCalcBattle);
  6163. }
  6164. /**
  6165. * Processing the results of the battle recalculation
  6166. *
  6167. * Обработка результатов прерасчета битвы
  6168. */
  6169. function resultPreCalcBattle(e) {
  6170. let wins = e.map(n => n.result.win);
  6171. let firstBattle = e.shift();
  6172. let countWin = wins.reduce((w, s) => w + s);
  6173. const countTestBattle = getInput('countTestBattle');
  6174. console.log('resultPreCalcBattle', `${countWin}/${countTestBattle}`)
  6175. if (countWin > 0) {
  6176. attempts = getInput('countAutoBattle');
  6177. } else {
  6178. attempts = 0;
  6179. }
  6180. resultCalcBattle(firstBattle);
  6181. }
  6182.  
  6183. /**
  6184. * Complete an arena battle
  6185. *
  6186. * Завершить битву на арене
  6187. */
  6188. function titanArenaEndBattle(args) {
  6189. let calls = [{
  6190. name: "titanArenaEndBattle",
  6191. args,
  6192. ident: "body"
  6193. }];
  6194. send(JSON.stringify({calls}), resultTitanArenaEndBattle);
  6195. }
  6196.  
  6197. function resultTitanArenaEndBattle(e) {
  6198. let attackScore = e.results[0].result.response.attackScore;
  6199. let numReval = countRivalsTier - finishListBattle.length;
  6200. setProgress(`${I18N('TITAN_ARENA')}: ${I18N('LEVEL')} ${currTier} </br>${I18N('BATTLES')}: ${numReval}/${countRivalsTier} - ${attackScore}`);
  6201. /**
  6202. * TODO: Might need to improve the results.
  6203. * TODO: Возможно стоит сделать улучшение результатов
  6204. */
  6205. // console.log('resultTitanArenaEndBattle', e)
  6206. console.log('resultTitanArenaEndBattle', numReval + '/' + countRivalsTier, attempts)
  6207. roundRivals();
  6208. }
  6209. /**
  6210. * Arena State
  6211. *
  6212. * Состояние арены
  6213. */
  6214. function titanArenaGetStatus() {
  6215. let calls = [{
  6216. name: "titanArenaGetStatus",
  6217. args: {},
  6218. ident: "body"
  6219. }];
  6220. send(JSON.stringify({calls}), checkResultInfo);
  6221. }
  6222. /**
  6223. * Arena Raid Request
  6224. *
  6225. * Запрос рейда арены
  6226. */
  6227. function titanArenaStartRaid() {
  6228. let calls = [{
  6229. name: "titanArenaStartRaid",
  6230. args: {
  6231. titans: titan_arena
  6232. },
  6233. ident: "body"
  6234. }];
  6235. send(JSON.stringify({calls}), calcResults);
  6236. }
  6237.  
  6238. function calcResults(data) {
  6239. let battlesInfo = data.results[0].result.response;
  6240. let {attackers, rivals} = battlesInfo;
  6241.  
  6242. let promises = [];
  6243. for (let n in rivals) {
  6244. rival = rivals[n];
  6245. promises.push(calcBattleResult({
  6246. attackers: attackers,
  6247. defenders: [rival.team],
  6248. seed: rival.seed,
  6249. typeId: n,
  6250. }));
  6251. }
  6252.  
  6253. Promise.all(promises)
  6254. .then(results => {
  6255. const endResults = {};
  6256. for (let info of results) {
  6257. let id = info.battleData.typeId;
  6258. endResults[id] = {
  6259. progress: info.progress,
  6260. result: info.result,
  6261. }
  6262. }
  6263. titanArenaEndRaid(endResults);
  6264. });
  6265. }
  6266.  
  6267. function calcBattleResult(battleData) {
  6268. return new Promise(function (resolve, reject) {
  6269. BattleCalc(battleData, "get_titanClanPvp", resolve);
  6270. });
  6271. }
  6272.  
  6273. /**
  6274. * Sending Raid Results
  6275. *
  6276. * Отправка результатов рейда
  6277. */
  6278. function titanArenaEndRaid(results) {
  6279. titanArenaEndRaidCall = {
  6280. calls: [{
  6281. name: "titanArenaEndRaid",
  6282. args: {
  6283. results
  6284. },
  6285. ident: "body"
  6286. }]
  6287. }
  6288. send(JSON.stringify(titanArenaEndRaidCall), checkRaidResults);
  6289. }
  6290.  
  6291. function checkRaidResults(data) {
  6292. results = data.results[0].result.response.results;
  6293. isSucsesRaid = true;
  6294. for (let i in results) {
  6295. isSucsesRaid &&= (results[i].attackScore >= 250);
  6296. }
  6297.  
  6298. if (isSucsesRaid) {
  6299. titanArenaCompleteTier();
  6300. } else {
  6301. titanArenaGetStatus();
  6302. }
  6303. }
  6304.  
  6305. function titanArenaFarmDailyReward() {
  6306. titanArenaFarmDailyRewardCall = {
  6307. calls: [{
  6308. name: "titanArenaFarmDailyReward",
  6309. args: {},
  6310. ident: "body"
  6311. }]
  6312. }
  6313. send(JSON.stringify(titanArenaFarmDailyRewardCall), () => {console.log('Done farm daily reward')});
  6314. }
  6315.  
  6316. function endTitanArena(reason, info) {
  6317. if (!['Peace_time', 'disabled'].includes(reason)) {
  6318. titanArenaFarmDailyReward();
  6319. }
  6320. console.log(reason, info);
  6321. setProgress(`${I18N('TITAN_ARENA')} ${I18N('COMPLETED')}!`, true);
  6322. resolve();
  6323. }
  6324. }
  6325.  
  6326. this.HWHClasses.executeTitanArena = executeTitanArena;
  6327.  
  6328. function hackGame() {
  6329. const self = this;
  6330. selfGame = null;
  6331. bindId = 1e9;
  6332. this.libGame = null;
  6333. this.doneLibLoad = () => {}
  6334.  
  6335. /**
  6336. * List of correspondence of used classes to their names
  6337. *
  6338. * Список соответствия используемых классов их названиям
  6339. */
  6340. ObjectsList = [
  6341. { name: 'BattlePresets', prop: 'game.battle.controller.thread.BattlePresets' },
  6342. { name: 'DataStorage', prop: 'game.data.storage.DataStorage' },
  6343. { name: 'BattleConfigStorage', prop: 'game.data.storage.battle.BattleConfigStorage' },
  6344. { name: 'BattleInstantPlay', prop: 'game.battle.controller.instant.BattleInstantPlay' },
  6345. { name: 'MultiBattleInstantReplay', prop: 'game.battle.controller.instant.MultiBattleInstantReplay' },
  6346. { name: 'MultiBattleResult', prop: 'game.battle.controller.MultiBattleResult' },
  6347.  
  6348. { name: 'PlayerMissionData', prop: 'game.model.user.mission.PlayerMissionData' },
  6349. { name: 'PlayerMissionBattle', prop: 'game.model.user.mission.PlayerMissionBattle' },
  6350. { name: 'GameModel', prop: 'game.model.GameModel' },
  6351. { name: 'CommandManager', prop: 'game.command.CommandManager' },
  6352. { name: 'MissionCommandList', prop: 'game.command.rpc.mission.MissionCommandList' },
  6353. { name: 'RPCCommandBase', prop: 'game.command.rpc.RPCCommandBase' },
  6354. { name: 'PlayerTowerData', prop: 'game.model.user.tower.PlayerTowerData' },
  6355. { name: 'TowerCommandList', prop: 'game.command.tower.TowerCommandList' },
  6356. { name: 'PlayerHeroTeamResolver', prop: 'game.model.user.hero.PlayerHeroTeamResolver' },
  6357. { name: 'BattlePausePopup', prop: 'game.view.popup.battle.BattlePausePopup' },
  6358. { name: 'BattlePopup', prop: 'game.view.popup.battle.BattlePopup' },
  6359. { name: 'DisplayObjectContainer', prop: 'starling.display.DisplayObjectContainer' },
  6360. { name: 'GuiClipContainer', prop: 'engine.core.clipgui.GuiClipContainer' },
  6361. { name: 'BattlePausePopupClip', prop: 'game.view.popup.battle.BattlePausePopupClip' },
  6362. { name: 'ClipLabel', prop: 'game.view.gui.components.ClipLabel' },
  6363. { name: 'ClipLabelBase', prop: 'game.view.gui.components.ClipLabelBase' },
  6364. { name: 'Translate', prop: 'com.progrestar.common.lang.Translate' },
  6365. { name: 'ClipButtonLabeledCentered', prop: 'game.view.gui.components.ClipButtonLabeledCentered' },
  6366. { name: 'BattlePausePopupMediator', prop: 'game.mediator.gui.popup.battle.BattlePausePopupMediator' },
  6367. { name: 'SettingToggleButton', prop: 'game.mechanics.settings.popup.view.SettingToggleButton' },
  6368. { name: 'PlayerDungeonData', prop: 'game.mechanics.dungeon.model.PlayerDungeonData' },
  6369. { name: 'NextDayUpdatedManager', prop: 'game.model.user.NextDayUpdatedManager' },
  6370. { name: 'BattleController', prop: 'game.battle.controller.BattleController' },
  6371. { name: 'BattleSettingsModel', prop: 'game.battle.controller.BattleSettingsModel' },
  6372. { name: 'BooleanProperty', prop: 'engine.core.utils.property.BooleanProperty' },
  6373. { name: 'RuleStorage', prop: 'game.data.storage.rule.RuleStorage' },
  6374. { name: 'BattleConfig', prop: 'battle.BattleConfig' },
  6375. { name: 'BattleGuiMediator', prop: 'game.battle.gui.BattleGuiMediator' },
  6376. { name: 'BooleanPropertyWriteable', prop: 'engine.core.utils.property.BooleanPropertyWriteable' },
  6377. { name: 'BattleLogEncoder', prop: 'battle.log.BattleLogEncoder' },
  6378. { name: 'BattleLogReader', prop: 'battle.log.BattleLogReader' },
  6379. { name: 'PlayerSubscriptionInfoValueObject', prop: 'game.model.user.subscription.PlayerSubscriptionInfoValueObject' },
  6380. { name: 'AdventureMapCamera', prop: 'game.mechanics.adventure.popup.map.AdventureMapCamera' },
  6381. ];
  6382.  
  6383. /**
  6384. * Contains the game classes needed to write and override game methods
  6385. *
  6386. * Содержит классы игры необходимые для написания и подмены методов игры
  6387. */
  6388. Game = {
  6389. /**
  6390. * Function 'e'
  6391. * Функция 'e'
  6392. */
  6393. bindFunc: function (a, b) {
  6394. if (null == b)
  6395. return null;
  6396. null == b.__id__ && (b.__id__ = bindId++);
  6397. var c;
  6398. null == a.hx__closures__ ? a.hx__closures__ = {} :
  6399. c = a.hx__closures__[b.__id__];
  6400. null == c && (c = b.bind(a), a.hx__closures__[b.__id__] = c);
  6401. return c
  6402. },
  6403. };
  6404.  
  6405. /**
  6406. * Connects to game objects via the object creation event
  6407. *
  6408. * Подключается к объектам игры через событие создания объекта
  6409. */
  6410. function connectGame() {
  6411. for (let obj of ObjectsList) {
  6412. /**
  6413. * https: //stackoverflow.com/questions/42611719/how-to-intercept-and-modify-a-specific-property-for-any-object
  6414. */
  6415. Object.defineProperty(Object.prototype, obj.prop, {
  6416. set: function (value) {
  6417. if (!selfGame) {
  6418. selfGame = this;
  6419. }
  6420. if (!Game[obj.name]) {
  6421. Game[obj.name] = value;
  6422. }
  6423. // console.log('set ' + obj.prop, this, value);
  6424. this[obj.prop + '_'] = value;
  6425. },
  6426. get: function () {
  6427. // console.log('get ' + obj.prop, this);
  6428. return this[obj.prop + '_'];
  6429. }
  6430. });
  6431. }
  6432. }
  6433.  
  6434. /**
  6435. * Game.BattlePresets
  6436. * @param {bool} a isReplay
  6437. * @param {bool} b autoToggleable
  6438. * @param {bool} c auto On Start
  6439. * @param {object} d config
  6440. * @param {bool} f showBothTeams
  6441. */
  6442. /**
  6443. * Returns the results of the battle to the callback function
  6444. * Возвращает в функцию callback результаты боя
  6445. * @param {*} battleData battle data данные боя
  6446. * @param {*} battleConfig combat configuration type options:
  6447. *
  6448. * тип конфигурации боя варианты:
  6449. *
  6450. * "get_invasion", "get_titanPvpManual", "get_titanPvp",
  6451. * "get_titanClanPvp","get_clanPvp","get_titan","get_boss",
  6452. * "get_tower","get_pve","get_pvpManual","get_pvp","get_core"
  6453. *
  6454. * You can specify the xYc function in the game.assets.storage.BattleAssetStorage class
  6455. *
  6456. * Можно уточнить в классе game.assets.storage.BattleAssetStorage функция xYc
  6457. * @param {*} callback функция в которую вернуться результаты боя
  6458. */
  6459. this.BattleCalc = function (battleData, battleConfig, callback) {
  6460. // battleConfig = battleConfig || getBattleType(battleData.type)
  6461. if (!Game.BattlePresets) throw Error('Use connectGame');
  6462. battlePresets = new Game.BattlePresets(battleData.progress, !1, !0, Game.DataStorage[getFn(Game.DataStorage, 24)][getF(Game.BattleConfigStorage, battleConfig)](), !1);
  6463. let battleInstantPlay;
  6464. if (battleData.progress?.length > 1) {
  6465. battleInstantPlay = new Game.MultiBattleInstantReplay(battleData, battlePresets);
  6466. } else {
  6467. battleInstantPlay = new Game.BattleInstantPlay(battleData, battlePresets);
  6468. }
  6469. battleInstantPlay[getProtoFn(Game.BattleInstantPlay, 9)].add((battleInstant) => {
  6470. const MBR_2 = getProtoFn(Game.MultiBattleResult, 2);
  6471. const battleResults = battleInstant[getF(Game.BattleInstantPlay, 'get_result')]();
  6472. const battleData = battleInstant[getF(Game.BattleInstantPlay, 'get_rawBattleInfo')]();
  6473. const battleLogs = [];
  6474. const timeLimit = battlePresets[getF(Game.BattlePresets, 'get_timeLimit')]();
  6475. let battleTime = 0;
  6476. let battleTimer = 0;
  6477. for (const battleResult of battleResults[MBR_2]) {
  6478. const battleLog = Game.BattleLogEncoder.read(new Game.BattleLogReader(battleResult));
  6479. battleLogs.push(battleLog);
  6480. const maxTime = Math.max(...battleLog.map((e) => (e.time < timeLimit && e.time !== 168.8 ? e.time : 0)));
  6481. battleTimer += getTimer(maxTime)
  6482. battleTime += maxTime;
  6483. }
  6484. callback({
  6485. battleLogs,
  6486. battleTime,
  6487. battleTimer,
  6488. battleData,
  6489. progress: battleResults[getF(Game.MultiBattleResult, 'get_progress')](),
  6490. result: battleResults[getF(Game.MultiBattleResult, 'get_result')](),
  6491. });
  6492. });
  6493. battleInstantPlay.start();
  6494. }
  6495.  
  6496. /**
  6497. * Returns a function with the specified name from the class
  6498. *
  6499. * Возвращает из класса функцию с указанным именем
  6500. * @param {Object} classF Class // класс
  6501. * @param {String} nameF function name // имя функции
  6502. * @param {String} pos name and alias order // порядок имени и псевдонима
  6503. * @returns
  6504. */
  6505. function getF(classF, nameF, pos) {
  6506. pos = pos || false;
  6507. let prop = Object.entries(classF.prototype.__properties__)
  6508. if (!pos) {
  6509. return prop.filter((e) => e[1] == nameF).pop()[0];
  6510. } else {
  6511. return prop.filter((e) => e[0] == nameF).pop()[1];
  6512. }
  6513. }
  6514.  
  6515. /**
  6516. * Returns a function with the specified name from the class
  6517. *
  6518. * Возвращает из класса функцию с указанным именем
  6519. * @param {Object} classF Class // класс
  6520. * @param {String} nameF function name // имя функции
  6521. * @returns
  6522. */
  6523. function getFnP(classF, nameF) {
  6524. let prop = Object.entries(classF.__properties__)
  6525. return prop.filter((e) => e[1] == nameF).pop()[0];
  6526. }
  6527.  
  6528. /**
  6529. * Returns the function name with the specified ordinal from the class
  6530. *
  6531. * Возвращает имя функции с указаным порядковым номером из класса
  6532. * @param {Object} classF Class // класс
  6533. * @param {Number} nF Order number of function // порядковый номер функции
  6534. * @returns
  6535. */
  6536. function getFn(classF, nF) {
  6537. let prop = Object.keys(classF);
  6538. return prop[nF];
  6539. }
  6540.  
  6541. /**
  6542. * Returns the name of the function with the specified serial number from the prototype of the class
  6543. *
  6544. * Возвращает имя функции с указаным порядковым номером из прототипа класса
  6545. * @param {Object} classF Class // класс
  6546. * @param {Number} nF Order number of function // порядковый номер функции
  6547. * @returns
  6548. */
  6549. function getProtoFn(classF, nF) {
  6550. let prop = Object.keys(classF.prototype);
  6551. return prop[nF];
  6552. }
  6553. /**
  6554. * Description of replaced functions
  6555. *
  6556. * Описание подменяемых функций
  6557. */
  6558. replaceFunction = {
  6559. company: function () {
  6560. let PMD_12 = getProtoFn(Game.PlayerMissionData, 12);
  6561. let oldSkipMisson = Game.PlayerMissionData.prototype[PMD_12];
  6562. Game.PlayerMissionData.prototype[PMD_12] = function (a, b, c) {
  6563. if (!isChecked('passBattle')) {
  6564. oldSkipMisson.call(this, a, b, c);
  6565. return;
  6566. }
  6567.  
  6568. try {
  6569. this[getProtoFn(Game.PlayerMissionData, 9)] = new Game.PlayerMissionBattle(a, b, c);
  6570.  
  6571. var a = new Game.BattlePresets(
  6572. !1,
  6573. !1,
  6574. !0,
  6575. Game.DataStorage[getFn(Game.DataStorage, 24)][getProtoFn(Game.BattleConfigStorage, 20)](),
  6576. !1
  6577. );
  6578. a = new Game.BattleInstantPlay(c, a);
  6579. a[getProtoFn(Game.BattleInstantPlay, 9)].add(Game.bindFunc(this, this.P$h));
  6580. a.start();
  6581. } catch (error) {
  6582. console.error('company', error);
  6583. oldSkipMisson.call(this, a, b, c);
  6584. }
  6585. };
  6586.  
  6587. Game.PlayerMissionData.prototype.P$h = function (a) {
  6588. let GM_2 = getFn(Game.GameModel, 2);
  6589. let GM_P2 = getProtoFn(Game.GameModel, 2);
  6590. let CM_20 = getProtoFn(Game.CommandManager, 20);
  6591. let MCL_2 = getProtoFn(Game.MissionCommandList, 2);
  6592. let MBR_15 = getF(Game.MultiBattleResult, 'get_result');
  6593. let RPCCB_15 = getProtoFn(Game.RPCCommandBase, 16);
  6594. let PMD_32 = getProtoFn(Game.PlayerMissionData, 32);
  6595. Game.GameModel[GM_2]()[GM_P2][CM_20][MCL_2](a[MBR_15]())[RPCCB_15](Game.bindFunc(this, this[PMD_32]));
  6596. };
  6597. },
  6598. /*
  6599. tower: function () {
  6600. let PTD_67 = getProtoFn(Game.PlayerTowerData, 67);
  6601. let oldSkipTower = Game.PlayerTowerData.prototype[PTD_67];
  6602. Game.PlayerTowerData.prototype[PTD_67] = function (a) {
  6603. if (!isChecked('passBattle')) {
  6604. oldSkipTower.call(this, a);
  6605. return;
  6606. }
  6607. try {
  6608. var p = new Game.BattlePresets(
  6609. !1,
  6610. !1,
  6611. !0,
  6612. Game.DataStorage[getFn(Game.DataStorage, 24)][getProtoFn(Game.BattleConfigStorage, 20)](),
  6613. !1
  6614. );
  6615. a = new Game.BattleInstantPlay(a, p);
  6616. a[getProtoFn(Game.BattleInstantPlay, 9)].add(Game.bindFunc(this, this.P$h));
  6617. a.start();
  6618. } catch (error) {
  6619. console.error('tower', error);
  6620. oldSkipMisson.call(this, a, b, c);
  6621. }
  6622. };
  6623.  
  6624. Game.PlayerTowerData.prototype.P$h = function (a) {
  6625. const GM_2 = getFnP(Game.GameModel, 'get_instance');
  6626. const GM_P2 = getProtoFn(Game.GameModel, 2);
  6627. const CM_29 = getProtoFn(Game.CommandManager, 29);
  6628. const TCL_5 = getProtoFn(Game.TowerCommandList, 5);
  6629. const MBR_15 = getF(Game.MultiBattleResult, 'get_result');
  6630. const RPCCB_15 = getProtoFn(Game.RPCCommandBase, 17);
  6631. const PTD_78 = getProtoFn(Game.PlayerTowerData, 78);
  6632. Game.GameModel[GM_2]()[GM_P2][CM_29][TCL_5](a[MBR_15]())[RPCCB_15](Game.bindFunc(this, this[PTD_78]));
  6633. };
  6634. },
  6635. */
  6636. // skipSelectHero: function() {
  6637. // if (!HOST) throw Error('Use connectGame');
  6638. // Game.PlayerHeroTeamResolver.prototype[getProtoFn(Game.PlayerHeroTeamResolver, 3)] = () => false;
  6639. // },
  6640. passBattle: function () {
  6641. let BPP_4 = getProtoFn(Game.BattlePausePopup, 4);
  6642. let oldPassBattle = Game.BattlePausePopup.prototype[BPP_4];
  6643. Game.BattlePausePopup.prototype[BPP_4] = function (a) {
  6644. if (!isChecked('passBattle')) {
  6645. oldPassBattle.call(this, a);
  6646. return;
  6647. }
  6648. try {
  6649. Game.BattlePopup.prototype[getProtoFn(Game.BattlePausePopup, 4)].call(this, a);
  6650. this[getProtoFn(Game.BattlePausePopup, 3)]();
  6651. this[getProtoFn(Game.DisplayObjectContainer, 3)](this.clip[getProtoFn(Game.GuiClipContainer, 2)]());
  6652. this.clip[getProtoFn(Game.BattlePausePopupClip, 1)][getProtoFn(Game.ClipLabelBase, 9)](
  6653. Game.Translate.translate('UI_POPUP_BATTLE_PAUSE')
  6654. );
  6655.  
  6656. this.clip[getProtoFn(Game.BattlePausePopupClip, 2)][getProtoFn(Game.ClipButtonLabeledCentered, 2)](
  6657. Game.Translate.translate('UI_POPUP_BATTLE_RETREAT'),
  6658. ((q = this[getProtoFn(Game.BattlePausePopup, 1)]), Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 17)]))
  6659. );
  6660. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 2)](
  6661. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 14)](),
  6662. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 13)]()
  6663. ? ((q = this[getProtoFn(Game.BattlePausePopup, 1)]), Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 18)]))
  6664. : ((q = this[getProtoFn(Game.BattlePausePopup, 1)]), Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 18)]))
  6665. );
  6666.  
  6667. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 0)][
  6668. getProtoFn(Game.ClipLabelBase, 24)
  6669. ]();
  6670. this.clip[getProtoFn(Game.BattlePausePopupClip, 3)][getProtoFn(Game.SettingToggleButton, 3)](
  6671. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 9)]()
  6672. );
  6673. this.clip[getProtoFn(Game.BattlePausePopupClip, 4)][getProtoFn(Game.SettingToggleButton, 3)](
  6674. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 10)]()
  6675. );
  6676. this.clip[getProtoFn(Game.BattlePausePopupClip, 6)][getProtoFn(Game.SettingToggleButton, 3)](
  6677. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 11)]()
  6678. );
  6679. } catch (error) {
  6680. console.error('passBattle', error);
  6681. oldPassBattle.call(this, a);
  6682. }
  6683. };
  6684.  
  6685. let retreatButtonLabel = getF(Game.BattlePausePopupMediator, 'get_retreatButtonLabel');
  6686. let oldFunc = Game.BattlePausePopupMediator.prototype[retreatButtonLabel];
  6687. Game.BattlePausePopupMediator.prototype[retreatButtonLabel] = function () {
  6688. if (isChecked('passBattle')) {
  6689. return I18N('BTN_PASS');
  6690. } else {
  6691. return oldFunc.call(this);
  6692. }
  6693. };
  6694. },
  6695. endlessCards: function () {
  6696. let PDD_21 = getProtoFn(Game.PlayerDungeonData, 21);
  6697. let oldEndlessCards = Game.PlayerDungeonData.prototype[PDD_21];
  6698. Game.PlayerDungeonData.prototype[PDD_21] = function () {
  6699. if (countPredictionCard <= 0) {
  6700. return true;
  6701. } else {
  6702. return oldEndlessCards.call(this);
  6703. }
  6704. };
  6705. },
  6706. speedBattle: function () {
  6707. const get_timeScale = getF(Game.BattleController, 'get_timeScale');
  6708. const oldSpeedBattle = Game.BattleController.prototype[get_timeScale];
  6709. Game.BattleController.prototype[get_timeScale] = function () {
  6710. const speedBattle = Number.parseFloat(getInput('speedBattle'));
  6711. if (!speedBattle) {
  6712. return oldSpeedBattle.call(this);
  6713. }
  6714. try {
  6715. const BC_12 = getProtoFn(Game.BattleController, 12);
  6716. const BSM_12 = getProtoFn(Game.BattleSettingsModel, 12);
  6717. const BP_get_value = getF(Game.BooleanProperty, 'get_value');
  6718. if (this[BC_12][BSM_12][BP_get_value]()) {
  6719. return 0;
  6720. }
  6721. const BSM_2 = getProtoFn(Game.BattleSettingsModel, 2);
  6722. const BC_49 = getProtoFn(Game.BattleController, 49);
  6723. const BSM_1 = getProtoFn(Game.BattleSettingsModel, 1);
  6724. const BC_14 = getProtoFn(Game.BattleController, 14);
  6725. const BC_3 = getFn(Game.BattleController, 3);
  6726. if (this[BC_12][BSM_2][BP_get_value]()) {
  6727. var a = speedBattle * this[BC_49]();
  6728. } else {
  6729. a = this[BC_12][BSM_1][BP_get_value]();
  6730. const maxSpeed = Math.max(...this[BC_14]);
  6731. const multiple = a == this[BC_14].indexOf(maxSpeed) ? (maxSpeed >= 4 ? speedBattle : this[BC_14][a]) : this[BC_14][a];
  6732. a = multiple * Game.BattleController[BC_3][BP_get_value]() * this[BC_49]();
  6733. }
  6734. const BSM_24 = getProtoFn(Game.BattleSettingsModel, 24);
  6735. a > this[BC_12][BSM_24][BP_get_value]() && (a = this[BC_12][BSM_24][BP_get_value]());
  6736. const DS_23 = getFn(Game.DataStorage, 23);
  6737. const get_battleSpeedMultiplier = getF(Game.RuleStorage, 'get_battleSpeedMultiplier', true);
  6738. var b = Game.DataStorage[DS_23][get_battleSpeedMultiplier]();
  6739. const R_1 = getFn(selfGame.Reflect, 1);
  6740. const BC_1 = getFn(Game.BattleController, 1);
  6741. const get_config = getF(Game.BattlePresets, 'get_config');
  6742. null != b &&
  6743. (a = selfGame.Reflect[R_1](b, this[BC_1][get_config]().ident)
  6744. ? a * selfGame.Reflect[R_1](b, this[BC_1][get_config]().ident)
  6745. : a * selfGame.Reflect[R_1](b, 'default'));
  6746. return a;
  6747. } catch (error) {
  6748. console.error('passBatspeedBattletle', error);
  6749. return oldSpeedBattle.call(this);
  6750. }
  6751. };
  6752. },
  6753.  
  6754. /**
  6755. * Acceleration button without Valkyries favor
  6756. *
  6757. * Кнопка ускорения без Покровительства Валькирий
  6758. */
  6759. battleFastKey: function () {
  6760. const BGM_44 = getProtoFn(Game.BattleGuiMediator, 44);
  6761. const oldBattleFastKey = Game.BattleGuiMediator.prototype[BGM_44];
  6762. Game.BattleGuiMediator.prototype[BGM_44] = function () {
  6763. let flag = true;
  6764. //console.log(flag)
  6765. if (!flag) {
  6766. return oldBattleFastKey.call(this);
  6767. }
  6768. try {
  6769. const BGM_9 = getProtoFn(Game.BattleGuiMediator, 9);
  6770. const BGM_10 = getProtoFn(Game.BattleGuiMediator, 10);
  6771. const BPW_0 = getProtoFn(Game.BooleanPropertyWriteable, 0);
  6772. this[BGM_9][BPW_0](true);
  6773. this[BGM_10][BPW_0](true);
  6774. } catch (error) {
  6775. console.error(error);
  6776. return oldBattleFastKey.call(this);
  6777. }
  6778. };
  6779. },
  6780. fastSeason: function () {
  6781. const GameNavigator = selfGame['game.screen.navigator.GameNavigator'];
  6782. const oldFuncName = getProtoFn(GameNavigator, 18);
  6783. const newFuncName = getProtoFn(GameNavigator, 16);
  6784. const oldFastSeason = GameNavigator.prototype[oldFuncName];
  6785. const newFastSeason = GameNavigator.prototype[newFuncName];
  6786. GameNavigator.prototype[oldFuncName] = function (a, b) {
  6787. if (isChecked('fastSeason')) {
  6788. return newFastSeason.apply(this, [a]);
  6789. } else {
  6790. return oldFastSeason.apply(this, [a, b]);
  6791. }
  6792. };
  6793. },
  6794. ShowChestReward: function () {
  6795. const TitanArtifactChest = selfGame['game.mechanics.titan_arena.mediator.chest.TitanArtifactChestRewardPopupMediator'];
  6796. const getOpenAmountTitan = getF(TitanArtifactChest, 'get_openAmount');
  6797. const oldGetOpenAmountTitan = TitanArtifactChest.prototype[getOpenAmountTitan];
  6798. TitanArtifactChest.prototype[getOpenAmountTitan] = function () {
  6799. if (correctShowOpenArtifact) {
  6800. correctShowOpenArtifact--;
  6801. return 100;
  6802. }
  6803. return oldGetOpenAmountTitan.call(this);
  6804. };
  6805.  
  6806. const ArtifactChest = selfGame['game.view.popup.artifactchest.rewardpopup.ArtifactChestRewardPopupMediator'];
  6807. const getOpenAmount = getF(ArtifactChest, 'get_openAmount');
  6808. const oldGetOpenAmount = ArtifactChest.prototype[getOpenAmount];
  6809. ArtifactChest.prototype[getOpenAmount] = function () {
  6810. if (correctShowOpenArtifact) {
  6811. correctShowOpenArtifact--;
  6812. return 100;
  6813. }
  6814. return oldGetOpenAmount.call(this);
  6815. };
  6816. },
  6817. fixCompany: function () {
  6818. const GameBattleView = selfGame['game.mediator.gui.popup.battle.GameBattleView'];
  6819. const BattleThread = selfGame['game.battle.controller.thread.BattleThread'];
  6820. const getOnViewDisposed = getF(BattleThread, 'get_onViewDisposed');
  6821. const getThread = getF(GameBattleView, 'get_thread');
  6822. const oldFunc = GameBattleView.prototype[getThread];
  6823. GameBattleView.prototype[getThread] = function () {
  6824. return (
  6825. oldFunc.call(this) || {
  6826. [getOnViewDisposed]: async () => {},
  6827. }
  6828. );
  6829. };
  6830. },
  6831. BuyTitanArtifact: function () {
  6832. const BIP_4 = getProtoFn(selfGame['game.view.popup.shop.buy.BuyItemPopup'], 4);
  6833. const BuyItemPopup = selfGame['game.view.popup.shop.buy.BuyItemPopup'];
  6834. const oldFunc = BuyItemPopup.prototype[BIP_4];
  6835. BuyItemPopup.prototype[BIP_4] = function () {
  6836. if (isChecked('countControl')) {
  6837. const BuyTitanArtifactItemPopup = selfGame['game.view.popup.shop.buy.BuyTitanArtifactItemPopup'];
  6838. const BTAP_0 = getProtoFn(BuyTitanArtifactItemPopup, 0);
  6839. if (this[BTAP_0]) {
  6840. const BuyTitanArtifactPopupMediator = selfGame['game.mediator.gui.popup.shop.buy.BuyTitanArtifactItemPopupMediator'];
  6841. const BTAM_1 = getProtoFn(BuyTitanArtifactPopupMediator, 1);
  6842. const BuyItemPopupMediator = selfGame['game.mediator.gui.popup.shop.buy.BuyItemPopupMediator'];
  6843. const BIPM_5 = getProtoFn(BuyItemPopupMediator, 5);
  6844. const BIPM_7 = getProtoFn(BuyItemPopupMediator, 7);
  6845. const BIPM_9 = getProtoFn(BuyItemPopupMediator, 9);
  6846.  
  6847. let need = Math.min(this[BTAP_0][BTAM_1](), this[BTAP_0][BIPM_7]);
  6848. need = need ? need : 60;
  6849. this[BTAP_0][BIPM_9] = need;
  6850. this[BTAP_0][BIPM_5] = 10;
  6851. }
  6852. }
  6853. oldFunc.call(this);
  6854. };
  6855. },
  6856. ClanQuestsFastFarm: function () {
  6857. const VipRuleValueObject = selfGame['game.data.storage.rule.VipRuleValueObject'];
  6858. const getClanQuestsFastFarm = getF(VipRuleValueObject, 'get_clanQuestsFastFarm', 1);
  6859. VipRuleValueObject.prototype[getClanQuestsFastFarm] = function () {
  6860. return 0;
  6861. };
  6862. },
  6863. adventureCamera: function () {
  6864. const AMC_40 = getProtoFn(Game.AdventureMapCamera, 40);
  6865. const AMC_5 = getProtoFn(Game.AdventureMapCamera, 5);
  6866. const oldFunc = Game.AdventureMapCamera.prototype[AMC_40];
  6867. Game.AdventureMapCamera.prototype[AMC_40] = function (a) {
  6868. this[AMC_5] = 0.4;
  6869. oldFunc.bind(this)(a);
  6870. };
  6871. },
  6872. unlockMission: function () {
  6873. const WorldMapStoryDrommerHelper = selfGame['game.mediator.gui.worldmap.WorldMapStoryDrommerHelper'];
  6874. const WMSDH_4 = getFn(WorldMapStoryDrommerHelper, 4);
  6875. const WMSDH_7 = getFn(WorldMapStoryDrommerHelper, 7);
  6876. WorldMapStoryDrommerHelper[WMSDH_4] = function () {
  6877. return true;
  6878. };
  6879. WorldMapStoryDrommerHelper[WMSDH_7] = function () {
  6880. return true;
  6881. };
  6882. },
  6883. };
  6884.  
  6885. /**
  6886. * Starts replacing recorded functions
  6887. *
  6888. * Запускает замену записанных функций
  6889. */
  6890. this.activateHacks = function () {
  6891. if (!selfGame) throw Error('Use connectGame');
  6892. for (let func in replaceFunction) {
  6893. try {
  6894. replaceFunction[func]();
  6895. } catch (error) {
  6896. console.error(error);
  6897. }
  6898. }
  6899. }
  6900.  
  6901. /**
  6902. * Returns the game object
  6903. *
  6904. * Возвращает объект игры
  6905. */
  6906. this.getSelfGame = function () {
  6907. return selfGame;
  6908. }
  6909.  
  6910. /**
  6911. * Updates game data
  6912. *
  6913. * Обновляет данные игры
  6914. */
  6915. this.refreshGame = function () {
  6916. (new Game.NextDayUpdatedManager)[getProtoFn(Game.NextDayUpdatedManager, 5)]();
  6917. try {
  6918. cheats.refreshInventory();
  6919. } catch (e) { }
  6920. }
  6921.  
  6922. /**
  6923. * Update inventory
  6924. *
  6925. * Обновляет инвентарь
  6926. */
  6927. this.refreshInventory = async function () {
  6928. const GM_INST = getFnP(Game.GameModel, "get_instance");
  6929. const GM_0 = getProtoFn(Game.GameModel, 0);
  6930. const P_24 = getProtoFn(selfGame["game.model.user.Player"], 24);
  6931. const Player = Game.GameModel[GM_INST]()[GM_0];
  6932. Player[P_24] = new selfGame["game.model.user.inventory.PlayerInventory"]
  6933. Player[P_24].init(await Send({calls:[{name:"inventoryGet",args:{},ident:"body"}]}).then(e => e.results[0].result.response))
  6934. }
  6935. this.updateInventory = function (reward) {
  6936. const GM_INST = getFnP(Game.GameModel, 'get_instance');
  6937. const GM_0 = getProtoFn(Game.GameModel, 0);
  6938. const P_24 = getProtoFn(selfGame['game.model.user.Player'], 24);
  6939. const Player = Game.GameModel[GM_INST]()[GM_0];
  6940. Player[P_24].init(reward);
  6941. };
  6942.  
  6943. this.updateMap = function (data) {
  6944. const PCDD_21 = getProtoFn(selfGame['game.mechanics.clanDomination.model.PlayerClanDominationData'], 21);
  6945. const P_60 = getProtoFn(selfGame['game.model.user.Player'], 60);
  6946. const GM_0 = getProtoFn(Game.GameModel, 0);
  6947. const getInstance = getFnP(selfGame['Game'], 'get_instance');
  6948. const PlayerClanDominationData = Game.GameModel[getInstance]()[GM_0];
  6949. PlayerClanDominationData[P_60][PCDD_21].update(data);
  6950. };
  6951.  
  6952. /**
  6953. * Change the play screen on windowName
  6954. *
  6955. * Сменить экран игры на windowName
  6956. *
  6957. * Possible options:
  6958. *
  6959. * Возможные варианты:
  6960. *
  6961. * MISSION, ARENA, GRAND, CHEST, SKILLS, SOCIAL_GIFT, CLAN, ENCHANT, TOWER, RATING, CHALLENGE, BOSS, CHAT, CLAN_DUNGEON, CLAN_CHEST, TITAN_GIFT, CLAN_RAID, ASGARD, HERO_ASCENSION, ROLE_ASCENSION, ASCENSION_CHEST, TITAN_MISSION, TITAN_ARENA, TITAN_ARTIFACT, TITAN_ARTIFACT_CHEST, TITAN_VALLEY, TITAN_SPIRITS, TITAN_ARTIFACT_MERCHANT, TITAN_ARENA_HALL_OF_FAME, CLAN_PVP, CLAN_PVP_MERCHANT, CLAN_GLOBAL_PVP, CLAN_GLOBAL_PVP_TITAN, ARTIFACT, ZEPPELIN, ARTIFACT_CHEST, ARTIFACT_MERCHANT, EXPEDITIONS, SUBSCRIPTION, NY2018_GIFTS, NY2018_TREE, NY2018_WELCOME, ADVENTURE, ADVENTURESOLO, SANCTUARY, PET_MERCHANT, PET_LIST, PET_SUMMON, BOSS_RATING_EVENT, BRAWL
  6962. */
  6963. this.goNavigtor = function (windowName) {
  6964. let mechanicStorage = selfGame["game.data.storage.mechanic.MechanicStorage"];
  6965. let window = mechanicStorage[windowName];
  6966. let event = new selfGame["game.mediator.gui.popup.PopupStashEventParams"];
  6967. let Game = selfGame['Game'];
  6968. let navigator = getF(Game, "get_navigator")
  6969. let navigate = getProtoFn(selfGame["game.screen.navigator.GameNavigator"], 20)
  6970. let instance = getFnP(Game, 'get_instance');
  6971. Game[instance]()[navigator]()[navigate](window, event);
  6972. }
  6973.  
  6974. /**
  6975. * Move to the sanctuary cheats.goSanctuary()
  6976. *
  6977. * Переместиться в святилище cheats.goSanctuary()
  6978. */
  6979. this.goSanctuary = () => {
  6980. this.goNavigtor("SANCTUARY");
  6981. }
  6982.  
  6983. /**
  6984. * Go to Guild War
  6985. *
  6986. * Перейти к Войне Гильдий
  6987. */
  6988. this.goClanWar = function() {
  6989. let instance = getFnP(Game.GameModel, 'get_instance')
  6990. let player = Game.GameModel[instance]().A;
  6991. let clanWarSelect = selfGame["game.mechanics.cross_clan_war.popup.selectMode.CrossClanWarSelectModeMediator"];
  6992. new clanWarSelect(player).open();
  6993. }
  6994.  
  6995. /**
  6996. * Go to BrawlShop
  6997. *
  6998. * Переместиться в BrawlShop
  6999. */
  7000. this.goBrawlShop = () => {
  7001. const instance = getFnP(Game.GameModel, 'get_instance')
  7002. const P_36 = getProtoFn(selfGame["game.model.user.Player"], 36);
  7003. const PSD_0 = getProtoFn(selfGame["game.model.user.shop.PlayerShopData"], 0);
  7004. const IM_0 = getProtoFn(selfGame["haxe.ds.IntMap"], 0);
  7005. const PSDE_4 = getProtoFn(selfGame["game.model.user.shop.PlayerShopDataEntry"], 4);
  7006.  
  7007. const player = Game.GameModel[instance]().A;
  7008. const shop = player[P_36][PSD_0][IM_0][1038][PSDE_4];
  7009. const shopPopup = new selfGame["game.mechanics.brawl.mediator.BrawlShopPopupMediator"](player, shop)
  7010. shopPopup.open(new selfGame["game.mediator.gui.popup.PopupStashEventParams"])
  7011. }
  7012.  
  7013. /**
  7014. * Returns all stores from game data
  7015. *
  7016. * Возвращает все магазины из данных игры
  7017. */
  7018. this.getShops = () => {
  7019. const instance = getFnP(Game.GameModel, 'get_instance')
  7020. const P_36 = getProtoFn(selfGame["game.model.user.Player"], 36);
  7021. const PSD_0 = getProtoFn(selfGame["game.model.user.shop.PlayerShopData"], 0);
  7022. const IM_0 = getProtoFn(selfGame["haxe.ds.IntMap"], 0);
  7023.  
  7024. const player = Game.GameModel[instance]().A;
  7025. return player[P_36][PSD_0][IM_0];
  7026. }
  7027.  
  7028. /**
  7029. * Returns the store from the game data by ID
  7030. *
  7031. * Возвращает магазин из данных игры по идетификатору
  7032. */
  7033. this.getShop = (id) => {
  7034. const PSDE_4 = getProtoFn(selfGame["game.model.user.shop.PlayerShopDataEntry"], 4);
  7035. const shops = this.getShops();
  7036. const shop = shops[id]?.[PSDE_4];
  7037. return shop;
  7038. }
  7039.  
  7040. /**
  7041. * Change island map
  7042. *
  7043. * Сменить карту острова
  7044. */
  7045. this.changeIslandMap = (mapId = 2) => {
  7046. const GameInst = getFnP(selfGame['Game'], 'get_instance');
  7047. const GM_0 = getProtoFn(Game.GameModel, 0);
  7048. const P_59 = getProtoFn(selfGame["game.model.user.Player"], 60);
  7049. const PSAD_31 = getProtoFn(selfGame['game.mechanics.season_adventure.model.PlayerSeasonAdventureData'], 31);
  7050. const Player = Game.GameModel[GameInst]()[GM_0];
  7051. Player[P_59][PSAD_31]({ id: mapId, seasonAdventure: { id: mapId, startDate: 1701914400, endDate: 1709690400, closed: false } });
  7052.  
  7053. const GN_15 = getProtoFn(selfGame["game.screen.navigator.GameNavigator"], 17)
  7054. const navigator = getF(selfGame['Game'], "get_navigator");
  7055. selfGame['Game'][GameInst]()[navigator]()[GN_15](new selfGame["game.mediator.gui.popup.PopupStashEventParams"]);
  7056. }
  7057.  
  7058. /**
  7059. * Game library availability tracker
  7060. *
  7061. * Отслеживание доступности игровой библиотеки
  7062. */
  7063. function checkLibLoad() {
  7064. timeout = setTimeout(() => {
  7065. if (Game.GameModel) {
  7066. changeLib();
  7067. } else {
  7068. checkLibLoad();
  7069. }
  7070. }, 100)
  7071. }
  7072.  
  7073. /**
  7074. * Game library data spoofing
  7075. *
  7076. * Подмена данных игровой библиотеки
  7077. */
  7078. function changeLib() {
  7079. console.log('lib connect');
  7080. const originalStartFunc = Game.GameModel.prototype.start;
  7081. Game.GameModel.prototype.start = function (a, b, c) {
  7082. self.libGame = b.raw;
  7083. self.doneLibLoad(self.libGame);
  7084. try {
  7085. const levels = b.raw.seasonAdventure.level;
  7086. for (const id in levels) {
  7087. const level = levels[id];
  7088. level.clientData.graphics.fogged = level.clientData.graphics.visible
  7089. }
  7090. const adv = b.raw.seasonAdventure.list[1];
  7091. adv.clientData.asset = 'dialog_season_adventure_tiles';
  7092. } catch (e) {
  7093. console.warn(e);
  7094. }
  7095. originalStartFunc.call(this, a, b, c);
  7096. }
  7097. }
  7098.  
  7099. this.LibLoad = function() {
  7100. return new Promise((e) => {
  7101. this.doneLibLoad = e;
  7102. });
  7103. }
  7104.  
  7105. /**
  7106. * Returns the value of a language constant
  7107. *
  7108. * Возвращает значение языковой константы
  7109. * @param {*} langConst language constant // языковая константа
  7110. * @returns
  7111. */
  7112. this.translate = function (langConst) {
  7113. return Game.Translate.translate(langConst);
  7114. }
  7115.  
  7116. connectGame();
  7117. checkLibLoad();
  7118. }
  7119.  
  7120. /**
  7121. * Auto collection of gifts
  7122. *
  7123. * Автосбор подарков
  7124. */
  7125. function getAutoGifts() {
  7126. // c3ltYm9scyB0aGF0IG1lYW4gbm90aGluZw==
  7127. let valName = 'giftSendIds_' + userInfo.id;
  7128.  
  7129. if (!localStorage['clearGift' + userInfo.id]) {
  7130. localStorage[valName] = '';
  7131. localStorage['clearGift' + userInfo.id] = '+';
  7132. }
  7133.  
  7134. if (!localStorage[valName]) {
  7135. localStorage[valName] = '';
  7136. }
  7137.  
  7138. const giftsAPI = new ZingerYWebsiteAPI('getGifts.php', arguments);
  7139. /**
  7140. * Submit a request to receive gift codes
  7141. *
  7142. * Отправка запроса для получения кодов подарков
  7143. */
  7144. giftsAPI.request().then((data) => {
  7145. let freebieCheckCalls = {
  7146. calls: [],
  7147. };
  7148. data.forEach((giftId, n) => {
  7149. if (localStorage[valName].includes(giftId)) return;
  7150. freebieCheckCalls.calls.push({
  7151. name: 'registration',
  7152. args: {
  7153. user: { referrer: {} },
  7154. giftId,
  7155. },
  7156. context: {
  7157. actionTs: Math.floor(performance.now()),
  7158. cookie: window?.NXAppInfo?.session_id || null,
  7159. },
  7160. ident: giftId,
  7161. });
  7162. });
  7163.  
  7164. if (!freebieCheckCalls.calls.length) {
  7165. return;
  7166. }
  7167.  
  7168. send(JSON.stringify(freebieCheckCalls), (e) => {
  7169. let countGetGifts = 0;
  7170. const gifts = [];
  7171. for (check of e.results) {
  7172. gifts.push(check.ident);
  7173. if (check.result.response != null) {
  7174. countGetGifts++;
  7175. }
  7176. }
  7177. const saveGifts = localStorage[valName].split(';');
  7178. localStorage[valName] = [...saveGifts, ...gifts].slice(-50).join(';');
  7179. console.log(`${I18N('GIFTS')}: ${countGetGifts}`);
  7180. });
  7181. });
  7182. }
  7183.  
  7184. /**
  7185. * To fill the kills in the Forge of Souls
  7186. *
  7187. * Набить килов в горниле душ
  7188. */
  7189. async function bossRatingEvent() {
  7190. const topGet = await Send(JSON.stringify({ calls: [{ name: "topGet", args: { type: "bossRatingTop", extraId: 0 }, ident: "body" }] }));
  7191. if (!topGet || !topGet.results[0].result.response[0]) {
  7192. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  7193. return;
  7194. }
  7195. const replayId = topGet.results[0].result.response[0].userData.replayId;
  7196. const result = await Send(JSON.stringify({
  7197. calls: [
  7198. { name: "battleGetReplay", args: { id: replayId }, ident: "battleGetReplay" },
  7199. { name: "heroGetAll", args: {}, ident: "heroGetAll" },
  7200. { name: "pet_getAll", args: {}, ident: "pet_getAll" },
  7201. { name: "offerGetAll", args: {}, ident: "offerGetAll" }
  7202. ]
  7203. }));
  7204. const bossEventInfo = result.results[3].result.response.find(e => e.offerType == "bossEvent");
  7205. if (!bossEventInfo) {
  7206. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  7207. return;
  7208. }
  7209. const usedHeroes = bossEventInfo.progress.usedHeroes;
  7210. const party = Object.values(result.results[0].result.response.replay.attackers);
  7211. const availableHeroes = Object.values(result.results[1].result.response).map(e => e.id);
  7212. const availablePets = Object.values(result.results[2].result.response).map(e => e.id);
  7213. const calls = [];
  7214. /**
  7215. * First pack
  7216. *
  7217. * Первая пачка
  7218. */
  7219. const args = {
  7220. heroes: [],
  7221. favor: {}
  7222. }
  7223. for (let hero of party) {
  7224. if (hero.id >= 6000 && availablePets.includes(hero.id)) {
  7225. args.pet = hero.id;
  7226. continue;
  7227. }
  7228. if (!availableHeroes.includes(hero.id) || usedHeroes.includes(hero.id)) {
  7229. continue;
  7230. }
  7231. args.heroes.push(hero.id);
  7232. if (hero.favorPetId) {
  7233. args.favor[hero.id] = hero.favorPetId;
  7234. }
  7235. }
  7236. if (args.heroes.length) {
  7237. calls.push({
  7238. name: "bossRatingEvent_startBattle",
  7239. args,
  7240. ident: "body_0"
  7241. });
  7242. }
  7243. /**
  7244. * Other packs
  7245. *
  7246. * Другие пачки
  7247. */
  7248. let heroes = [];
  7249. let count = 1;
  7250. while (heroId = availableHeroes.pop()) {
  7251. if (args.heroes.includes(heroId) || usedHeroes.includes(heroId)) {
  7252. continue;
  7253. }
  7254. heroes.push(heroId);
  7255. if (heroes.length == 5) {
  7256. calls.push({
  7257. name: "bossRatingEvent_startBattle",
  7258. args: {
  7259. heroes: [...heroes],
  7260. pet: availablePets[Math.floor(Math.random() * availablePets.length)]
  7261. },
  7262. ident: "body_" + count
  7263. });
  7264. heroes = [];
  7265. count++;
  7266. }
  7267. }
  7268.  
  7269. if (!calls.length) {
  7270. setProgress(`${I18N('NO_HEROES')}`, true);
  7271. return;
  7272. }
  7273.  
  7274. const resultBattles = await Send(JSON.stringify({ calls }));
  7275. console.log(resultBattles);
  7276. rewardBossRatingEvent();
  7277. }
  7278.  
  7279. /**
  7280. * Collecting Rewards from the Forge of Souls
  7281. *
  7282. * Сбор награды из Горнила Душ
  7283. */
  7284. function rewardBossRatingEvent() {
  7285. let rewardBossRatingCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  7286. send(rewardBossRatingCall, function (data) {
  7287. let bossEventInfo = data.results[0].result.response.find(e => e.offerType == "bossEvent");
  7288. if (!bossEventInfo) {
  7289. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  7290. return;
  7291. }
  7292.  
  7293. let farmedChests = bossEventInfo.progress.farmedChests;
  7294. let score = bossEventInfo.progress.score;
  7295. setProgress(`${I18N('DAMAGE_AMOUNT')}: ${score}`);
  7296. let revard = bossEventInfo.reward;
  7297.  
  7298. let getRewardCall = {
  7299. calls: []
  7300. }
  7301.  
  7302. let count = 0;
  7303. for (let i = 1; i < 10; i++) {
  7304. if (farmedChests.includes(i)) {
  7305. continue;
  7306. }
  7307. if (score < revard[i].score) {
  7308. break;
  7309. }
  7310. getRewardCall.calls.push({
  7311. name: "bossRatingEvent_getReward",
  7312. args: {
  7313. rewardId: i
  7314. },
  7315. ident: "body_" + i
  7316. });
  7317. count++;
  7318. }
  7319. if (!count) {
  7320. setProgress(`${I18N('NOTHING_TO_COLLECT')}`, true);
  7321. return;
  7322. }
  7323.  
  7324. send(JSON.stringify(getRewardCall), e => {
  7325. console.log(e);
  7326. setProgress(`${I18N('COLLECTED')} ${e?.results?.length} ${I18N('REWARD')}`, true);
  7327. });
  7328. });
  7329. }
  7330.  
  7331. /**
  7332. * Collect Easter eggs and event rewards
  7333. *
  7334. * Собрать пасхалки и награды событий
  7335. */
  7336. function offerFarmAllReward() {
  7337. const offerGetAllCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  7338. return Send(offerGetAllCall).then((data) => {
  7339. const offerGetAll = data.results[0].result.response.filter(e => e.type == "reward" && !e?.freeRewardObtained && e.reward);
  7340. if (!offerGetAll.length) {
  7341. setProgress(`${I18N('NOTHING_TO_COLLECT')}`, true);
  7342. return;
  7343. }
  7344.  
  7345. const calls = [];
  7346. for (let reward of offerGetAll) {
  7347. calls.push({
  7348. name: "offerFarmReward",
  7349. args: {
  7350. offerId: reward.id
  7351. },
  7352. ident: "offerFarmReward_" + reward.id
  7353. });
  7354. }
  7355.  
  7356. return Send(JSON.stringify({ calls })).then(e => {
  7357. console.log(e);
  7358. setProgress(`${I18N('COLLECTED')} ${e?.results?.length} ${I18N('REWARD')}`, true);
  7359. });
  7360. });
  7361. }
  7362.  
  7363. /**
  7364. * Assemble Outland
  7365. *
  7366. * Собрать запределье
  7367. */
  7368. function getOutland() {
  7369. return new Promise(function (resolve, reject) {
  7370. send('{"calls":[{"name":"bossGetAll","args":{},"ident":"bossGetAll"}]}', e => {
  7371. let bosses = e.results[0].result.response;
  7372.  
  7373. let bossRaidOpenChestCall = {
  7374. calls: []
  7375. };
  7376.  
  7377. for (let boss of bosses) {
  7378. if (boss.mayRaid) {
  7379. bossRaidOpenChestCall.calls.push({
  7380. name: "bossRaid",
  7381. args: {
  7382. bossId: boss.id
  7383. },
  7384. ident: "bossRaid_" + boss.id
  7385. });
  7386. bossRaidOpenChestCall.calls.push({
  7387. name: "bossOpenChest",
  7388. args: {
  7389. bossId: boss.id,
  7390. amount: 1,
  7391. starmoney: 0
  7392. },
  7393. ident: "bossOpenChest_" + boss.id
  7394. });
  7395. } else if (boss.chestId == 1) {
  7396. bossRaidOpenChestCall.calls.push({
  7397. name: "bossOpenChest",
  7398. args: {
  7399. bossId: boss.id,
  7400. amount: 1,
  7401. starmoney: 0
  7402. },
  7403. ident: "bossOpenChest_" + boss.id
  7404. });
  7405. }
  7406. }
  7407.  
  7408. if (!bossRaidOpenChestCall.calls.length) {
  7409. setProgress(`${I18N('OUTLAND')} ${I18N('NOTHING_TO_COLLECT')}`, true);
  7410. resolve();
  7411. return;
  7412. }
  7413.  
  7414. send(JSON.stringify(bossRaidOpenChestCall), e => {
  7415. setProgress(`${I18N('OUTLAND')} ${I18N('COLLECTED')}`, true);
  7416. resolve();
  7417. });
  7418. });
  7419. });
  7420. }
  7421.  
  7422. /**
  7423. * Collect all rewards
  7424. *
  7425. * Собрать все награды
  7426. */
  7427. function questAllFarm() {
  7428. return new Promise(function (resolve, reject) {
  7429. let questGetAllCall = {
  7430. calls: [{
  7431. name: "questGetAll",
  7432. args: {},
  7433. ident: "body"
  7434. }]
  7435. }
  7436. send(JSON.stringify(questGetAllCall), function (data) {
  7437. let questGetAll = data.results[0].result.response;
  7438. const questAllFarmCall = {
  7439. calls: []
  7440. }
  7441. let number = 0;
  7442. for (let quest of questGetAll) {
  7443. if (quest.id < 1e6 && quest.state == 2) {
  7444. questAllFarmCall.calls.push({
  7445. name: "questFarm",
  7446. args: {
  7447. questId: quest.id
  7448. },
  7449. ident: `group_${number}_body`
  7450. });
  7451. number++;
  7452. }
  7453. }
  7454.  
  7455. if (!questAllFarmCall.calls.length) {
  7456. setProgress(`${I18N('COLLECTED')} ${number} ${I18N('REWARD')}`, true);
  7457. resolve();
  7458. return;
  7459. }
  7460.  
  7461. send(JSON.stringify(questAllFarmCall), function (res) {
  7462. console.log(res);
  7463. setProgress(`${I18N('COLLECTED')} ${number} ${I18N('REWARD')}`, true);
  7464. resolve();
  7465. });
  7466. });
  7467. })
  7468. }
  7469.  
  7470. /**
  7471. * Mission auto repeat
  7472. *
  7473. * Автоповтор миссии
  7474. * isStopSendMission = false;
  7475. * isSendsMission = true;
  7476. **/
  7477. this.sendsMission = async function (param) {
  7478. if (isStopSendMission) {
  7479. isSendsMission = false;
  7480. console.log(I18N('STOPPED'));
  7481. setProgress('');
  7482. await popup.confirm(`${I18N('STOPPED')}<br>${I18N('REPETITIONS')}: ${param.count}`, [{
  7483. msg: 'Ok',
  7484. result: true
  7485. }, ])
  7486. return;
  7487. }
  7488. lastMissionBattleStart = Date.now();
  7489. let missionStartCall = {
  7490. "calls": [{
  7491. "name": "missionStart",
  7492. "args": lastMissionStart,
  7493. "ident": "body"
  7494. }]
  7495. }
  7496. /**
  7497. * Mission Request
  7498. *
  7499. * Запрос на выполнение мисии
  7500. */
  7501. SendRequest(JSON.stringify(missionStartCall), async e => {
  7502. if (e['error']) {
  7503. isSendsMission = false;
  7504. console.log(e['error']);
  7505. setProgress('');
  7506. let msg = e['error'].name + ' ' + e['error'].description + `<br>${I18N('REPETITIONS')}: ${param.count}`;
  7507. await popup.confirm(msg, [
  7508. {msg: 'Ok', result: true},
  7509. ])
  7510. return;
  7511. }
  7512. /**
  7513. * Mission data calculation
  7514. *
  7515. * Расчет данных мисии
  7516. */
  7517. BattleCalc(e.results[0].result.response, 'get_tower', async r => {
  7518. /** missionTimer */
  7519. let timer = getTimer(r.battleTime) + 5;
  7520. const period = Math.ceil((Date.now() - lastMissionBattleStart) / 1000);
  7521. if (period < timer) {
  7522. timer = timer - period;
  7523. await countdownTimer(timer, `${I18N('MISSIONS_PASSED')}: ${param.count}`);
  7524. }
  7525.  
  7526. let missionEndCall = {
  7527. "calls": [{
  7528. "name": "missionEnd",
  7529. "args": {
  7530. "id": param.id,
  7531. "result": r.result,
  7532. "progress": r.progress
  7533. },
  7534. "ident": "body"
  7535. }]
  7536. }
  7537. /**
  7538. * Mission Completion Request
  7539. *
  7540. * Запрос на завершение миссии
  7541. */
  7542. SendRequest(JSON.stringify(missionEndCall), async (e) => {
  7543. if (e['error']) {
  7544. isSendsMission = false;
  7545. console.log(e['error']);
  7546. setProgress('');
  7547. let msg = e['error'].name + ' ' + e['error'].description + `<br>${I18N('REPETITIONS')}: ${param.count}`;
  7548. await popup.confirm(msg, [
  7549. {msg: 'Ok', result: true},
  7550. ])
  7551. return;
  7552. }
  7553. r = e.results[0].result.response;
  7554. if (r['error']) {
  7555. isSendsMission = false;
  7556. console.log(r['error']);
  7557. setProgress('');
  7558. await popup.confirm(`<br>${I18N('REPETITIONS')}: ${param.count}` + ' 3 ' + r['error'], [
  7559. {msg: 'Ok', result: true},
  7560. ])
  7561. return;
  7562. }
  7563.  
  7564. param.count++;
  7565. setProgress(`${I18N('MISSIONS_PASSED')}: ${param.count} (${I18N('STOP')})`, false, () => {
  7566. isStopSendMission = true;
  7567. });
  7568. setTimeout(sendsMission, 1, param);
  7569. });
  7570. })
  7571. });
  7572. }
  7573.  
  7574. /**
  7575. * Opening of russian dolls
  7576. *
  7577. * Открытие матрешек
  7578. */
  7579. async function openRussianDolls(libId, amount) {
  7580. let sum = 0;
  7581. const sumResult = {};
  7582. let count = 0;
  7583.  
  7584. while (amount) {
  7585. sum += amount;
  7586. setProgress(`${I18N('TOTAL_OPEN')} ${sum}`);
  7587. const calls = [
  7588. {
  7589. name: 'consumableUseLootBox',
  7590. args: { libId, amount },
  7591. ident: 'body',
  7592. },
  7593. ];
  7594. const response = await Send(JSON.stringify({ calls })).then((e) => e.results[0].result.response);
  7595. let [countLootBox, result] = Object.entries(response).pop();
  7596. count += +countLootBox;
  7597. let newCount = 0;
  7598.  
  7599. if (result?.consumable && result.consumable[libId]) {
  7600. newCount = result.consumable[libId];
  7601. delete result.consumable[libId];
  7602. }
  7603.  
  7604. mergeItemsObj(sumResult, result);
  7605. amount = newCount;
  7606. }
  7607.  
  7608. setProgress(`${I18N('TOTAL_OPEN')} ${sum}`, 5000);
  7609. return [count, sumResult];
  7610. }
  7611.  
  7612. function mergeItemsObj(obj1, obj2) {
  7613. for (const key in obj2) {
  7614. if (obj1[key]) {
  7615. if (typeof obj1[key] == 'object') {
  7616. for (const innerKey in obj2[key]) {
  7617. obj1[key][innerKey] = (obj1[key][innerKey] || 0) + obj2[key][innerKey];
  7618. }
  7619. } else {
  7620. obj1[key] += obj2[key] || 0;
  7621. }
  7622. } else {
  7623. obj1[key] = obj2[key];
  7624. }
  7625. }
  7626.  
  7627. return obj1;
  7628. }
  7629.  
  7630. /**
  7631. * Collect all mail, except letters with energy and charges of the portal
  7632. *
  7633. * Собрать всю почту, кроме писем с энергией и зарядами портала
  7634. */
  7635. function mailGetAll() {
  7636. const getMailInfo = '{"calls":[{"name":"mailGetAll","args":{},"ident":"body"}]}';
  7637.  
  7638. return Send(getMailInfo).then(dataMail => {
  7639. const letters = dataMail.results[0].result.response.letters;
  7640. const letterIds = lettersFilter(letters);
  7641. if (!letterIds.length) {
  7642. setProgress(I18N('NOTHING_TO_COLLECT'), true);
  7643. return;
  7644. }
  7645.  
  7646. const calls = [
  7647. { name: "mailFarm", args: { letterIds }, ident: "body" }
  7648. ];
  7649.  
  7650. return Send(JSON.stringify({ calls })).then(res => {
  7651. const lettersIds = res.results[0].result.response;
  7652. if (lettersIds) {
  7653. const countLetters = Object.keys(lettersIds).length;
  7654. setProgress(`${I18N('RECEIVED')} ${countLetters} ${I18N('LETTERS')}`, true);
  7655. }
  7656. });
  7657. });
  7658. }
  7659.  
  7660. /**
  7661. * Filters received emails
  7662. *
  7663. * Фильтрует получаемые письма
  7664. */
  7665. function lettersFilter(letters) {
  7666. const lettersIds = [];
  7667. for (let l in letters) {
  7668. letter = letters[l];
  7669. const reward = letter?.reward;
  7670. if (!reward || !Object.keys(reward).length) {
  7671. continue;
  7672. }
  7673. /**
  7674. * Mail Collection Exceptions
  7675. *
  7676. * Исключения на сбор писем
  7677. */
  7678. const isFarmLetter = !(
  7679. /** Portals // сферы портала */
  7680. (reward?.refillable ? reward.refillable[45] : false) ||
  7681. /** Energy // энергия */
  7682. (reward?.stamina ? reward.stamina : false) ||
  7683. /** accelerating energy gain // ускорение набора энергии */
  7684. (reward?.buff ? true : false) ||
  7685. /** VIP Points // вип очки */
  7686. (reward?.vipPoints ? reward.vipPoints : false) ||
  7687. /** souls of heroes // душы героев */
  7688. (reward?.fragmentHero ? true : false) ||
  7689. /** heroes // герои */
  7690. (reward?.bundleHeroReward ? true : false)
  7691. );
  7692. if (isFarmLetter) {
  7693. lettersIds.push(~~letter.id);
  7694. continue;
  7695. }
  7696. /**
  7697. * Если до окончания годности письма менее 24 часов,
  7698. * то оно собирается не смотря на исключения
  7699. */
  7700. const availableUntil = +letter?.availableUntil;
  7701. if (availableUntil) {
  7702. const maxTimeLeft = 24 * 60 * 60 * 1000;
  7703. const timeLeft = (new Date(availableUntil * 1000) - new Date())
  7704. console.log('Time left:', timeLeft)
  7705. if (timeLeft < maxTimeLeft) {
  7706. lettersIds.push(~~letter.id);
  7707. continue;
  7708. }
  7709. }
  7710. }
  7711. return lettersIds;
  7712. }
  7713.  
  7714. /**
  7715. * Displaying information about the areas of the portal and attempts on the VG
  7716. *
  7717. * Отображение информации о сферах портала и попытках на ВГ
  7718. */
  7719. async function justInfo() {
  7720. return new Promise(async (resolve, reject) => {
  7721. const calls = [{
  7722. name: "userGetInfo",
  7723. args: {},
  7724. ident: "userGetInfo"
  7725. },
  7726. {
  7727. name: "clanWarGetInfo",
  7728. args: {},
  7729. ident: "clanWarGetInfo"
  7730. },
  7731. {
  7732. name: "titanArenaGetStatus",
  7733. args: {},
  7734. ident: "titanArenaGetStatus"
  7735. }];
  7736. const result = await Send(JSON.stringify({ calls }));
  7737. const infos = result.results;
  7738. const portalSphere = infos[0].result.response.refillable.find(n => n.id == 45);
  7739. const clanWarMyTries = infos[1].result.response?.myTries ?? 0;
  7740. const arePointsMax = infos[1].result.response?.arePointsMax;
  7741. const titansLevel = +(infos[2].result.response?.tier ?? 0);
  7742. const titansStatus = infos[2].result.response?.status; //peace_time || battle
  7743.  
  7744. const sanctuaryButton = buttons['goToSanctuary'].button;
  7745. const clanWarButton = buttons['goToClanWar'].button;
  7746. const titansArenaButton = buttons['testTitanArena'].button;
  7747.  
  7748. if (portalSphere.amount) {
  7749. sanctuaryButton.style.color = portalSphere.amount >= 3 ? 'red' : 'brown';
  7750. sanctuaryButton.title = `${I18N('SANCTUARY_TITLE')}\n${portalSphere.amount} ${I18N('PORTALS')}`;
  7751. } else {
  7752. sanctuaryButton.style.color = '';
  7753. sanctuaryButton.title = I18N('SANCTUARY_TITLE');
  7754. }
  7755. if (clanWarMyTries && !arePointsMax) {
  7756. clanWarButton.style.color = 'red';
  7757. clanWarButton.title = `${I18N('GUILD_WAR_TITLE')}\n${clanWarMyTries}${I18N('ATTEMPTS')}`;
  7758. } else {
  7759. clanWarButton.style.color = '';
  7760. clanWarButton.title = I18N('GUILD_WAR_TITLE');
  7761. }
  7762.  
  7763. if (titansLevel < 7 && titansStatus == 'battle') {
  7764. const partColor = Math.floor(125 * titansLevel / 7);
  7765. titansArenaButton.style.color = `rgb(255,${partColor},${partColor})`;
  7766. titansArenaButton.title = `${I18N('TITAN_ARENA_TITLE')}\n${titansLevel} ${I18N('LEVEL')}`;
  7767. } else {
  7768. titansArenaButton.style.color = '';
  7769. titansArenaButton.title = I18N('TITAN_ARENA_TITLE');
  7770. }
  7771.  
  7772. const imgPortal =
  7773. 'data:image/gif;base64,R0lGODlhLwAvAHAAACH5BAEAAP8ALAAAAAAvAC8AhwAAABkQWgjF3krO3ghSjAhSzinF3u+tGWvO3s5rGSmE5gha7+/OWghSrWvmnClShCmUlAiE5u+MGe/W3mvvWmspUmvvGSnOWinOnCnOGWsZjErvnAiUlErvWmsIUkrvGQjOWgjOnAjOGUoZjM6MGe/OIWvv5q1KGSnv5mulGe/vWs7v3ozv3kqEGYxKGWuEWmtSKUrv3mNaCEpKUs7OWiml5ggxWmMpEAgZpRlaCO/35q1rGRkxKWtarSkZrRljKSkZhAjv3msIGRk6CEparQhjWq3v3kql3ozOGe/vnM6tGYytWu9rGWuEGYzO3kqE3gil5s6MWq3vnGvFnM7vWoxrGc5KGYyMWs6tWq2MGYzOnO+tWmvFWkqlWoxrWgAZhEqEWq2tWoytnIyt3krFnGul3mulWmulnEIpUkqlGUqlnK3OnK2MWs7OnClSrSmUte+tnGvFGYytGYzvWs5rWowpGa3O3u/OnErFWoyMnGuE3muEnEqEnIyMGYzOWs7OGe9r3u9rWq3vWq1rWq1r3invWimlWu+t3q0pWq2t3u8pWu8p3q0p3invnCnvGe/vGa2tGa3vGa2tnK0pGe9rnK1rnCmlGe8pGe8pnK0pnGsZrSkp3msp3s7vGYzvnM7vnIzvGc6tnM5r3oxr3gilWs6t3owpWs4pWs4p3owp3s5rnIxrnAilGc4pGc4pnIwpnAgp3kop3s7O3u9KGe+MWoxKWoyM3kIIUgiUte+MnErFGc5KWowIGe9K3u9KWq3OWq1KWq1K3gjvWimEWu+M3q0IWq2M3u8IWu8I3q0I3gjvnAjvGa3OGa2MnK0IGe9KnK1KnCmEGe8IGe8InK0InEoZrSkI3msI3s6MnM5K3oxK3giEWs6M3owIWs4IWs4I3owI3s5KnIxKnAiEGc4IGc4InIwInAgI3koI3kJaCAgQKUIpEGtKUkJSKUIIECla7ylazmtahGta70pa70pahGtazkpazmtrWiExUkprUiljWikQKRkQCAAQCAAACAAAAAj/AP8JHEiwoMGDCBMqXMiwocODJlBIRBHDxMOLBmMEkSjAgICPE2Mw/OUH4z8TGz+agBIBCsuWUAQE0WLwzkAkKZZcnAilhk+fA1bUiEC0ZZABJOD8IyHhwJYDkpakafJQ4kooR5yw0LFihQ4WJhAMKCoARRYSTJgkUOInBZK2DiX2rGHEiI67eFcYATtAAVEoKEiQSFBFDs4UKbg0lGgAigIEeCNzrWvCxIChEcoy3dGiSoITTRQvnCLRrxOveI2McbKahevKJmooiKkFy4Gzg5tMMaMwitwIj/PqGPCugL0CT47ANhEjQg3Atg9IT5CiS4uEUcRIBH4EtREETuB9/xn/BUcBBbBXGGgpoPaBEid23EuXgvdBJhtQGFCwwA7eMgs0gEMDBJD3hR7KbRVbSwP8UcIWJNwjIRLXGZRAAhLVsIACR9y1whMNfNGAHgiUcUSBX8ADWwwKzCYADTSUcMA9ebwQmkFYMMFGhgu80x1XTxSAwxNdGWGCAiG6YQBzly3QkhYxlsDGP1cg4YBBaC0h1zsLPGHXCkfA00AZeu11hALl1VBZXwW0RAaMDGDxTxNdTGEQExJoiUINXCpwmhFOKJCcVmCdOR56MezXJhRvwFlCC2lcWVAUEjBxRobw9HhEXUYekWBlsoVoQEWyFbAAFPRIQQMDJcDQhRhYSv+QZ1kGcAnPYya4BhZYlb1TQ4iI+tVmBPpIQQWrMORxkKwSsEFrDaa+8xgCy1mmgLSHxtDXAhtGMIOxDKjgAkLM7iAAYD4VJ+0RAyAgVl++ikfAESxy62QB365awrjLyprAcxEY4FOmXEp7LbctjlfAAE1yGwEBYBirAgP8GtTUARIMM1QBPrVYQAHF9dgiml/Mexl/3DbAwxnHMqBExQVdLAEMjRXQgHOyydaibPCgqEDH3JrawDosUDExCTATZJuMJ0AAxRNXtLFFPD+P/DB58AC9wH4N4BMxDRPvkPRAbLx3AAlVMLBFCXeQgIaIKJKHQ9X8+forAetMsaoKB7j/MAhCL5j9VFNPJYBGiCGW18CtsvWIs5j7gLEGqyV81gxC6ZBQQgkSMEUCLQckMMLHNhcAD3B+8TdyA0PPACWrB8SH0BItyHAAAwdE4YILTSUww8cELwAyt7D4JSberkd5wA4neIFQE020sMPmJZBwAi0SJMBOA6WTXgAsDYDPOj7r3KNFy5WfkEBCKbTQBQzTM+By5wm4YAPr+LM+IIE27LPOFWswmgqqZ4UEXCEhLUjBGWbgAs3JD2OfWcc68GEDArCOAASwAfnWUYUwtIEKSVCBCiSgPuclpAlImMI9YNDAzeFuMEwQ2w3W4Q530PAGLthBFNqwghCKMAoF3MEB/xNihvr8Ix4sdCCrJja47CVAMFjAwid6eJcQWi8BO4jHQl6AGFjdwwUnOMF75CfCMpoxCTpAoxoZMBgs3qMh7ZODQFYYxgSMsQThCpcK0BiZJNxBCZ7zwhsbYqO3wCoe7AjjCaxAggNUcY94mcDa3qMECWSBHYN0CBfj0IQliEFCMFjkIulAAisUkBZYyB4USxAFCZnkH1xsgltSYCMYyACMpizghS7kOTZIKJMmeYEZzCCH6iCmBS1IRzpkcEsXVMGZMMgHJvfwyoLsYQ9nmMIUuDAFPIAhH8pUZjLbcY89rKKaC9nDFeLxy3vkYwbJTMcL0InOeOSjBVShJz2pqQvPfvrznwANKEMCAgA7';
  7774.  
  7775. setProgress('<img src="' + imgPortal + '" style="height: 25px;position: relative;top: 5px;"> ' + `${portalSphere.amount} </br> ${I18N('GUILD_WAR')}: ${clanWarMyTries}`, true);
  7776. resolve();
  7777. });
  7778. }
  7779.  
  7780. async function getDailyBonus() {
  7781. const dailyBonusInfo = await Send(JSON.stringify({
  7782. calls: [{
  7783. name: "dailyBonusGetInfo",
  7784. args: {},
  7785. ident: "body"
  7786. }]
  7787. })).then(e => e.results[0].result.response);
  7788. const { availableToday, availableVip, currentDay } = dailyBonusInfo;
  7789.  
  7790. if (!availableToday) {
  7791. console.log('Уже собрано');
  7792. return;
  7793. }
  7794.  
  7795. const currentVipPoints = +userInfo.vipPoints;
  7796. const dailyBonusStat = lib.getData('dailyBonusStatic');
  7797. const vipInfo = lib.getData('level').vip;
  7798. let currentVipLevel = 0;
  7799. for (let i in vipInfo) {
  7800. vipLvl = vipInfo[i];
  7801. if (currentVipPoints >= vipLvl.vipPoints) {
  7802. currentVipLevel = vipLvl.level;
  7803. }
  7804. }
  7805. const vipLevelDouble = dailyBonusStat[`${currentDay}_0_0`].vipLevelDouble;
  7806.  
  7807. const calls = [{
  7808. name: "dailyBonusFarm",
  7809. args: {
  7810. vip: availableVip && currentVipLevel >= vipLevelDouble ? 1 : 0
  7811. },
  7812. ident: "body"
  7813. }];
  7814.  
  7815. const result = await Send(JSON.stringify({ calls }));
  7816. if (result.error) {
  7817. console.error(result.error);
  7818. return;
  7819. }
  7820.  
  7821. const reward = result.results[0].result.response;
  7822. const type = Object.keys(reward).pop();
  7823. const itemId = Object.keys(reward[type]).pop();
  7824. const count = reward[type][itemId];
  7825. const itemName = cheats.translate(`LIB_${type.toUpperCase()}_NAME_${itemId}`);
  7826.  
  7827. console.log(`Ежедневная награда: Получено ${count} ${itemName}`, reward);
  7828. }
  7829.  
  7830. async function farmStamina(lootBoxId = 148) {
  7831. const lootBox = await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"}]}')
  7832. .then(e => e.results[0].result.response.consumable[148]);
  7833.  
  7834. /** Добавить другие ящики */
  7835. /**
  7836. * 144 - медная шкатулка
  7837. * 145 - бронзовая шкатулка
  7838. * 148 - платиновая шкатулка
  7839. */
  7840. if (!lootBox) {
  7841. setProgress(I18N('NO_BOXES'), true);
  7842. return;
  7843. }
  7844.  
  7845. let maxFarmEnergy = getSaveVal('maxFarmEnergy', 100);
  7846. const result = await popup.confirm(I18N('OPEN_LOOTBOX', { lootBox }), [
  7847. { result: false, isClose: true },
  7848. { msg: I18N('BTN_YES'), result: true },
  7849. { msg: I18N('STAMINA'), isInput: true, default: maxFarmEnergy },
  7850. ]);
  7851. if (!+result) {
  7852. return;
  7853. }
  7854.  
  7855. if ((typeof result) !== 'boolean' && Number.parseInt(result)) {
  7856. maxFarmEnergy = +result;
  7857. setSaveVal('maxFarmEnergy', maxFarmEnergy);
  7858. } else {
  7859. maxFarmEnergy = 0;
  7860. }
  7861.  
  7862. let collectEnergy = 0;
  7863. for (let count = lootBox; count > 0; count--) {
  7864. const response = await Send('{"calls":[{"name":"consumableUseLootBox","args":{"libId":148,"amount":1},"ident":"body"}]}').then(
  7865. (e) => e.results[0].result.response
  7866. );
  7867. const result = Object.values(response).pop();
  7868. if ('stamina' in result) {
  7869. setProgress(`${I18N('OPEN')}: ${lootBox - count}/${lootBox} ${I18N('STAMINA')} +${result.stamina}<br>${I18N('STAMINA')}: ${collectEnergy}`, false);
  7870. console.log(`${ I18N('STAMINA') } + ${ result.stamina }`);
  7871. if (!maxFarmEnergy) {
  7872. return;
  7873. }
  7874. collectEnergy += +result.stamina;
  7875. if (collectEnergy >= maxFarmEnergy) {
  7876. console.log(`${I18N('STAMINA')} + ${ collectEnergy }`);
  7877. setProgress(`${I18N('STAMINA')} + ${ collectEnergy }`, false);
  7878. return;
  7879. }
  7880. } else {
  7881. setProgress(`${I18N('OPEN')}: ${lootBox - count}/${lootBox}<br>${I18N('STAMINA')}: ${collectEnergy}`, false);
  7882. console.log(result);
  7883. }
  7884. }
  7885.  
  7886. setProgress(I18N('BOXES_OVER'), true);
  7887. }
  7888.  
  7889. async function fillActive() {
  7890. const data = await Send(JSON.stringify({
  7891. calls: [{
  7892. name: "questGetAll",
  7893. args: {},
  7894. ident: "questGetAll"
  7895. }, {
  7896. name: "inventoryGet",
  7897. args: {},
  7898. ident: "inventoryGet"
  7899. }, {
  7900. name: "clanGetInfo",
  7901. args: {},
  7902. ident: "clanGetInfo"
  7903. }
  7904. ]
  7905. })).then(e => e.results.map(n => n.result.response));
  7906.  
  7907. const quests = data[0];
  7908. const inv = data[1];
  7909. const stat = data[2].stat;
  7910. const maxActive = 2000 - stat.todayItemsActivity;
  7911. if (maxActive <= 0) {
  7912. setProgress(I18N('NO_MORE_ACTIVITY'), true);
  7913. return;
  7914. }
  7915. let countGetActive = 0;
  7916. const quest = quests.find(e => e.id > 10046 && e.id < 10051);
  7917. if (quest) {
  7918. countGetActive = 1750 - quest.progress;
  7919. }
  7920. if (countGetActive <= 0) {
  7921. countGetActive = maxActive;
  7922. }
  7923. console.log(countGetActive);
  7924.  
  7925. countGetActive = +(await popup.confirm(I18N('EXCHANGE_ITEMS', { maxActive }), [
  7926. { result: false, isClose: true },
  7927. { msg: I18N('GET_ACTIVITY'), isInput: true, default: countGetActive.toString() },
  7928. ]));
  7929.  
  7930. if (!countGetActive) {
  7931. return;
  7932. }
  7933.  
  7934. if (countGetActive > maxActive) {
  7935. countGetActive = maxActive;
  7936. }
  7937.  
  7938. const items = lib.getData('inventoryItem');
  7939.  
  7940. let itemsInfo = [];
  7941. for (let type of ['gear', 'scroll']) {
  7942. for (let i in inv[type]) {
  7943. const v = items[type][i]?.enchantValue || 0;
  7944. itemsInfo.push({
  7945. id: i,
  7946. count: inv[type][i],
  7947. v,
  7948. type
  7949. })
  7950. }
  7951. const invType = 'fragment' + type.toLowerCase().charAt(0).toUpperCase() + type.slice(1);
  7952. for (let i in inv[invType]) {
  7953. const v = items[type][i]?.fragmentEnchantValue || 0;
  7954. itemsInfo.push({
  7955. id: i,
  7956. count: inv[invType][i],
  7957. v,
  7958. type: invType
  7959. })
  7960. }
  7961. }
  7962. itemsInfo = itemsInfo.filter(e => e.v < 4 && e.count > 200);
  7963. itemsInfo = itemsInfo.sort((a, b) => b.count - a.count);
  7964. console.log(itemsInfo);
  7965. const activeItem = itemsInfo.shift();
  7966. console.log(activeItem);
  7967. const countItem = Math.ceil(countGetActive / activeItem.v);
  7968. if (countItem > activeItem.count) {
  7969. setProgress(I18N('NOT_ENOUGH_ITEMS'), true);
  7970. console.log(activeItem);
  7971. return;
  7972. }
  7973.  
  7974. await Send(JSON.stringify({
  7975. calls: [{
  7976. name: "clanItemsForActivity",
  7977. args: {
  7978. items: {
  7979. [activeItem.type]: {
  7980. [activeItem.id]: countItem
  7981. }
  7982. }
  7983. },
  7984. ident: "body"
  7985. }]
  7986. })).then(e => {
  7987. /** TODO: Вывести потраченые предметы */
  7988. console.log(e);
  7989. setProgress(`${I18N('ACTIVITY_RECEIVED')}: ` + e.results[0].result.response, true);
  7990. });
  7991. }
  7992.  
  7993. async function buyHeroFragments() {
  7994. const result = await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"},{"name":"shopGetAll","args":{},"ident":"shopGetAll"}]}')
  7995. .then(e => e.results.map(n => n.result.response));
  7996. const inv = result[0];
  7997. const shops = Object.values(result[1]).filter(shop => [4, 5, 6, 8, 9, 10, 17].includes(shop.id));
  7998. const calls = [];
  7999.  
  8000. for (let shop of shops) {
  8001. const slots = Object.values(shop.slots);
  8002. for (const slot of slots) {
  8003. /* Уже куплено */
  8004. if (slot.bought) {
  8005. continue;
  8006. }
  8007. /* Не душа героя */
  8008. if (!('fragmentHero' in slot.reward)) {
  8009. continue;
  8010. }
  8011. const coin = Object.keys(slot.cost).pop();
  8012. const coinId = Object.keys(slot.cost[coin]).pop();
  8013. const stock = inv[coin][coinId] || 0;
  8014. /* Не хватает на покупку */
  8015. if (slot.cost[coin][coinId] > stock) {
  8016. continue;
  8017. }
  8018. inv[coin][coinId] -= slot.cost[coin][coinId];
  8019. calls.push({
  8020. name: "shopBuy",
  8021. args: {
  8022. shopId: shop.id,
  8023. slot: slot.id,
  8024. cost: slot.cost,
  8025. reward: slot.reward,
  8026. },
  8027. ident: `shopBuy_${shop.id}_${slot.id}`,
  8028. })
  8029. }
  8030. }
  8031.  
  8032. if (!calls.length) {
  8033. setProgress(I18N('NO_PURCHASABLE_HERO_SOULS'), true);
  8034. return;
  8035. }
  8036.  
  8037. const bought = await Send(JSON.stringify({ calls })).then(e => e.results.map(n => n.result.response));
  8038. if (!bought) {
  8039. console.log('что-то пошло не так')
  8040. return;
  8041. }
  8042.  
  8043. let countHeroSouls = 0;
  8044. for (const buy of bought) {
  8045. countHeroSouls += +Object.values(Object.values(buy).pop()).pop();
  8046. }
  8047. console.log(countHeroSouls, bought, calls);
  8048. setProgress(I18N('PURCHASED_HERO_SOULS', { countHeroSouls }), true);
  8049. }
  8050.  
  8051. /** Открыть платные сундуки в Запределье за 90 */
  8052. async function bossOpenChestPay() {
  8053. const callsNames = ['userGetInfo', 'bossGetAll', 'specialOffer_getAll', 'getTime'];
  8054. const info = await Send({ calls: callsNames.map((name) => ({ name, args: {}, ident: name })) }).then((e) =>
  8055. e.results.map((n) => n.result.response)
  8056. );
  8057.  
  8058. const user = info[0];
  8059. const boses = info[1];
  8060. const offers = info[2];
  8061. const time = info[3];
  8062.  
  8063. const discountOffer = offers.find((e) => e.offerType == 'costReplaceOutlandChest');
  8064.  
  8065. let discount = 1;
  8066. if (discountOffer && discountOffer.endTime > time) {
  8067. discount = 1 - discountOffer.offerData.outlandChest.discountPercent / 100;
  8068. }
  8069.  
  8070. cost9chests = 540 * discount;
  8071. cost18chests = 1740 * discount;
  8072. costFirstChest = 90 * discount;
  8073. costSecondChest = 200 * discount;
  8074.  
  8075. const currentStarMoney = user.starMoney;
  8076. if (currentStarMoney < cost9chests) {
  8077. setProgress('Недостаточно изюма, нужно ' + cost9chests + ' у Вас ' + currentStarMoney, true);
  8078. return;
  8079. }
  8080.  
  8081. const imgEmerald =
  8082. "<img style='position: relative;top: 3px;' src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABkAAAAXCAYAAAD+4+QTAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAY8SURBVEhLpVV5bFVlFv/d7a19W3tfN1pKabGFAm3Rlg4toAWRiH+AioiaqAkaE42NycRR0ZnomJnJYHAJERGNyx/GJYoboo2igKVSMUUKreW1pRvUvr7XvvXe9+7qeW1nGJaJycwvObnny/fl/L7zO+c7l8EV0LAKzA+H83lAFAC/BeDJN2gnc5yd/WaQ8Q0NCCnAANkU+ZfjIpKqJWBOd4EDbHagueBPb1tWuesi9Rqn86zJZDbAMTp4xoSFzMaa4FVe6fra3bbzQbYN6A8Cmrz0qoBx8gzMmaj/QfKHWyxs+4e1DiC78M9v5TTn1RtbVH+kMWlJCCad100VOmQiUWFnNLg4HW42QeYEl3KnIiP5Bzu/dr27o0UistD48k2d8rF9Sib9GZKaejAnOmrs2/6e3VR3q7idF41GWVA41uQQ1RMY00ZJrChcrAYvx8HHaSjil8LLilCY98BORylBKlWQHhjzfvfFnuTfPn1O+xFolzM7s5nMI80rSl7qib8ykRNcWyaUosBWgnN6BL3pHuRwucjmnBTUCjfHwElkNiaNPHYr0mYCKnMeE/r3OC2NQiZZheHsfQ9Vu1uAM+eBIX2W5Nqsh/ewtxlrhl75NtUviDpwq+s+NOXWwWFhKKCd6iCQVByV2qSb0wEo5PvhY9YikGrH3uAdiBtBDIdVVAvlyfjBOffuesTcDxySqD3mUxaOPLZ6aktAOS/kqHaYigN7gnsxMGnDAuEuiPw6ymIt3MwaZFFQB7MeTmYjPLSWjTTCioQ5XCOMJIPeoInD/SNOviy6heLmALkckRTyf3xLbtQ8k6sdOodcxoocMoXU9JoFdF8VESMMiWRJmykyedqXTInaQJnOTtYDcJtZ+DXkRSrOou1cCoHx4LptL0nLgYU8kWhwlFgrNV2wFnEmVAr+w9gUzkwQic2DoNmLYe0QgkYXIuYg4uYYosYQJs1fMGkEpqWzUVucDh9E37gCIWFgvY9FcbniEipii6hbwZVilP0kXB/jysrrPLqU3yDG0JzXhA3OjWgsXo8UG6XbR6AxScqJjJHo/gmY0+9FIOn80I0UkukQFohJNFZmwV/uhosX2j59KPuF8JgS5CI3wHB90RUdKL12pMs7Z3VvfH6WyOajPt+Deb7FRDCBmNmNpNmPhHEWCW0IMXUQaTVEtVPhseYTZRCBeB86h8+hY0yDodsHfny+4NETB7JOLN74TXqmu1Yu4ixHuj3ii0/eaatx7RgY/NYKtR2tm+6B7lbwTGg3bDQ06MLTcsoJettR4DqaC8+u/gfe6HwZOzuGQU8JDR5f1B2+6uHWp8RPSjfsj5/dDyMzfIAj3bqSK8bGW579ECPWXRViHTijDK2BPojcPCxkbXCZflh1H5ISkCCSWJxI8jcjmErhnaHh6fdzdbZTd0aKd7Q+5T/gqj6VyBBkwmfG0QySkkHDJq19dDrgvP3GQq/Pt6h/8mesLqqFz+6DRq0qWkR4uGzEYhrGJBktNdvQGfoJH490YwmNuwKt+LWvWubtAk6GlPHhfw/LCyQz0BXEZOaoLcDf1lAt2z1z5nIhlIsL0Csfo90sWDkHXDYXaq2VWFZShffOfoQc0qOIzT9wbGvpXxOYGgG6SdwLuJSE6mPT1ZNdUdM9fyi8YlnTEiHLc423GBPaFBSVQcrQqcMYrJrbjElVRUf8FIq57K4z/8x7rL9f7ymsb0vHz83GmsXlJJSlsXKhxn3w+YSyrC48vKB0zVbLYqHCUYEe5SekaRYznBuLvU1olwbBmvr4r/v4RzteN4761x+Wxg9dGPH/wkzhL8WRHkMvKo7j/sc/Swfir7ZT/WTYSapc6LwFhc4qSKwLEYHXoz/bnzv8dOw7+4ojyYkvLyfI4MokhNToSKZwYf+6u3e39P3y8XH6AeY5yxHiBcx11OA8rZO9qTdaNx9/n9KPyUdnOulKuFyui6GHAAkHpEDBptqauaKtcMySRBW3HH2Do1+9WbP9GXocVGj5okJfit8jATY06Dh+MBIyiwZrrylb4XXneO1BV9df7n/tMb0/0J17O9LJU7Nn/x+UrKvOyOq58dXtNz0Q2Luz+cUnrqe1q+qmyv8q9/+EypuXZrK2kdEwgW3R5pW/r8I0gN8AVk6uP7Y929oAAAAASUVORK5CYII='>";
  8083.  
  8084. if (currentStarMoney < cost9chests) {
  8085. setProgress(I18N('NOT_ENOUGH_EMERALDS_540', { currentStarMoney, imgEmerald }), true);
  8086. return;
  8087. }
  8088.  
  8089. const buttons = [{ result: false, isClose: true }];
  8090.  
  8091. if (currentStarMoney >= cost9chests) {
  8092. buttons.push({
  8093. msg: I18N('BUY_OUTLAND_BTN', { count: 9, countEmerald: cost9chests, imgEmerald }),
  8094. result: [costFirstChest, costFirstChest, 0],
  8095. });
  8096. }
  8097.  
  8098. if (currentStarMoney >= cost18chests) {
  8099. buttons.push({
  8100. msg: I18N('BUY_OUTLAND_BTN', { count: 18, countEmerald: cost18chests, imgEmerald }),
  8101. result: [costFirstChest, costFirstChest, 0, costSecondChest, costSecondChest, 0],
  8102. });
  8103. }
  8104.  
  8105. const answer = await popup.confirm(`<div style="margin-bottom: 15px;">${I18N('BUY_OUTLAND')}</div>`, buttons);
  8106.  
  8107. if (!answer) {
  8108. return;
  8109. }
  8110.  
  8111. const callBoss = [];
  8112. let n = 0;
  8113. for (let boss of boses) {
  8114. const bossId = boss.id;
  8115. if (boss.chestNum != 2) {
  8116. continue;
  8117. }
  8118. const calls = [];
  8119. for (const starmoney of answer) {
  8120. calls.push({
  8121. name: 'bossOpenChest',
  8122. args: {
  8123. amount: 1,
  8124. bossId,
  8125. starmoney,
  8126. },
  8127. ident: 'bossOpenChest_' + ++n,
  8128. });
  8129. }
  8130. callBoss.push(calls);
  8131. }
  8132.  
  8133. if (!callBoss.length) {
  8134. setProgress(I18N('CHESTS_NOT_AVAILABLE'), true);
  8135. return;
  8136. }
  8137.  
  8138. let count = 0;
  8139. let errors = 0;
  8140. for (const calls of callBoss) {
  8141. const result = await Send({ calls });
  8142. console.log(result);
  8143. if (result?.results) {
  8144. count += result.results.length;
  8145. } else {
  8146. errors++;
  8147. }
  8148. }
  8149.  
  8150. setProgress(`${I18N('OUTLAND_CHESTS_RECEIVED')}: ${count}`, true);
  8151. }
  8152.  
  8153. async function autoRaidAdventure() {
  8154. const calls = [
  8155. {
  8156. name: "userGetInfo",
  8157. args: {},
  8158. ident: "userGetInfo"
  8159. },
  8160. {
  8161. name: "adventure_raidGetInfo",
  8162. args: {},
  8163. ident: "adventure_raidGetInfo"
  8164. }
  8165. ];
  8166. const result = await Send(JSON.stringify({ calls }))
  8167. .then(e => e.results.map(n => n.result.response));
  8168.  
  8169. const portalSphere = result[0].refillable.find(n => n.id == 45);
  8170. const adventureRaid = Object.entries(result[1].raid).filter(e => e[1]).pop()
  8171. const adventureId = adventureRaid ? adventureRaid[0] : 0;
  8172.  
  8173. if (!portalSphere.amount || !adventureId) {
  8174. setProgress(I18N('RAID_NOT_AVAILABLE'), true);
  8175. return;
  8176. }
  8177.  
  8178. const countRaid = +(await popup.confirm(I18N('RAID_ADVENTURE', { adventureId }), [
  8179. { result: false, isClose: true },
  8180. { msg: I18N('RAID'), isInput: true, default: portalSphere.amount },
  8181. ]));
  8182.  
  8183. if (!countRaid) {
  8184. return;
  8185. }
  8186.  
  8187. if (countRaid > portalSphere.amount) {
  8188. countRaid = portalSphere.amount;
  8189. }
  8190.  
  8191. const resultRaid = await Send(JSON.stringify({
  8192. calls: [...Array(countRaid)].map((e, i) => ({
  8193. name: "adventure_raid",
  8194. args: {
  8195. adventureId
  8196. },
  8197. ident: `body_${i}`
  8198. }))
  8199. })).then(e => e.results.map(n => n.result.response));
  8200.  
  8201. if (!resultRaid.length) {
  8202. console.log(resultRaid);
  8203. setProgress(I18N('SOMETHING_WENT_WRONG'), true);
  8204. return;
  8205. }
  8206.  
  8207. console.log(resultRaid, adventureId, portalSphere.amount);
  8208. setProgress(I18N('ADVENTURE_COMPLETED', { adventureId, times: resultRaid.length }), true);
  8209. }
  8210.  
  8211. /** Вывести всю клановую статистику в консоль браузера */
  8212. async function clanStatistic() {
  8213. const copy = function (text) {
  8214. const copyTextarea = document.createElement("textarea");
  8215. copyTextarea.style.opacity = "0";
  8216. copyTextarea.textContent = text;
  8217. document.body.appendChild(copyTextarea);
  8218. copyTextarea.select();
  8219. document.execCommand("copy");
  8220. document.body.removeChild(copyTextarea);
  8221. delete copyTextarea;
  8222. }
  8223. const calls = [
  8224. { name: "clanGetInfo", args: {}, ident: "clanGetInfo" },
  8225. { name: "clanGetWeeklyStat", args: {}, ident: "clanGetWeeklyStat" },
  8226. { name: "clanGetLog", args: {}, ident: "clanGetLog" },
  8227. ];
  8228.  
  8229. const result = await Send(JSON.stringify({ calls }));
  8230.  
  8231. const dataClanInfo = result.results[0].result.response;
  8232. const dataClanStat = result.results[1].result.response;
  8233. const dataClanLog = result.results[2].result.response;
  8234.  
  8235. const membersStat = {};
  8236. for (let i = 0; i < dataClanStat.stat.length; i++) {
  8237. membersStat[dataClanStat.stat[i].id] = dataClanStat.stat[i];
  8238. }
  8239.  
  8240. const joinStat = {};
  8241. historyLog = dataClanLog.history;
  8242. for (let j in historyLog) {
  8243. his = historyLog[j];
  8244. if (his.event == 'join') {
  8245. joinStat[his.userId] = his.ctime;
  8246. }
  8247. }
  8248.  
  8249. const infoArr = [];
  8250. const members = dataClanInfo.clan.members;
  8251. for (let n in members) {
  8252. var member = [
  8253. n,
  8254. members[n].name,
  8255. members[n].level,
  8256. dataClanInfo.clan.warriors.includes(+n) ? 1 : 0,
  8257. (new Date(members[n].lastLoginTime * 1000)).toLocaleString().replace(',', ''),
  8258. joinStat[n] ? (new Date(joinStat[n] * 1000)).toLocaleString().replace(',', '') : '',
  8259. membersStat[n].activity.reverse().join('\t'),
  8260. membersStat[n].adventureStat.reverse().join('\t'),
  8261. membersStat[n].clanGifts.reverse().join('\t'),
  8262. membersStat[n].clanWarStat.reverse().join('\t'),
  8263. membersStat[n].dungeonActivity.reverse().join('\t'),
  8264. ];
  8265. infoArr.push(member);
  8266. }
  8267. const info = infoArr.sort((a, b) => (b[2] - a[2])).map((e) => e.join('\t')).join('\n');
  8268. console.log(info);
  8269. copy(info);
  8270. setProgress(I18N('CLAN_STAT_COPY'), true);
  8271. }
  8272.  
  8273. async function buyInStoreForGold() {
  8274. const result = await Send('{"calls":[{"name":"shopGetAll","args":{},"ident":"body"},{"name":"userGetInfo","args":{},"ident":"userGetInfo"}]}').then(e => e.results.map(n => n.result.response));
  8275. const shops = result[0];
  8276. const user = result[1];
  8277. let gold = user.gold;
  8278. const calls = [];
  8279. if (shops[17]) {
  8280. const slots = shops[17].slots;
  8281. for (let i = 1; i <= 2; i++) {
  8282. if (!slots[i].bought) {
  8283. const costGold = slots[i].cost.gold;
  8284. if ((gold - costGold) < 0) {
  8285. continue;
  8286. }
  8287. gold -= costGold;
  8288. calls.push({
  8289. name: "shopBuy",
  8290. args: {
  8291. shopId: 17,
  8292. slot: i,
  8293. cost: slots[i].cost,
  8294. reward: slots[i].reward,
  8295. },
  8296. ident: 'body_' + i,
  8297. })
  8298. }
  8299. }
  8300. }
  8301. const slots = shops[1].slots;
  8302. for (let i = 4; i <= 6; i++) {
  8303. if (!slots[i].bought && slots[i]?.cost?.gold) {
  8304. const costGold = slots[i].cost.gold;
  8305. if ((gold - costGold) < 0) {
  8306. continue;
  8307. }
  8308. gold -= costGold;
  8309. calls.push({
  8310. name: "shopBuy",
  8311. args: {
  8312. shopId: 1,
  8313. slot: i,
  8314. cost: slots[i].cost,
  8315. reward: slots[i].reward,
  8316. },
  8317. ident: 'body_' + i,
  8318. })
  8319. }
  8320. }
  8321.  
  8322. if (!calls.length) {
  8323. setProgress(I18N('NOTHING_BUY'), true);
  8324. return;
  8325. }
  8326.  
  8327. const resultBuy = await Send(JSON.stringify({ calls })).then(e => e.results.map(n => n.result.response));
  8328. console.log(resultBuy);
  8329. const countBuy = resultBuy.length;
  8330. setProgress(I18N('LOTS_BOUGHT', { countBuy }), true);
  8331. }
  8332.  
  8333. function rewardsAndMailFarm() {
  8334. return new Promise(function (resolve, reject) {
  8335. let questGetAllCall = {
  8336. calls: [{
  8337. name: "questGetAll",
  8338. args: {},
  8339. ident: "questGetAll"
  8340. }, {
  8341. name: "mailGetAll",
  8342. args: {},
  8343. ident: "mailGetAll"
  8344. }]
  8345. }
  8346. send(JSON.stringify(questGetAllCall), function (data) {
  8347. if (!data) return;
  8348. const questGetAll = data.results[0].result.response.filter((e) => e.state == 2);
  8349. const questBattlePass = lib.getData('quest').battlePass;
  8350. const questChainBPass = lib.getData('battlePass').questChain;
  8351. const listBattlePass = lib.getData('battlePass').list;
  8352.  
  8353. const questAllFarmCall = {
  8354. calls: [],
  8355. };
  8356. const questIds = [];
  8357. for (let quest of questGetAll) {
  8358. if (quest.id >= 2001e4) {
  8359. continue;
  8360. }
  8361. if (quest.id > 1e6 && quest.id < 2e7) {
  8362. const questInfo = questBattlePass[quest.id];
  8363. const chain = questChainBPass[questInfo.chain];
  8364. if (chain.requirement?.battlePassTicket) {
  8365. continue;
  8366. }
  8367. const battlePass = listBattlePass[chain.battlePass];
  8368. const startTime = battlePass.startCondition.time.value * 1e3
  8369. const endTime = new Date(startTime + battlePass.duration * 1e3);
  8370. if (startTime > Date.now() || endTime < Date.now()) {
  8371. continue;
  8372. }
  8373. }
  8374. if (quest.id >= 2e7) {
  8375. questIds.push(quest.id);
  8376. continue;
  8377. }
  8378. questAllFarmCall.calls.push({
  8379. name: 'questFarm',
  8380. args: {
  8381. questId: quest.id,
  8382. },
  8383. ident: `questFarm_${quest.id}`,
  8384. });
  8385. }
  8386.  
  8387. if (questIds.length) {
  8388. questAllFarmCall.calls.push({
  8389. name: 'quest_questsFarm',
  8390. args: { questIds },
  8391. ident: 'quest_questsFarm',
  8392. });
  8393. }
  8394.  
  8395. let letters = data?.results[1]?.result?.response?.letters;
  8396. letterIds = lettersFilter(letters);
  8397.  
  8398. if (letterIds.length) {
  8399. questAllFarmCall.calls.push({
  8400. name: 'mailFarm',
  8401. args: { letterIds },
  8402. ident: 'mailFarm',
  8403. });
  8404. }
  8405.  
  8406. if (!questAllFarmCall.calls.length) {
  8407. setProgress(I18N('NOTHING_TO_COLLECT'), true);
  8408. resolve();
  8409. return;
  8410. }
  8411.  
  8412. send(JSON.stringify(questAllFarmCall), async function (res) {
  8413. let countQuests = 0;
  8414. let countMail = 0;
  8415. let questsIds = [];
  8416. for (let call of res.results) {
  8417. if (call.ident.includes('questFarm')) {
  8418. countQuests++;
  8419. } else if (call.ident.includes('questsFarm')) {
  8420. countQuests += Object.keys(call.result.response).length;
  8421. } else if (call.ident.includes('mailFarm')) {
  8422. countMail = Object.keys(call.result.response).length;
  8423. }
  8424.  
  8425. const newQuests = call.result.newQuests;
  8426. if (newQuests) {
  8427. for (let quest of newQuests) {
  8428. if ((quest.id < 1e6 || (quest.id >= 2e7 && quest.id < 2001e4)) && quest.state == 2) {
  8429. questsIds.push(quest.id);
  8430. }
  8431. }
  8432. }
  8433. }
  8434.  
  8435. while (questsIds.length) {
  8436. const questIds = [];
  8437. const calls = [];
  8438. for (let questId of questsIds) {
  8439. if (questId < 1e6) {
  8440. calls.push({
  8441. name: 'questFarm',
  8442. args: {
  8443. questId,
  8444. },
  8445. ident: `questFarm_${questId}`,
  8446. });
  8447. countQuests++;
  8448. } else if (questId >= 2e7 && questId < 2001e4) {
  8449. questIds.push(questId);
  8450. countQuests++;
  8451. }
  8452. }
  8453. calls.push({
  8454. name: 'quest_questsFarm',
  8455. args: { questIds },
  8456. ident: 'body',
  8457. });
  8458. const results = await Send({ calls }).then((e) => e.results.map((e) => e.result));
  8459. questsIds = [];
  8460. for (const result of results) {
  8461. const newQuests = result.newQuests;
  8462. if (newQuests) {
  8463. for (let quest of newQuests) {
  8464. if (quest.state == 2) {
  8465. questsIds.push(quest.id);
  8466. }
  8467. }
  8468. }
  8469. }
  8470. }
  8471.  
  8472. setProgress(I18N('COLLECT_REWARDS_AND_MAIL', { countQuests, countMail }), true);
  8473. resolve();
  8474. });
  8475. });
  8476. })
  8477. }
  8478.  
  8479. class epicBrawl {
  8480. timeout = null;
  8481. time = null;
  8482.  
  8483. constructor() {
  8484. if (epicBrawl.inst) {
  8485. return epicBrawl.inst;
  8486. }
  8487. epicBrawl.inst = this;
  8488. return this;
  8489. }
  8490.  
  8491. runTimeout(func, timeDiff) {
  8492. const worker = new Worker(URL.createObjectURL(new Blob([`
  8493. self.onmessage = function(e) {
  8494. const timeDiff = e.data;
  8495.  
  8496. if (timeDiff > 0) {
  8497. setTimeout(() => {
  8498. self.postMessage(1);
  8499. self.close();
  8500. }, timeDiff);
  8501. }
  8502. };
  8503. `])));
  8504. worker.postMessage(timeDiff);
  8505. worker.onmessage = () => {
  8506. func();
  8507. };
  8508. return true;
  8509. }
  8510.  
  8511. timeDiff(date1, date2) {
  8512. const date1Obj = new Date(date1);
  8513. const date2Obj = new Date(date2);
  8514.  
  8515. const timeDiff = Math.abs(date2Obj - date1Obj);
  8516.  
  8517. const totalSeconds = timeDiff / 1000;
  8518. const minutes = Math.floor(totalSeconds / 60);
  8519. const seconds = Math.floor(totalSeconds % 60);
  8520.  
  8521. const formattedMinutes = String(minutes).padStart(2, '0');
  8522. const formattedSeconds = String(seconds).padStart(2, '0');
  8523.  
  8524. return `${formattedMinutes}:${formattedSeconds}`;
  8525. }
  8526.  
  8527. check() {
  8528. console.log(new Date(this.time))
  8529. if (Date.now() > this.time) {
  8530. this.timeout = null;
  8531. this.start()
  8532. return;
  8533. }
  8534. this.timeout = this.runTimeout(() => this.check(), 6e4);
  8535. return this.timeDiff(this.time, Date.now())
  8536. }
  8537.  
  8538. async start() {
  8539. if (this.timeout) {
  8540. const time = this.timeDiff(this.time, Date.now());
  8541. console.log(new Date(this.time))
  8542. setProgress(I18N('TIMER_ALREADY', { time }), false, hideProgress);
  8543. return;
  8544. }
  8545. setProgress(I18N('EPIC_BRAWL'), false, hideProgress);
  8546. const teamInfo = await Send('{"calls":[{"name":"teamGetAll","args":{},"ident":"teamGetAll"},{"name":"teamGetFavor","args":{},"ident":"teamGetFavor"},{"name":"userGetInfo","args":{},"ident":"userGetInfo"}]}').then(e => e.results.map(n => n.result.response));
  8547. const refill = teamInfo[2].refillable.find(n => n.id == 52)
  8548. this.time = (refill.lastRefill + 3600) * 1000
  8549. const attempts = refill.amount;
  8550. if (!attempts) {
  8551. console.log(new Date(this.time));
  8552. const time = this.check();
  8553. setProgress(I18N('NO_ATTEMPTS_TIMER_START', { time }), false, hideProgress);
  8554. return;
  8555. }
  8556.  
  8557. if (!teamInfo[0].epic_brawl) {
  8558. setProgress(I18N('NO_HEROES_PACK'), false, hideProgress);
  8559. return;
  8560. }
  8561.  
  8562. const args = {
  8563. heroes: teamInfo[0].epic_brawl.filter(e => e < 1000),
  8564. pet: teamInfo[0].epic_brawl.filter(e => e > 6000).pop(),
  8565. favor: teamInfo[1].epic_brawl,
  8566. }
  8567.  
  8568. let wins = 0;
  8569. let coins = 0;
  8570. let streak = { progress: 0, nextStage: 0 };
  8571. for (let i = attempts; i > 0; i--) {
  8572. const info = await Send(JSON.stringify({
  8573. calls: [
  8574. { name: "epicBrawl_getEnemy", args: {}, ident: "epicBrawl_getEnemy" }, { name: "epicBrawl_startBattle", args, ident: "epicBrawl_startBattle" }
  8575. ]
  8576. })).then(e => e.results.map(n => n.result.response));
  8577.  
  8578. const { progress, result } = await Calc(info[1].battle);
  8579. const endResult = await Send(JSON.stringify({ calls: [{ name: "epicBrawl_endBattle", args: { progress, result }, ident: "epicBrawl_endBattle" }, { name: "epicBrawl_getWinStreak", args: {}, ident: "epicBrawl_getWinStreak" }] })).then(e => e.results.map(n => n.result.response));
  8580.  
  8581. const resultInfo = endResult[0].result;
  8582. streak = endResult[1];
  8583.  
  8584. wins += resultInfo.win;
  8585. coins += resultInfo.reward ? resultInfo.reward.coin[39] : 0;
  8586.  
  8587. console.log(endResult[0].result)
  8588. if (endResult[1].progress == endResult[1].nextStage) {
  8589. const farm = await Send('{"calls":[{"name":"epicBrawl_farmWinStreak","args":{},"ident":"body"}]}').then(e => e.results[0].result.response);
  8590. coins += farm.coin[39];
  8591. }
  8592.  
  8593. setProgress(I18N('EPIC_BRAWL_RESULT', {
  8594. i, wins, attempts, coins,
  8595. progress: streak.progress,
  8596. nextStage: streak.nextStage,
  8597. end: '',
  8598. }), false, hideProgress);
  8599. }
  8600.  
  8601. console.log(new Date(this.time));
  8602. const time = this.check();
  8603. setProgress(I18N('EPIC_BRAWL_RESULT', {
  8604. wins, attempts, coins,
  8605. i: '',
  8606. progress: streak.progress,
  8607. nextStage: streak.nextStage,
  8608. end: I18N('ATTEMPT_ENDED', { time }),
  8609. }), false, hideProgress);
  8610. }
  8611. }
  8612.  
  8613. function countdownTimer(seconds, message) {
  8614. message = message || I18N('TIMER');
  8615. const stopTimer = Date.now() + seconds * 1e3
  8616. return new Promise(resolve => {
  8617. const interval = setInterval(async () => {
  8618. const now = Date.now();
  8619. setProgress(`${message} ${((stopTimer - now) / 1000).toFixed(2)}`, false);
  8620. if (now > stopTimer) {
  8621. clearInterval(interval);
  8622. setProgress('', 1);
  8623. resolve();
  8624. }
  8625. }, 100);
  8626. });
  8627. }
  8628.  
  8629. this.HWHFuncs.countdownTimer = countdownTimer;
  8630.  
  8631. /** Набить килов в горниле душк */
  8632. async function bossRatingEventSouls() {
  8633. const data = await Send({
  8634. calls: [
  8635. { name: "heroGetAll", args: {}, ident: "teamGetAll" },
  8636. { name: "offerGetAll", args: {}, ident: "offerGetAll" },
  8637. { name: "pet_getAll", args: {}, ident: "pet_getAll" },
  8638. ]
  8639. });
  8640. const bossEventInfo = data.results[1].result.response.find(e => e.offerType == "bossEvent");
  8641. if (!bossEventInfo) {
  8642. setProgress('Эвент завершен', true);
  8643. return;
  8644. }
  8645.  
  8646. if (bossEventInfo.progress.score > 250) {
  8647. setProgress('Уже убито больше 250 врагов');
  8648. rewardBossRatingEventSouls();
  8649. return;
  8650. }
  8651. const availablePets = Object.values(data.results[2].result.response).map(e => e.id);
  8652. const heroGetAllList = data.results[0].result.response;
  8653. const usedHeroes = bossEventInfo.progress.usedHeroes;
  8654. const heroList = [];
  8655.  
  8656. for (let heroId in heroGetAllList) {
  8657. let hero = heroGetAllList[heroId];
  8658. if (usedHeroes.includes(hero.id)) {
  8659. continue;
  8660. }
  8661. heroList.push(hero.id);
  8662. }
  8663.  
  8664. if (!heroList.length) {
  8665. setProgress('Нет героев', true);
  8666. return;
  8667. }
  8668.  
  8669. const pet = availablePets.includes(6005) ? 6005 : availablePets[Math.floor(Math.random() * availablePets.length)];
  8670. const petLib = lib.getData('pet');
  8671. let count = 1;
  8672.  
  8673. for (const heroId of heroList) {
  8674. const args = {
  8675. heroes: [heroId],
  8676. pet
  8677. }
  8678. /** Поиск питомца для героя */
  8679. for (const petId of availablePets) {
  8680. if (petLib[petId].favorHeroes.includes(heroId)) {
  8681. args.favor = {
  8682. [heroId]: petId
  8683. }
  8684. break;
  8685. }
  8686. }
  8687.  
  8688. const calls = [{
  8689. name: "bossRatingEvent_startBattle",
  8690. args,
  8691. ident: "body"
  8692. }, {
  8693. name: "offerGetAll",
  8694. args: {},
  8695. ident: "offerGetAll"
  8696. }];
  8697.  
  8698. const res = await Send({ calls });
  8699. count++;
  8700.  
  8701. if ('error' in res) {
  8702. console.error(res.error);
  8703. setProgress('Перезагрузите игру и попробуйте позже', true);
  8704. return;
  8705. }
  8706.  
  8707. const eventInfo = res.results[1].result.response.find(e => e.offerType == "bossEvent");
  8708. if (eventInfo.progress.score > 250) {
  8709. break;
  8710. }
  8711. setProgress('Количество убитых врагов: ' + eventInfo.progress.score + '<br>Использовано ' + count + ' героев');
  8712. }
  8713.  
  8714. rewardBossRatingEventSouls();
  8715. }
  8716. /** Сбор награды из Горнила Душ */
  8717. async function rewardBossRatingEventSouls() {
  8718. const data = await Send({
  8719. calls: [
  8720. { name: "offerGetAll", args: {}, ident: "offerGetAll" }
  8721. ]
  8722. });
  8723.  
  8724. const bossEventInfo = data.results[0].result.response.find(e => e.offerType == "bossEvent");
  8725. if (!bossEventInfo) {
  8726. setProgress('Эвент завершен', true);
  8727. return;
  8728. }
  8729.  
  8730. const farmedChests = bossEventInfo.progress.farmedChests;
  8731. const score = bossEventInfo.progress.score;
  8732. // setProgress('Количество убитых врагов: ' + score);
  8733. const revard = bossEventInfo.reward;
  8734. const calls = [];
  8735.  
  8736. let count = 0;
  8737. for (let i = 1; i < 10; i++) {
  8738. if (farmedChests.includes(i)) {
  8739. continue;
  8740. }
  8741. if (score < revard[i].score) {
  8742. break;
  8743. }
  8744. calls.push({
  8745. name: "bossRatingEvent_getReward",
  8746. args: {
  8747. rewardId: i
  8748. },
  8749. ident: "body_" + i
  8750. });
  8751. count++;
  8752. }
  8753. if (!count) {
  8754. setProgress('Нечего собирать', true);
  8755. return;
  8756. }
  8757.  
  8758. Send({ calls }).then(e => {
  8759. console.log(e);
  8760. setProgress('Собрано ' + e?.results?.length + ' наград', true);
  8761. })
  8762. }
  8763. /**
  8764. * Spin the Seer
  8765. *
  8766. * Покрутить провидца
  8767. */
  8768. async function rollAscension() {
  8769. const refillable = await Send({calls:[
  8770. {
  8771. name:"userGetInfo",
  8772. args:{},
  8773. ident:"userGetInfo"
  8774. }
  8775. ]}).then(e => e.results[0].result.response.refillable);
  8776. const i47 = refillable.find(i => i.id == 47);
  8777. if (i47?.amount) {
  8778. await Send({ calls: [{ name: "ascensionChest_open", args: { paid: false, amount: 1 }, ident: "body" }] });
  8779. setProgress(I18N('DONE'), true);
  8780. } else {
  8781. setProgress(I18N('NOT_ENOUGH_AP'), true);
  8782. }
  8783. }
  8784.  
  8785. /**
  8786. * Collect gifts for the New Year
  8787. *
  8788. * Собрать подарки на новый год
  8789. */
  8790. function getGiftNewYear() {
  8791. Send({ calls: [{ name: "newYearGiftGet", args: { type: 0 }, ident: "body" }] }).then(e => {
  8792. const gifts = e.results[0].result.response.gifts;
  8793. const calls = gifts.filter(e => e.opened == 0).map(e => ({
  8794. name: "newYearGiftOpen",
  8795. args: {
  8796. giftId: e.id
  8797. },
  8798. ident: `body_${e.id}`
  8799. }));
  8800. if (!calls.length) {
  8801. setProgress(I18N('NY_NO_GIFTS'), 5000);
  8802. return;
  8803. }
  8804. Send({ calls }).then(e => {
  8805. console.log(e.results)
  8806. const msg = I18N('NY_GIFTS_COLLECTED', { count: e.results.length });
  8807. console.log(msg);
  8808. setProgress(msg, 5000);
  8809. });
  8810. })
  8811. }
  8812.  
  8813. async function updateArtifacts() {
  8814. const count = +await popup.confirm(I18N('SET_NUMBER_LEVELS'), [
  8815. { msg: I18N('BTN_GO'), isInput: true, default: 10 },
  8816. { result: false, isClose: true }
  8817. ]);
  8818. if (!count) {
  8819. return;
  8820. }
  8821. const quest = new questRun;
  8822. await quest.autoInit();
  8823. const heroes = Object.values(quest.questInfo['heroGetAll']);
  8824. const inventory = quest.questInfo['inventoryGet'];
  8825. const calls = [];
  8826. for (let i = count; i > 0; i--) {
  8827. const upArtifact = quest.getUpgradeArtifact();
  8828. if (!upArtifact.heroId) {
  8829. if (await popup.confirm(I18N('POSSIBLE_IMPROVE_LEVELS', { count: calls.length }), [
  8830. { msg: I18N('YES'), result: true },
  8831. { result: false, isClose: true }
  8832. ])) {
  8833. break;
  8834. } else {
  8835. return;
  8836. }
  8837. }
  8838. const hero = heroes.find(e => e.id == upArtifact.heroId);
  8839. hero.artifacts[upArtifact.slotId].level++;
  8840. inventory[upArtifact.costCurrency][upArtifact.costId] -= upArtifact.costValue;
  8841. calls.push({
  8842. name: "heroArtifactLevelUp",
  8843. args: {
  8844. heroId: upArtifact.heroId,
  8845. slotId: upArtifact.slotId
  8846. },
  8847. ident: `heroArtifactLevelUp_${i}`
  8848. });
  8849. }
  8850.  
  8851. if (!calls.length) {
  8852. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  8853. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  8854. return;
  8855. }
  8856.  
  8857. await Send(JSON.stringify({ calls })).then(e => {
  8858. if ('error' in e) {
  8859. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  8860. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  8861. } else {
  8862. console.log(I18N('IMPROVED_LEVELS', { count: e.results.length }));
  8863. setProgress(I18N('IMPROVED_LEVELS', { count: e.results.length }), false);
  8864. }
  8865. });
  8866. }
  8867.  
  8868. window.sign = a => {
  8869. const i = this['\x78\x79\x7a'];
  8870. return md5([i['\x6e\x61\x6d\x65'], i['\x76\x65\x72\x73\x69\x6f\x6e'], i['\x61\x75\x74\x68\x6f\x72'], ~(a % 1e3)]['\x6a\x6f\x69\x6e']('\x5f'))
  8871. }
  8872.  
  8873. async function updateSkins() {
  8874. const count = +await popup.confirm(I18N('SET_NUMBER_LEVELS'), [
  8875. { msg: I18N('BTN_GO'), isInput: true, default: 10 },
  8876. { result: false, isClose: true }
  8877. ]);
  8878. if (!count) {
  8879. return;
  8880. }
  8881.  
  8882. const quest = new questRun;
  8883. await quest.autoInit();
  8884. const heroes = Object.values(quest.questInfo['heroGetAll']);
  8885. const inventory = quest.questInfo['inventoryGet'];
  8886. const calls = [];
  8887. for (let i = count; i > 0; i--) {
  8888. const upSkin = quest.getUpgradeSkin();
  8889. if (!upSkin.heroId) {
  8890. if (await popup.confirm(I18N('POSSIBLE_IMPROVE_LEVELS', { count: calls.length }), [
  8891. { msg: I18N('YES'), result: true },
  8892. { result: false, isClose: true }
  8893. ])) {
  8894. break;
  8895. } else {
  8896. return;
  8897. }
  8898. }
  8899. const hero = heroes.find(e => e.id == upSkin.heroId);
  8900. hero.skins[upSkin.skinId]++;
  8901. inventory[upSkin.costCurrency][upSkin.costCurrencyId] -= upSkin.cost;
  8902. calls.push({
  8903. name: "heroSkinUpgrade",
  8904. args: {
  8905. heroId: upSkin.heroId,
  8906. skinId: upSkin.skinId
  8907. },
  8908. ident: `heroSkinUpgrade_${i}`
  8909. })
  8910. }
  8911.  
  8912. if (!calls.length) {
  8913. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  8914. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  8915. return;
  8916. }
  8917.  
  8918. await Send(JSON.stringify({ calls })).then(e => {
  8919. if ('error' in e) {
  8920. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  8921. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  8922. } else {
  8923. console.log(I18N('IMPROVED_LEVELS', { count: e.results.length }));
  8924. setProgress(I18N('IMPROVED_LEVELS', { count: e.results.length }), false);
  8925. }
  8926. });
  8927. }
  8928.  
  8929. function getQuestionInfo(img, nameOnly = false) {
  8930. const libHeroes = Object.values(lib.data.hero);
  8931. const parts = img.split(':');
  8932. const id = parts[1];
  8933. switch (parts[0]) {
  8934. case 'titanArtifact_id':
  8935. return cheats.translate("LIB_TITAN_ARTIFACT_NAME_" + id);
  8936. case 'titan':
  8937. return cheats.translate("LIB_HERO_NAME_" + id);
  8938. case 'skill':
  8939. return cheats.translate("LIB_SKILL_" + id);
  8940. case 'inventoryItem_gear':
  8941. return cheats.translate("LIB_GEAR_NAME_" + id);
  8942. case 'inventoryItem_coin':
  8943. return cheats.translate("LIB_COIN_NAME_" + id);
  8944. case 'artifact':
  8945. if (nameOnly) {
  8946. return cheats.translate("LIB_ARTIFACT_NAME_" + id);
  8947. }
  8948. heroes = libHeroes.filter(h => h.id < 100 && h.artifacts.includes(+id));
  8949. return {
  8950. /** Как называется этот артефакт? */
  8951. name: cheats.translate("LIB_ARTIFACT_NAME_" + id),
  8952. /** Какому герою принадлежит этот артефакт? */
  8953. heroes: heroes.map(h => cheats.translate("LIB_HERO_NAME_" + h.id))
  8954. };
  8955. case 'hero':
  8956. if (nameOnly) {
  8957. return cheats.translate("LIB_HERO_NAME_" + id);
  8958. }
  8959. artifacts = lib.data.hero[id].artifacts;
  8960. return {
  8961. /** Как зовут этого героя? */
  8962. name: cheats.translate("LIB_HERO_NAME_" + id),
  8963. /** Какой артефакт принадлежит этому герою? */
  8964. artifact: artifacts.map(a => cheats.translate("LIB_ARTIFACT_NAME_" + a))
  8965. };
  8966. }
  8967. }
  8968.  
  8969. function hintQuest(quest) {
  8970. const result = {};
  8971. if (quest?.questionIcon) {
  8972. const info = getQuestionInfo(quest.questionIcon);
  8973. if (info?.heroes) {
  8974. /** Какому герою принадлежит этот артефакт? */
  8975. result.answer = quest.answers.filter(e => info.heroes.includes(e.answerText.slice(1)));
  8976. }
  8977. if (info?.artifact) {
  8978. /** Какой артефакт принадлежит этому герою? */
  8979. result.answer = quest.answers.filter(e => info.artifact.includes(e.answerText.slice(1)));
  8980. }
  8981. if (typeof info == 'string') {
  8982. result.info = { name: info };
  8983. } else {
  8984. result.info = info;
  8985. }
  8986. }
  8987.  
  8988. if (quest.answers[0]?.answerIcon) {
  8989. result.answer = quest.answers.filter(e => quest.question.includes(getQuestionInfo(e.answerIcon, true)))
  8990. }
  8991.  
  8992. if ((!result?.answer || !result.answer.length) && !result.info?.name) {
  8993. return false;
  8994. }
  8995.  
  8996. let resultText = '';
  8997. if (result?.info) {
  8998. resultText += I18N('PICTURE') + result.info.name;
  8999. }
  9000. console.log(result);
  9001. if (result?.answer && result.answer.length) {
  9002. resultText += I18N('ANSWER') + result.answer[0].id + (!result.answer[0].answerIcon ? ' - ' + result.answer[0].answerText : '');
  9003. }
  9004.  
  9005. return resultText;
  9006. }
  9007.  
  9008. async function farmBattlePass() {
  9009. const isFarmReward = (reward) => {
  9010. return !(reward?.buff || reward?.fragmentHero || reward?.bundleHeroReward);
  9011. };
  9012.  
  9013. const battlePassProcess = (pass) => {
  9014. if (!pass.id) {return []}
  9015. const levels = Object.values(lib.data.battlePass.level).filter(x => x.battlePass == pass.id)
  9016. const last_level = levels[levels.length - 1];
  9017. let actual = Math.max(...levels.filter(p => pass.exp >= p.experience).map(p => p.level))
  9018.  
  9019. if (pass.exp > last_level.experience) {
  9020. actual = last_level.level + (pass.exp - last_level.experience) / last_level.experienceByLevel;
  9021. }
  9022. const calls = [];
  9023. for(let i = 1; i <= actual; i++) {
  9024. const level = i >= last_level.level ? last_level : levels.find(l => l.level === i);
  9025. const reward = {free: level?.freeReward, paid:level?.paidReward};
  9026.  
  9027. if (!pass.rewards[i]?.free && isFarmReward(reward.free)) {
  9028. const args = {level: i, free:true};
  9029. if (!pass.gold) { args.id = pass.id }
  9030. calls.push({ name: 'battlePass_farmReward', args, ident: `${pass.gold ? 'body' : 'spesial'}_free_${args.id}_${i}` });
  9031. }
  9032. if (pass.ticket && !pass.rewards[i]?.paid && isFarmReward(reward.paid)) {
  9033. const args = {level: i, free:false};
  9034. if (!pass.gold) { args.id = pass.id}
  9035. calls.push({ name: 'battlePass_farmReward', args, ident: `${pass.gold ? 'body' : 'spesial'}_paid_${args.id}_${i}` });
  9036. }
  9037. }
  9038. return calls;
  9039. }
  9040.  
  9041. const passes = await Send({
  9042. calls: [
  9043. { name: 'battlePass_getInfo', args: {}, ident: 'getInfo' },
  9044. { name: 'battlePass_getSpecial', args: {}, ident: 'getSpecial' },
  9045. ],
  9046. }).then((e) => [{...e.results[0].result.response?.battlePass, gold: true}, ...Object.values(e.results[1].result.response)]);
  9047.  
  9048. const calls = passes.map(p => battlePassProcess(p)).flat()
  9049.  
  9050. if (!calls.length) {
  9051. setProgress(I18N('NOTHING_TO_COLLECT'));
  9052. return;
  9053. }
  9054.  
  9055. let results = await Send({calls});
  9056. if (results.error) {
  9057. console.log(results.error);
  9058. setProgress(I18N('SOMETHING_WENT_WRONG'));
  9059. } else {
  9060. setProgress(I18N('SEASON_REWARD_COLLECTED', {count: results.results.length}), true);
  9061. }
  9062. }
  9063.  
  9064. async function sellHeroSoulsForGold() {
  9065. let { fragmentHero, heroes } = await Send({
  9066. calls: [
  9067. { name: 'inventoryGet', args: {}, ident: 'inventoryGet' },
  9068. { name: 'heroGetAll', args: {}, ident: 'heroGetAll' },
  9069. ],
  9070. })
  9071. .then((e) => e.results.map((r) => r.result.response))
  9072. .then((e) => ({ fragmentHero: e[0].fragmentHero, heroes: e[1] }));
  9073.  
  9074. const calls = [];
  9075. for (let i in fragmentHero) {
  9076. if (heroes[i] && heroes[i].star == 6) {
  9077. calls.push({
  9078. name: 'inventorySell',
  9079. args: {
  9080. type: 'hero',
  9081. libId: i,
  9082. amount: fragmentHero[i],
  9083. fragment: true,
  9084. },
  9085. ident: 'inventorySell_' + i,
  9086. });
  9087. }
  9088. }
  9089. if (!calls.length) {
  9090. console.log(0);
  9091. return 0;
  9092. }
  9093. const rewards = await Send({ calls }).then((e) => e.results.map((r) => r.result?.response?.gold || 0));
  9094. const gold = rewards.reduce((e, a) => e + a, 0);
  9095. setProgress(I18N('GOLD_RECEIVED', { gold }), true);
  9096. }
  9097.  
  9098. /**
  9099. * Attack of the minions of Asgard
  9100. *
  9101. * Атака прислужников Асгарда
  9102. */
  9103. function testRaidNodes() {
  9104. const { executeRaidNodes } = HWHClasses;
  9105. return new Promise((resolve, reject) => {
  9106. const tower = new executeRaidNodes(resolve, reject);
  9107. tower.start();
  9108. });
  9109. }
  9110.  
  9111. /**
  9112. * Attack of the minions of Asgard
  9113. *
  9114. * Атака прислужников Асгарда
  9115. */
  9116. function executeRaidNodes(resolve, reject) {
  9117. let raidData = {
  9118. teams: [],
  9119. favor: {},
  9120. nodes: [],
  9121. attempts: 0,
  9122. countExecuteBattles: 0,
  9123. cancelBattle: 0,
  9124. }
  9125.  
  9126. callsExecuteRaidNodes = {
  9127. calls: [{
  9128. name: "clanRaid_getInfo",
  9129. args: {},
  9130. ident: "clanRaid_getInfo"
  9131. }, {
  9132. name: "teamGetAll",
  9133. args: {},
  9134. ident: "teamGetAll"
  9135. }, {
  9136. name: "teamGetFavor",
  9137. args: {},
  9138. ident: "teamGetFavor"
  9139. }]
  9140. }
  9141.  
  9142. this.start = function () {
  9143. send(JSON.stringify(callsExecuteRaidNodes), startRaidNodes);
  9144. }
  9145.  
  9146. async function startRaidNodes(data) {
  9147. res = data.results;
  9148. clanRaidInfo = res[0].result.response;
  9149. teamGetAll = res[1].result.response;
  9150. teamGetFavor = res[2].result.response;
  9151.  
  9152. let index = 0;
  9153. let isNotFullPack = false;
  9154. for (let team of teamGetAll.clanRaid_nodes) {
  9155. if (team.length < 6) {
  9156. isNotFullPack = true;
  9157. }
  9158. raidData.teams.push({
  9159. data: {},
  9160. heroes: team.filter(id => id < 6000),
  9161. pet: team.filter(id => id >= 6000).pop(),
  9162. battleIndex: index++
  9163. });
  9164. }
  9165. raidData.favor = teamGetFavor.clanRaid_nodes;
  9166.  
  9167. if (isNotFullPack) {
  9168. if (await popup.confirm(I18N('MINIONS_WARNING'), [
  9169. { msg: I18N('BTN_NO'), result: true },
  9170. { msg: I18N('BTN_YES'), result: false },
  9171. ])) {
  9172. endRaidNodes('isNotFullPack');
  9173. return;
  9174. }
  9175. }
  9176.  
  9177. raidData.nodes = clanRaidInfo.nodes;
  9178. raidData.attempts = clanRaidInfo.attempts;
  9179. setIsCancalBattle(false);
  9180.  
  9181. checkNodes();
  9182. }
  9183.  
  9184. function getAttackNode() {
  9185. for (let nodeId in raidData.nodes) {
  9186. let node = raidData.nodes[nodeId];
  9187. let points = 0
  9188. for (team of node.teams) {
  9189. points += team.points;
  9190. }
  9191. let now = Date.now() / 1000;
  9192. if (!points && now > node.timestamps.start && now < node.timestamps.end) {
  9193. let countTeam = node.teams.length;
  9194. delete raidData.nodes[nodeId];
  9195. return {
  9196. nodeId,
  9197. countTeam
  9198. };
  9199. }
  9200. }
  9201. return null;
  9202. }
  9203.  
  9204. function checkNodes() {
  9205. setProgress(`${I18N('REMAINING_ATTEMPTS')}: ${raidData.attempts}`);
  9206. let nodeInfo = getAttackNode();
  9207. if (nodeInfo && raidData.attempts) {
  9208. startNodeBattles(nodeInfo);
  9209. return;
  9210. }
  9211.  
  9212. endRaidNodes('EndRaidNodes');
  9213. }
  9214.  
  9215. function startNodeBattles(nodeInfo) {
  9216. let {nodeId, countTeam} = nodeInfo;
  9217. let teams = raidData.teams.slice(0, countTeam);
  9218. let heroes = raidData.teams.map(e => e.heroes).flat();
  9219. let favor = {...raidData.favor};
  9220. for (let heroId in favor) {
  9221. if (!heroes.includes(+heroId)) {
  9222. delete favor[heroId];
  9223. }
  9224. }
  9225.  
  9226. let calls = [{
  9227. name: "clanRaid_startNodeBattles",
  9228. args: {
  9229. nodeId,
  9230. teams,
  9231. favor
  9232. },
  9233. ident: "body"
  9234. }];
  9235.  
  9236. send(JSON.stringify({calls}), resultNodeBattles);
  9237. }
  9238.  
  9239. function resultNodeBattles(e) {
  9240. if (e['error']) {
  9241. endRaidNodes('nodeBattlesError', e['error']);
  9242. return;
  9243. }
  9244.  
  9245. console.log(e);
  9246. let battles = e.results[0].result.response.battles;
  9247. let promises = [];
  9248. let battleIndex = 0;
  9249. for (let battle of battles) {
  9250. battle.battleIndex = battleIndex++;
  9251. promises.push(calcBattleResult(battle));
  9252. }
  9253.  
  9254. Promise.all(promises)
  9255. .then(results => {
  9256. const endResults = {};
  9257. let isAllWin = true;
  9258. for (let r of results) {
  9259. isAllWin &&= r.result.win;
  9260. }
  9261. if (!isAllWin) {
  9262. cancelEndNodeBattle(results[0]);
  9263. return;
  9264. }
  9265. raidData.countExecuteBattles = results.length;
  9266. let timeout = 500;
  9267. for (let r of results) {
  9268. setTimeout(endNodeBattle, timeout, r);
  9269. timeout += 500;
  9270. }
  9271. });
  9272. }
  9273. /**
  9274. * Returns the battle calculation promise
  9275. *
  9276. * Возвращает промис расчета боя
  9277. */
  9278. function calcBattleResult(battleData) {
  9279. return new Promise(function (resolve, reject) {
  9280. BattleCalc(battleData, "get_clanPvp", resolve);
  9281. });
  9282. }
  9283. /**
  9284. * Cancels the fight
  9285. *
  9286. * Отменяет бой
  9287. */
  9288. function cancelEndNodeBattle(r) {
  9289. const fixBattle = function (heroes) {
  9290. for (const ids in heroes) {
  9291. hero = heroes[ids];
  9292. hero.energy = random(1, 999);
  9293. if (hero.hp > 0) {
  9294. hero.hp = random(1, hero.hp);
  9295. }
  9296. }
  9297. }
  9298. fixBattle(r.progress[0].attackers.heroes);
  9299. fixBattle(r.progress[0].defenders.heroes);
  9300. endNodeBattle(r);
  9301. }
  9302. /**
  9303. * Ends the fight
  9304. *
  9305. * Завершает бой
  9306. */
  9307. function endNodeBattle(r) {
  9308. let nodeId = r.battleData.result.nodeId;
  9309. let battleIndex = r.battleData.battleIndex;
  9310. let calls = [{
  9311. name: "clanRaid_endNodeBattle",
  9312. args: {
  9313. nodeId,
  9314. battleIndex,
  9315. result: r.result,
  9316. progress: r.progress
  9317. },
  9318. ident: "body"
  9319. }]
  9320.  
  9321. SendRequest(JSON.stringify({calls}), battleResult);
  9322. }
  9323. /**
  9324. * Processing the results of the battle
  9325. *
  9326. * Обработка результатов боя
  9327. */
  9328. function battleResult(e) {
  9329. if (e['error']) {
  9330. endRaidNodes('missionEndError', e['error']);
  9331. return;
  9332. }
  9333. r = e.results[0].result.response;
  9334. if (r['error']) {
  9335. if (r.reason == "invalidBattle") {
  9336. raidData.cancelBattle++;
  9337. checkNodes();
  9338. } else {
  9339. endRaidNodes('missionEndError', e['error']);
  9340. }
  9341. return;
  9342. }
  9343.  
  9344. if (!(--raidData.countExecuteBattles)) {
  9345. raidData.attempts--;
  9346. checkNodes();
  9347. }
  9348. }
  9349. /**
  9350. * Completing a task
  9351. *
  9352. * Завершение задачи
  9353. */
  9354. function endRaidNodes(reason, info) {
  9355. setIsCancalBattle(true);
  9356. let textCancel = raidData.cancelBattle ? ` ${I18N('BATTLES_CANCELED')}: ${raidData.cancelBattle}` : '';
  9357. setProgress(`${I18N('MINION_RAID')} ${I18N('COMPLETED')}! ${textCancel}`, true);
  9358. console.log(reason, info);
  9359. resolve();
  9360. }
  9361. }
  9362.  
  9363. this.HWHClasses.executeRaidNodes = executeRaidNodes;
  9364.  
  9365. /**
  9366. * Asgard Boss Attack Replay
  9367. *
  9368. * Повтор атаки босса Асгарда
  9369. */
  9370. function testBossBattle() {
  9371. const { executeBossBattle } = HWHClasses;
  9372. return new Promise((resolve, reject) => {
  9373. const bossBattle = new executeBossBattle(resolve, reject);
  9374. bossBattle.start(lastBossBattle);
  9375. });
  9376. }
  9377.  
  9378. /**
  9379. * Asgard Boss Attack Replay
  9380. *
  9381. * Повтор атаки босса Асгарда
  9382. */
  9383. function executeBossBattle(resolve, reject) {
  9384.  
  9385. this.start = function (battleInfo) {
  9386. preCalcBattle(battleInfo);
  9387. }
  9388.  
  9389. function getBattleInfo(battle) {
  9390. return new Promise(function (resolve) {
  9391. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  9392. BattleCalc(battle, getBattleType(battle.type), e => {
  9393. let extra = e.progress[0].defenders.heroes[1].extra;
  9394. resolve(extra.damageTaken + extra.damageTakenNextLevel);
  9395. });
  9396. });
  9397. }
  9398.  
  9399. function preCalcBattle(battle) {
  9400. let actions = [];
  9401. const countTestBattle = getInput('countTestBattle');
  9402. for (let i = 0; i < countTestBattle; i++) {
  9403. actions.push(getBattleInfo(battle, true));
  9404. }
  9405. Promise.all(actions)
  9406. .then(resultPreCalcBattle);
  9407. }
  9408.  
  9409. async function resultPreCalcBattle(damages) {
  9410. let maxDamage = 0;
  9411. let minDamage = 1e10;
  9412. let avgDamage = 0;
  9413. for (let damage of damages) {
  9414. avgDamage += damage
  9415. if (damage > maxDamage) {
  9416. maxDamage = damage;
  9417. }
  9418. if (damage < minDamage) {
  9419. minDamage = damage;
  9420. }
  9421. }
  9422. avgDamage /= damages.length;
  9423. console.log(damages.map(e => e.toLocaleString()).join('\n'), avgDamage, maxDamage);
  9424.  
  9425. await popup.confirm(
  9426. `${I18N('ROUND_STAT')} ${damages.length} ${I18N('BATTLE')}:` +
  9427. `<br>${I18N('MINIMUM')}: ` + minDamage.toLocaleString() +
  9428. `<br>${I18N('MAXIMUM')}: ` + maxDamage.toLocaleString() +
  9429. `<br>${I18N('AVERAGE')}: ` + avgDamage.toLocaleString()
  9430. , [
  9431. { msg: I18N('BTN_OK'), result: 0},
  9432. ])
  9433. endBossBattle(I18N('BTN_CANCEL'));
  9434. }
  9435.  
  9436. /**
  9437. * Completing a task
  9438. *
  9439. * Завершение задачи
  9440. */
  9441. function endBossBattle(reason, info) {
  9442. console.log(reason, info);
  9443. resolve();
  9444. }
  9445. }
  9446.  
  9447. this.HWHClasses.executeBossBattle = executeBossBattle;
  9448.  
  9449. class FixBattle {
  9450. minTimer = 1.3;
  9451. maxTimer = 15.3;
  9452.  
  9453. constructor(battle, isTimeout = true) {
  9454. this.battle = structuredClone(battle);
  9455. this.isTimeout = isTimeout;
  9456. }
  9457.  
  9458. timeout(callback, timeout) {
  9459. if (this.isTimeout) {
  9460. this.worker.postMessage(timeout);
  9461. this.worker.onmessage = callback;
  9462. } else {
  9463. callback();
  9464. }
  9465. }
  9466.  
  9467. randTimer() {
  9468. return Math.random() * (this.maxTimer - this.minTimer + 1) + this.minTimer;
  9469. }
  9470.  
  9471. setAvgTime(startTime) {
  9472. this.fixTime += Date.now() - startTime;
  9473. this.avgTime = this.fixTime / this.count;
  9474. }
  9475.  
  9476. init() {
  9477. this.fixTime = 0;
  9478. this.lastTimer = 0;
  9479. this.index = 0;
  9480. this.lastBossDamage = 0;
  9481. this.bestResult = {
  9482. count: 0,
  9483. timer: 0,
  9484. value: 0,
  9485. result: null,
  9486. progress: null,
  9487. };
  9488. this.lastBattleResult = {
  9489. win: false,
  9490. };
  9491. this.worker = new Worker(
  9492. URL.createObjectURL(
  9493. new Blob([
  9494. `self.onmessage = function(e) {
  9495. const timeout = e.data;
  9496. setTimeout(() => {
  9497. self.postMessage(1);
  9498. }, timeout);
  9499. };`,
  9500. ])
  9501. )
  9502. );
  9503. }
  9504.  
  9505. async start(endTime = Date.now() + 6e4, maxCount = 100) {
  9506. this.endTime = endTime;
  9507. this.maxCount = maxCount;
  9508. this.init();
  9509. return await new Promise((resolve) => {
  9510. this.resolve = resolve;
  9511. this.count = 0;
  9512. this.loop();
  9513. });
  9514. }
  9515.  
  9516. endFix() {
  9517. this.bestResult.maxCount = this.count;
  9518. this.worker.terminate();
  9519. this.resolve(this.bestResult);
  9520. }
  9521.  
  9522. async loop() {
  9523. const start = Date.now();
  9524. if (this.isEndLoop()) {
  9525. this.endFix();
  9526. return;
  9527. }
  9528. this.count++;
  9529. try {
  9530. this.lastResult = await Calc(this.battle);
  9531. } catch (e) {
  9532. this.updateProgressTimer(this.index++);
  9533. this.timeout(this.loop.bind(this), 0);
  9534. return;
  9535. }
  9536. const { progress, result } = this.lastResult;
  9537. this.lastBattleResult = result;
  9538. this.lastBattleProgress = progress;
  9539. this.setAvgTime(start);
  9540. this.checkResult();
  9541. this.showResult();
  9542. this.updateProgressTimer();
  9543. this.timeout(this.loop.bind(this), 0);
  9544. }
  9545.  
  9546. isEndLoop() {
  9547. return this.count >= this.maxCount || this.endTime < Date.now();
  9548. }
  9549.  
  9550. updateProgressTimer(index = 0) {
  9551. this.lastTimer = this.randTimer();
  9552. this.battle.progress = [{ attackers: { input: ['auto', 0, 0, 'auto', index, this.lastTimer] } }];
  9553. }
  9554.  
  9555. showResult() {
  9556. console.log(
  9557. this.count,
  9558. this.avgTime.toFixed(2),
  9559. (this.endTime - Date.now()) / 1000,
  9560. this.lastTimer.toFixed(2),
  9561. this.lastBossDamage.toLocaleString(),
  9562. this.bestResult.value.toLocaleString()
  9563. );
  9564. }
  9565.  
  9566. checkResult() {
  9567. const { damageTaken, damageTakenNextLevel } = this.lastBattleProgress[0].defenders.heroes[1].extra;
  9568. this.lastBossDamage = damageTaken + damageTakenNextLevel;
  9569. if (this.lastBossDamage > this.bestResult.value) {
  9570. this.bestResult = {
  9571. count: this.count,
  9572. timer: this.lastTimer,
  9573. value: this.lastBossDamage,
  9574. result: structuredClone(this.lastBattleResult),
  9575. progress: structuredClone(this.lastBattleProgress),
  9576. };
  9577. }
  9578. }
  9579.  
  9580. stopFix() {
  9581. this.endTime = 0;
  9582. }
  9583. }
  9584.  
  9585. this.HWHClasses.FixBattle = FixBattle;
  9586.  
  9587. class WinFixBattle extends FixBattle {
  9588. checkResult() {
  9589. if (this.lastBattleResult.win) {
  9590. this.bestResult = {
  9591. count: this.count,
  9592. timer: this.lastTimer,
  9593. value: this.lastBattleResult.stars,
  9594. result: structuredClone(this.lastBattleResult),
  9595. progress: structuredClone(this.lastBattleProgress),
  9596. battleTimer: this.lastResult.battleTimer,
  9597. };
  9598. }
  9599. }
  9600.  
  9601. setWinTimer(value) {
  9602. this.winTimer = value;
  9603. }
  9604.  
  9605. setMaxTimer(value) {
  9606. this.maxTimer = value;
  9607. }
  9608.  
  9609. randTimer() {
  9610. if (this.winTimer) {
  9611. return this.winTimer;
  9612. }
  9613. return super.randTimer();
  9614. }
  9615.  
  9616. isEndLoop() {
  9617. return super.isEndLoop() || this.bestResult.result?.win;
  9618. }
  9619.  
  9620. showResult() {
  9621. console.log(
  9622. this.count,
  9623. this.avgTime.toFixed(2),
  9624. (this.endTime - Date.now()) / 1000,
  9625. this.lastResult.battleTime,
  9626. this.lastTimer,
  9627. this.bestResult.value
  9628. );
  9629. const endTime = ((this.endTime - Date.now()) / 1000).toFixed(2);
  9630. const avgTime = this.avgTime.toFixed(2);
  9631. const msg = `${I18N('LETS_FIX')} ${this.count}/${this.maxCount}<br/>${endTime}s<br/>${avgTime}ms`;
  9632. setProgress(msg, false, this.stopFix.bind(this));
  9633. }
  9634. }
  9635.  
  9636. this.HWHClasses.WinFixBattle = WinFixBattle;
  9637.  
  9638. class BestOrWinFixBattle extends WinFixBattle {
  9639. isNoMakeWin = false;
  9640.  
  9641. getState(result) {
  9642. let beforeSumFactor = 0;
  9643. const beforeHeroes = result.battleData.defenders[0];
  9644. for (let heroId in beforeHeroes) {
  9645. const hero = beforeHeroes[heroId];
  9646. const state = hero.state;
  9647. let factor = 1;
  9648. if (state) {
  9649. const hp = state.hp / (hero?.hp || 1);
  9650. const energy = state.energy / 1e3;
  9651. factor = hp + energy / 20;
  9652. }
  9653. beforeSumFactor += factor;
  9654. }
  9655.  
  9656. let afterSumFactor = 0;
  9657. const afterHeroes = result.progress[0].defenders.heroes;
  9658. for (let heroId in afterHeroes) {
  9659. const hero = afterHeroes[heroId];
  9660. const hp = hero.hp / (beforeHeroes[heroId]?.hp || 1);
  9661. const energy = hero.energy / 1e3;
  9662. const factor = hp + energy / 20;
  9663. afterSumFactor += factor;
  9664. }
  9665. return 100 - Math.floor((afterSumFactor / beforeSumFactor) * 1e4) / 100;
  9666. }
  9667.  
  9668. setNoMakeWin(value) {
  9669. this.isNoMakeWin = value;
  9670. }
  9671.  
  9672. checkResult() {
  9673. const state = this.getState(this.lastResult);
  9674. console.log(state);
  9675.  
  9676. if (state > this.bestResult.value) {
  9677. if (!(this.isNoMakeWin && this.lastBattleResult.win)) {
  9678. this.bestResult = {
  9679. count: this.count,
  9680. timer: this.lastTimer,
  9681. value: state,
  9682. result: structuredClone(this.lastBattleResult),
  9683. progress: structuredClone(this.lastBattleProgress),
  9684. battleTimer: this.lastResult.battleTimer,
  9685. };
  9686. }
  9687. }
  9688. }
  9689. }
  9690.  
  9691. this.HWHClasses.BestOrWinFixBattle = BestOrWinFixBattle;
  9692.  
  9693. class BossFixBattle extends FixBattle {
  9694. showResult() {
  9695. super.showResult();
  9696. //setTimeout(() => {
  9697. const best = this.bestResult;
  9698. const maxDmg = best.value.toLocaleString();
  9699. const avgTime = this.avgTime.toLocaleString();
  9700. const msg = `${I18N('LETS_FIX')} ${this.count}/${this.maxCount}<br/>${maxDmg}<br/>${avgTime}ms`;
  9701. setProgress(msg, false, this.stopFix.bind(this));
  9702. //}, 0);
  9703. }
  9704. }
  9705.  
  9706. this.HWHClasses.BossFixBattle = BossFixBattle;
  9707.  
  9708. class DungeonFixBattle extends FixBattle {
  9709. init() {
  9710. super.init();
  9711. this.isTimeout = false;
  9712. }
  9713.  
  9714. setState() {
  9715. const result = this.lastResult;
  9716. let beforeSumFactor = 0;
  9717. const beforeHeroes = result.battleData.attackers;
  9718. for (let heroId in beforeHeroes) {
  9719. const hero = beforeHeroes[heroId];
  9720. const state = hero.state;
  9721. let factor = 1;
  9722. if (state) {
  9723. const hp = state.hp / (hero?.hp || 1);
  9724. const energy = state.energy / 1e3;
  9725. factor = hp + energy / 20;
  9726. }
  9727. beforeSumFactor += factor;
  9728. }
  9729.  
  9730. let afterSumFactor = 0;
  9731. const afterHeroes = result.progress[0].attackers.heroes;
  9732. for (let heroId in afterHeroes) {
  9733. const hero = afterHeroes[heroId];
  9734. const hp = hero.hp / (beforeHeroes[heroId]?.hp || 1);
  9735. const energy = hero.energy / 1e3;
  9736. const factor = hp + energy / 20;
  9737. afterSumFactor += factor;
  9738. }
  9739. this.lastState = Math.floor((afterSumFactor / beforeSumFactor) * 1e4) / 100;
  9740. }
  9741.  
  9742. checkResult() {
  9743. this.setState();
  9744. if (this.lastResult.result.win && this.lastState > this.bestResult.value) {
  9745. this.bestResult = {
  9746. count: this.count,
  9747. timer: this.lastTimer,
  9748. value: this.lastState,
  9749. result: this.lastResult.result,
  9750. progress: this.lastResult.progress,
  9751. };
  9752. }
  9753. }
  9754.  
  9755. showResult() {
  9756. console.log(
  9757. this.count,
  9758. this.avgTime.toFixed(2),
  9759. (this.endTime - Date.now()) / 1000,
  9760. this.lastTimer.toFixed(2),
  9761. this.lastState.toLocaleString(),
  9762. this.bestResult.value.toLocaleString()
  9763. );
  9764. }
  9765. }
  9766.  
  9767. this.HWHClasses.DungeonFixBattle = DungeonFixBattle;
  9768.  
  9769. const masterWsMixin = {
  9770. wsStart() {
  9771. const socket = new WebSocket(this.url);
  9772.  
  9773. socket.onopen = () => {
  9774. console.log('Connected to server');
  9775.  
  9776. // Пример создания новой задачи
  9777. const newTask = {
  9778. type: 'newTask',
  9779. battle: this.battle,
  9780. endTime: this.endTime - 1e4,
  9781. maxCount: this.maxCount,
  9782. };
  9783. socket.send(JSON.stringify(newTask));
  9784. };
  9785.  
  9786. socket.onmessage = this.onmessage.bind(this);
  9787.  
  9788. socket.onclose = () => {
  9789. console.log('Disconnected from server');
  9790. };
  9791.  
  9792. this.ws = socket;
  9793. },
  9794.  
  9795. onmessage(event) {
  9796. const data = JSON.parse(event.data);
  9797. switch (data.type) {
  9798. case 'newTask': {
  9799. console.log('newTask:', data);
  9800. this.id = data.id;
  9801. this.countExecutor = data.count;
  9802. break;
  9803. }
  9804. case 'getSolTask': {
  9805. console.log('getSolTask:', data);
  9806. this.endFix(data.solutions);
  9807. break;
  9808. }
  9809. case 'resolveTask': {
  9810. console.log('resolveTask:', data);
  9811. if (data.id === this.id && data.solutions.length === this.countExecutor) {
  9812. this.worker.terminate();
  9813. this.endFix(data.solutions);
  9814. }
  9815. break;
  9816. }
  9817. default:
  9818. console.log('Unknown message type:', data.type);
  9819. }
  9820. },
  9821.  
  9822. getTask() {
  9823. this.ws.send(
  9824. JSON.stringify({
  9825. type: 'getSolTask',
  9826. id: this.id,
  9827. })
  9828. );
  9829. },
  9830. };
  9831.  
  9832. /*
  9833. mFix = new action.masterFixBattle(battle)
  9834. await mFix.start(Date.now() + 6e4, 1);
  9835. */
  9836. class masterFixBattle extends FixBattle {
  9837. constructor(battle, url = 'wss://localho.st:3000') {
  9838. super(battle, true);
  9839. this.url = url;
  9840. }
  9841.  
  9842. async start(endTime, maxCount) {
  9843. this.endTime = endTime;
  9844. this.maxCount = maxCount;
  9845. this.init();
  9846. this.wsStart();
  9847. return await new Promise((resolve) => {
  9848. this.resolve = resolve;
  9849. const timeout = this.endTime - Date.now();
  9850. this.timeout(this.getTask.bind(this), timeout);
  9851. });
  9852. }
  9853.  
  9854. async endFix(solutions) {
  9855. this.ws.close();
  9856. let maxCount = 0;
  9857. for (const solution of solutions) {
  9858. maxCount += solution.maxCount;
  9859. if (solution.value > this.bestResult.value) {
  9860. this.bestResult = solution;
  9861. }
  9862. }
  9863. this.count = maxCount;
  9864. super.endFix();
  9865. }
  9866. }
  9867.  
  9868. Object.assign(masterFixBattle.prototype, masterWsMixin);
  9869.  
  9870. this.HWHClasses.masterFixBattle = masterFixBattle;
  9871.  
  9872. class masterWinFixBattle extends WinFixBattle {
  9873. constructor(battle, url = 'wss://localho.st:3000') {
  9874. super(battle, true);
  9875. this.url = url;
  9876. }
  9877.  
  9878. async start(endTime, maxCount) {
  9879. this.endTime = endTime;
  9880. this.maxCount = maxCount;
  9881. this.init();
  9882. this.wsStart();
  9883. return await new Promise((resolve) => {
  9884. this.resolve = resolve;
  9885. const timeout = this.endTime - Date.now();
  9886. this.timeout(this.getTask.bind(this), timeout);
  9887. });
  9888. }
  9889.  
  9890. async endFix(solutions) {
  9891. this.ws.close();
  9892. let maxCount = 0;
  9893. for (const solution of solutions) {
  9894. maxCount += solution.maxCount;
  9895. if (solution.value > this.bestResult.value) {
  9896. this.bestResult = solution;
  9897. }
  9898. }
  9899. this.count = maxCount;
  9900. super.endFix();
  9901. }
  9902. }
  9903.  
  9904. Object.assign(masterWinFixBattle.prototype, masterWsMixin);
  9905.  
  9906. this.HWHClasses.masterWinFixBattle = masterWinFixBattle;
  9907.  
  9908. const slaveWsMixin = {
  9909. wsStop() {
  9910. this.ws.close();
  9911. },
  9912.  
  9913. wsStart() {
  9914. const socket = new WebSocket(this.url);
  9915.  
  9916. socket.onopen = () => {
  9917. console.log('Connected to server');
  9918. };
  9919. socket.onmessage = this.onmessage.bind(this);
  9920. socket.onclose = () => {
  9921. console.log('Disconnected from server');
  9922. };
  9923.  
  9924. this.ws = socket;
  9925. },
  9926.  
  9927. async onmessage(event) {
  9928. const data = JSON.parse(event.data);
  9929. switch (data.type) {
  9930. case 'newTask': {
  9931. console.log('newTask:', data.task);
  9932. const { battle, endTime, maxCount } = data.task;
  9933. this.battle = battle;
  9934. const id = data.task.id;
  9935. const solution = await this.start(endTime, maxCount);
  9936. this.ws.send(
  9937. JSON.stringify({
  9938. type: 'resolveTask',
  9939. id,
  9940. solution,
  9941. })
  9942. );
  9943. break;
  9944. }
  9945. default:
  9946. console.log('Unknown message type:', data.type);
  9947. }
  9948. },
  9949. };
  9950. /*
  9951. sFix = new action.slaveFixBattle();
  9952. sFix.wsStart()
  9953. */
  9954. class slaveFixBattle extends FixBattle {
  9955. constructor(url = 'wss://localho.st:3000') {
  9956. super(null, false);
  9957. this.isTimeout = false;
  9958. this.url = url;
  9959. }
  9960. }
  9961.  
  9962. Object.assign(slaveFixBattle.prototype, slaveWsMixin);
  9963.  
  9964. this.HWHClasses.slaveFixBattle = slaveFixBattle;
  9965.  
  9966. class slaveWinFixBattle extends WinFixBattle {
  9967. constructor(url = 'wss://localho.st:3000') {
  9968. super(null, false);
  9969. this.isTimeout = false;
  9970. this.url = url;
  9971. }
  9972. }
  9973.  
  9974. Object.assign(slaveWinFixBattle.prototype, slaveWsMixin);
  9975.  
  9976. this.HWHClasses.slaveWinFixBattle = slaveWinFixBattle;
  9977. /**
  9978. * Auto-repeat attack
  9979. *
  9980. * Автоповтор атаки
  9981. */
  9982. function testAutoBattle() {
  9983. const { executeAutoBattle } = HWHClasses;
  9984. return new Promise((resolve, reject) => {
  9985. const bossBattle = new executeAutoBattle(resolve, reject);
  9986. bossBattle.start(lastBattleArg, lastBattleInfo);
  9987. });
  9988. }
  9989.  
  9990. /**
  9991. * Auto-repeat attack
  9992. *
  9993. * Автоповтор атаки
  9994. */
  9995. function executeAutoBattle(resolve, reject) {
  9996. let battleArg = {};
  9997. let countBattle = 0;
  9998. let countError = 0;
  9999. let findCoeff = 0;
  10000. let dataNotEeceived = 0;
  10001. let stopAutoBattle = false;
  10002.  
  10003. let isSetWinTimer = false;
  10004. const svgJustice = '<svg width="20" height="20" viewBox="0 0 124 125" xmlns="http://www.w3.org/2000/svg" style="fill: #fff;"><g><path d="m54 0h-1c-7.25 6.05-17.17 6.97-25.78 10.22-8.6 3.25-23.68 1.07-23.22 12.78s-0.47 24.08 1 35 2.36 18.36 7 28c4.43-8.31-3.26-18.88-3-30 0.26-11.11-2.26-25.29-1-37 11.88-4.16 26.27-0.42 36.77-9.23s20.53 6.05 29.23-0.77c-6.65-2.98-14.08-4.96-20-9z"/></g><g><path d="m108 5c-11.05 2.96-27.82 2.2-35.08 11.92s-14.91 14.71-22.67 23.33c-7.77 8.62-14.61 15.22-22.25 23.75 7.05 11.93 14.33 2.58 20.75-4.25 6.42-6.82 12.98-13.03 19.5-19.5s12.34-13.58 19.75-18.25c2.92 7.29-8.32 12.65-13.25 18.75-4.93 6.11-12.19 11.48-17.5 17.5s-12.31 11.38-17.25 17.75c10.34 14.49 17.06-3.04 26.77-10.23s15.98-16.89 26.48-24.52c10.5-7.64 12.09-24.46 14.75-36.25z"/></g><g><path d="m60 25c-11.52-6.74-24.53 8.28-38 6 0.84 9.61-1.96 20.2 2 29 5.53-4.04-4.15-23.2 4.33-26.67 8.48-3.48 18.14-1.1 24.67-8.33 2.73 0.3 4.81 2.98 7 0z"/></g><g><path d="m100 75c3.84-11.28 5.62-25.85 3-38-4.2 5.12-3.5 13.58-4 20s-3.52 13.18 1 18z"/></g><g><path d="m55 94c15.66-5.61 33.71-20.85 29-39-3.07 8.05-4.3 16.83-10.75 23.25s-14.76 8.35-18.25 15.75z"/></g><g><path d="m0 94v7c6.05 3.66 9.48 13.3 18 11-3.54-11.78 8.07-17.05 14-25 6.66 1.52 13.43 16.26 19 5-11.12-9.62-20.84-21.33-32-31-9.35 6.63 4.76 11.99 6 19-7.88 5.84-13.24 17.59-25 14z"/></g><g><path d="m82 125h26v-19h16v-1c-11.21-8.32-18.38-21.74-30-29-8.59 10.26-19.05 19.27-27 30h15v19z"/></g><g><path d="m68 110c-7.68-1.45-15.22 4.83-21.92-1.08s-11.94-5.72-18.08-11.92c-3.03 8.84 10.66 9.88 16.92 16.08s17.09 3.47 23.08-3.08z"/></g></svg>';
  10005. const svgBoss = '<svg width="20" height="20" viewBox="0 0 40 41" xmlns="http://www.w3.org/2000/svg" style="fill: #fff;"><g><path d="m21 12c-2.19-3.23 5.54-10.95-0.97-10.97-6.52-0.02 1.07 7.75-1.03 10.97-2.81 0.28-5.49-0.2-8-1-0.68 3.53 0.55 6.06 4 4 0.65 7.03 1.11 10.95 1.67 18.33 0.57 7.38 6.13 7.2 6.55-0.11 0.42-7.3 1.35-11.22 1.78-18.22 3.53 1.9 4.73-0.42 4-4-2.61 0.73-5.14 1.35-8 1m-1 17c-1.59-3.6-1.71-10.47 0-14 1.59 3.6 1.71 10.47 0 14z"/></g><g><path d="m6 19c-1.24-4.15 2.69-8.87 1-12-3.67 4.93-6.52 10.57-6 17 5.64-0.15 8.82 4.98 13 8 1.3-6.54-0.67-12.84-8-13z"/></g><g><path d="m33 7c0.38 5.57 2.86 14.79-7 15v10c4.13-2.88 7.55-7.97 13-8 0.48-6.46-2.29-12.06-6-17z"/></g></svg>';
  10006. const svgAttempt = '<svg width="20" height="20" viewBox="0 0 645 645" xmlns="http://www.w3.org/2000/svg" style="fill: #fff;"><g><path d="m442 26c-8.8 5.43-6.6 21.6-12.01 30.99-2.5 11.49-5.75 22.74-8.99 34.01-40.61-17.87-92.26-15.55-133.32-0.32-72.48 27.31-121.88 100.19-142.68 171.32 10.95-4.49 19.28-14.97 29.3-21.7 50.76-37.03 121.21-79.04 183.47-44.07 16.68 5.8 2.57 21.22-0.84 31.7-4.14 12.19-11.44 23.41-13.93 36.07 56.01-17.98 110.53-41.23 166-61-20.49-59.54-46.13-117.58-67-177z"/></g><g><path d="m563 547c23.89-16.34 36.1-45.65 47.68-71.32 23.57-62.18 7.55-133.48-28.38-186.98-15.1-22.67-31.75-47.63-54.3-63.7 1.15 14.03 6.71 26.8 8.22 40.78 12.08 61.99 15.82 148.76-48.15 183.29-10.46-0.54-15.99-16.1-24.32-22.82-8.2-7.58-14.24-19.47-23.75-24.25-4.88 59.04-11.18 117.71-15 177 62.9 5.42 126.11 9.6 189 15-4.84-9.83-17.31-15.4-24.77-24.23-9.02-7.06-17.8-15.13-26.23-22.77z"/></g><g><path d="m276 412c-10.69-15.84-30.13-25.9-43.77-40.23-15.39-12.46-30.17-25.94-45.48-38.52-15.82-11.86-29.44-28.88-46.75-37.25-19.07 24.63-39.96 48.68-60.25 72.75-18.71 24.89-42.41 47.33-58.75 73.25 22.4-2.87 44.99-13.6 66.67-13.67 0.06 22.8 10.69 42.82 20.41 62.59 49.09 93.66 166.6 114.55 261.92 96.08-6.07-9.2-22.11-9.75-31.92-16.08-59.45-26.79-138.88-75.54-127.08-151.92 21.66-2.39 43.42-4.37 65-7z"/></g></svg>';
  10007.  
  10008. this.start = function (battleArgs, battleInfo) {
  10009. battleArg = battleArgs;
  10010. if (nameFuncStartBattle == 'invasion_bossStart') {
  10011. startBattle();
  10012. return;
  10013. }
  10014. preCalcBattle(battleInfo);
  10015. }
  10016. /**
  10017. * Returns a promise for combat recalculation
  10018. *
  10019. * Возвращает промис для прерасчета боя
  10020. */
  10021. function getBattleInfo(battle) {
  10022. return new Promise(function (resolve) {
  10023. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  10024. Calc(battle).then(e => {
  10025. e.coeff = calcCoeff(e, 'defenders');
  10026. resolve(e);
  10027. });
  10028. });
  10029. }
  10030. /**
  10031. * Battle recalculation
  10032. *
  10033. * Прерасчет боя
  10034. */
  10035. function preCalcBattle(battle) {
  10036. let actions = [];
  10037. const countTestBattle = getInput('countTestBattle');
  10038. for (let i = 0; i < countTestBattle; i++) {
  10039. actions.push(getBattleInfo(battle));
  10040. }
  10041. Promise.all(actions)
  10042. .then(resultPreCalcBattle);
  10043. }
  10044. /**
  10045. * Processing the results of the battle recalculation
  10046. *
  10047. * Обработка результатов прерасчета боя
  10048. */
  10049. async function resultPreCalcBattle(results) {
  10050. let countWin = results.reduce((s, w) => w.result.win + s, 0);
  10051. setProgress(`${I18N('CHANCE_TO_WIN')} ${Math.floor(countWin / results.length * 100)}% (${results.length})`, false, hideProgress);
  10052. if (countWin > 0) {
  10053. setIsCancalBattle(false);
  10054. startBattle();
  10055. return;
  10056. }
  10057.  
  10058. let minCoeff = 100;
  10059. let maxCoeff = -100;
  10060. let avgCoeff = 0;
  10061. results.forEach(e => {
  10062. if (e.coeff < minCoeff) minCoeff = e.coeff;
  10063. if (e.coeff > maxCoeff) maxCoeff = e.coeff;
  10064. avgCoeff += e.coeff;
  10065. });
  10066. avgCoeff /= results.length;
  10067.  
  10068. if (nameFuncStartBattle == 'invasion_bossStart' ||
  10069. nameFuncStartBattle == 'bossAttack') {
  10070. const result = await popup.confirm(
  10071. I18N('BOSS_VICTORY_IMPOSSIBLE', { battles: results.length }), [
  10072. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  10073. { msg: I18N('BTN_DO_IT'), result: true },
  10074. ])
  10075. if (result) {
  10076. setIsCancalBattle(false);
  10077. startBattle();
  10078. return;
  10079. }
  10080. setProgress(I18N('NOT_THIS_TIME'), true);
  10081. endAutoBattle('invasion_bossStart');
  10082. return;
  10083. }
  10084.  
  10085. const result = await popup.confirm(
  10086. I18N('VICTORY_IMPOSSIBLE') +
  10087. `<br>${I18N('ROUND_STAT')} ${results.length} ${I18N('BATTLE')}:` +
  10088. `<br>${I18N('MINIMUM')}: ` + minCoeff.toLocaleString() +
  10089. `<br>${I18N('MAXIMUM')}: ` + maxCoeff.toLocaleString() +
  10090. `<br>${I18N('AVERAGE')}: ` + avgCoeff.toLocaleString() +
  10091. `<br>${I18N('FIND_COEFF')} ` + avgCoeff.toLocaleString(), [
  10092. { msg: I18N('BTN_CANCEL'), result: 0, isCancel: true },
  10093. { msg: I18N('BTN_GO'), isInput: true, default: Math.round(avgCoeff * 1000) / 1000 },
  10094. ])
  10095. if (result) {
  10096. findCoeff = result;
  10097. setIsCancalBattle(false);
  10098. startBattle();
  10099. return;
  10100. }
  10101. setProgress(I18N('NOT_THIS_TIME'), true);
  10102. endAutoBattle(I18N('NOT_THIS_TIME'));
  10103. }
  10104.  
  10105. /**
  10106. * Calculation of the combat result coefficient
  10107. *
  10108. * Расчет коэфициента результата боя
  10109. */
  10110. function calcCoeff(result, packType) {
  10111. let beforeSumFactor = 0;
  10112. const beforePack = result.battleData[packType][0];
  10113. for (let heroId in beforePack) {
  10114. const hero = beforePack[heroId];
  10115. const state = hero.state;
  10116. let factor = 1;
  10117. if (state) {
  10118. const hp = state.hp / state.maxHp;
  10119. const energy = state.energy / 1e3;
  10120. factor = hp + energy / 20;
  10121. }
  10122. beforeSumFactor += factor;
  10123. }
  10124.  
  10125. let afterSumFactor = 0;
  10126. const afterPack = result.progress[0][packType].heroes;
  10127. for (let heroId in afterPack) {
  10128. const hero = afterPack[heroId];
  10129. const stateHp = beforePack[heroId]?.state?.hp || beforePack[heroId]?.stats?.hp;
  10130. const hp = hero.hp / stateHp;
  10131. const energy = hero.energy / 1e3;
  10132. const factor = hp + energy / 20;
  10133. afterSumFactor += factor;
  10134. }
  10135. const resultCoeff = -(afterSumFactor - beforeSumFactor);
  10136. return Math.round(resultCoeff * 1000) / 1000;
  10137. }
  10138. /**
  10139. * Start battle
  10140. *
  10141. * Начало боя
  10142. */
  10143. function startBattle() {
  10144. countBattle++;
  10145. const countMaxBattle = getInput('countAutoBattle');
  10146. // setProgress(countBattle + '/' + countMaxBattle);
  10147. if (countBattle > countMaxBattle) {
  10148. setProgress(`${I18N('RETRY_LIMIT_EXCEEDED')}: ${countMaxBattle}`, true);
  10149. endAutoBattle(`${I18N('RETRY_LIMIT_EXCEEDED')}: ${countMaxBattle}`)
  10150. return;
  10151. }
  10152. if (stopAutoBattle) {
  10153. setProgress(I18N('STOPPED'), true);
  10154. endAutoBattle('STOPPED');
  10155. return;
  10156. }
  10157. send({calls: [{
  10158. name: nameFuncStartBattle,
  10159. args: battleArg,
  10160. ident: "body"
  10161. }]}, calcResultBattle);
  10162. }
  10163. /**
  10164. * Battle calculation
  10165. *
  10166. * Расчет боя
  10167. */
  10168. async function calcResultBattle(e) {
  10169. if (!e) {
  10170. console.log('данные не были получены');
  10171. if (dataNotEeceived < 10) {
  10172. dataNotEeceived++;
  10173. startBattle();
  10174. return;
  10175. }
  10176. endAutoBattle('Error', 'данные не были получены ' + dataNotEeceived + ' раз');
  10177. return;
  10178. }
  10179. if ('error' in e) {
  10180. if (e.error.description === 'too many tries') {
  10181. invasionTimer += 100;
  10182. countBattle--;
  10183. countError++;
  10184. console.log(`Errors: ${countError}`, e.error);
  10185. startBattle();
  10186. return;
  10187. }
  10188. const result = await popup.confirm(I18N('ERROR_DURING_THE_BATTLE') + '<br>' + e.error.description, [
  10189. { msg: I18N('BTN_OK'), result: false },
  10190. { msg: I18N('RELOAD_GAME'), result: true },
  10191. ]);
  10192. endAutoBattle('Error', e.error);
  10193. if (result) {
  10194. location.reload();
  10195. }
  10196. return;
  10197. }
  10198. let battle = e.results[0].result.response.battle
  10199. if (nameFuncStartBattle == 'towerStartBattle' ||
  10200. nameFuncStartBattle == 'bossAttack' ||
  10201. nameFuncStartBattle == 'invasion_bossStart') {
  10202. battle = e.results[0].result.response;
  10203. }
  10204. lastBattleInfo = battle;
  10205. BattleCalc(battle, getBattleType(battle.type), resultBattle);
  10206. }
  10207. /**
  10208. * Processing the results of the battle
  10209. *
  10210. * Обработка результатов боя
  10211. */
  10212. async function resultBattle(e) {
  10213. const isWin = e.result.win;
  10214. if (isWin) {
  10215. endBattle(e, false);
  10216. return;
  10217. } else if (isChecked('tryFixIt_v2')) {
  10218. const { WinFixBattle } = HWHClasses;
  10219. const cloneBattle = structuredClone(e.battleData);
  10220. const bFix = new WinFixBattle(cloneBattle);
  10221. let attempts = Infinity;
  10222. if (nameFuncStartBattle == 'invasion_bossStart' && !isSetWinTimer) {
  10223. let winTimer = await popup.confirm(`Secret number:`, [
  10224. { result: false, isClose: true },
  10225. { msg: 'Go', isInput: true, default: '0' },
  10226. ]);
  10227. winTimer = Number.parseFloat(winTimer);
  10228. if (winTimer) {
  10229. attempts = 5;
  10230. bFix.setWinTimer(winTimer);
  10231. }
  10232. isSetWinTimer = true;
  10233. }
  10234. let endTime = Date.now() + 6e4;
  10235. if (nameFuncStartBattle == 'invasion_bossStart') {
  10236. endTime = Date.now() + 6e4 * 4;
  10237. bFix.setMaxTimer(120.3);
  10238. }
  10239. const result = await bFix.start(endTime, attempts);
  10240. console.log(result);
  10241. if (result.value) {
  10242. endBattle(result, false);
  10243. return;
  10244. }
  10245. }
  10246. const countMaxBattle = getInput('countAutoBattle');
  10247. if (findCoeff) {
  10248. const coeff = calcCoeff(e, 'defenders');
  10249. setProgress(`${countBattle}/${countMaxBattle}, ${coeff}`);
  10250. if (coeff > findCoeff) {
  10251. endBattle(e, false);
  10252. return;
  10253. }
  10254. } else {
  10255. if (nameFuncStartBattle == 'invasion_bossStart') {
  10256. const bossLvl = lastBattleInfo.typeId >= 130 ? lastBattleInfo.typeId : '';
  10257. const justice = lastBattleInfo?.effects?.attackers?.percentInOutDamageModAndEnergyIncrease_any_99_100_300_99_1000_300 || 0;
  10258. setProgress(`${svgBoss} ${bossLvl} ${svgJustice} ${justice} <br>${svgAttempt} ${countBattle}/${countMaxBattle}`, false, () => {
  10259. stopAutoBattle = true;
  10260. });
  10261. await new Promise((resolve) => setTimeout(resolve, 5000));
  10262. } else {
  10263. setProgress(`${countBattle}/${countMaxBattle}`);
  10264. }
  10265. }
  10266. if (nameFuncStartBattle == 'towerStartBattle' ||
  10267. nameFuncStartBattle == 'bossAttack' ||
  10268. nameFuncStartBattle == 'invasion_bossStart') {
  10269. startBattle();
  10270. return;
  10271. }
  10272. cancelEndBattle(e);
  10273. }
  10274. /**
  10275. * Cancel fight
  10276. *
  10277. * Отмена боя
  10278. */
  10279. function cancelEndBattle(r) {
  10280. const fixBattle = function (heroes) {
  10281. for (const ids in heroes) {
  10282. hero = heroes[ids];
  10283. hero.energy = random(1, 999);
  10284. if (hero.hp > 0) {
  10285. hero.hp = random(1, hero.hp);
  10286. }
  10287. }
  10288. }
  10289. fixBattle(r.progress[0].attackers.heroes);
  10290. fixBattle(r.progress[0].defenders.heroes);
  10291. endBattle(r, true);
  10292. }
  10293. /**
  10294. * End of the fight
  10295. *
  10296. * Завершение боя */
  10297. function endBattle(battleResult, isCancal) {
  10298. let calls = [{
  10299. name: nameFuncEndBattle,
  10300. args: {
  10301. result: battleResult.result,
  10302. progress: battleResult.progress
  10303. },
  10304. ident: "body"
  10305. }];
  10306.  
  10307. if (nameFuncStartBattle == 'invasion_bossStart') {
  10308. calls[0].args.id = lastBattleArg.id;
  10309. }
  10310.  
  10311. send(JSON.stringify({
  10312. calls
  10313. }), async e => {
  10314. console.log(e);
  10315. if (isCancal) {
  10316. startBattle();
  10317. return;
  10318. }
  10319.  
  10320. setProgress(`${I18N('SUCCESS')}!`, 5000)
  10321. if (nameFuncStartBattle == 'invasion_bossStart' ||
  10322. nameFuncStartBattle == 'bossAttack') {
  10323. const countMaxBattle = getInput('countAutoBattle');
  10324. const bossLvl = lastBattleInfo.typeId >= 130 ? lastBattleInfo.typeId : '';
  10325. const justice = lastBattleInfo?.effects?.attackers?.percentInOutDamageModAndEnergyIncrease_any_99_100_300_99_1000_300 || 0;
  10326. let winTimer = '';
  10327. if (nameFuncStartBattle == 'invasion_bossStart') {
  10328. winTimer = '<br>Secret number: ' + battleResult.progress[0].attackers.input[5];
  10329. }
  10330. const result = await popup.confirm(
  10331. I18N('BOSS_HAS_BEEN_DEF_TEXT', {
  10332. bossLvl: `${svgBoss} ${bossLvl} ${svgJustice} ${justice}`,
  10333. countBattle: svgAttempt + ' ' + countBattle,
  10334. countMaxBattle,
  10335. winTimer,
  10336. }),
  10337. [
  10338. { msg: I18N('BTN_OK'), result: 0 },
  10339. { msg: I18N('MAKE_A_SYNC'), result: 1 },
  10340. { msg: I18N('RELOAD_GAME'), result: 2 },
  10341. ]
  10342. );
  10343. if (result) {
  10344. if (result == 1) {
  10345. cheats.refreshGame();
  10346. }
  10347. if (result == 2) {
  10348. location.reload();
  10349. }
  10350. }
  10351.  
  10352. }
  10353. endAutoBattle(`${I18N('SUCCESS')}!`)
  10354. });
  10355. }
  10356. /**
  10357. * Completing a task
  10358. *
  10359. * Завершение задачи
  10360. */
  10361. function endAutoBattle(reason, info) {
  10362. setIsCancalBattle(true);
  10363. console.log(reason, info);
  10364. resolve();
  10365. }
  10366. }
  10367.  
  10368. this.HWHClasses.executeAutoBattle = executeAutoBattle;
  10369.  
  10370. function testDailyQuests() {
  10371. const { dailyQuests } = HWHClasses;
  10372. return new Promise((resolve, reject) => {
  10373. const quests = new dailyQuests(resolve, reject);
  10374. quests.init(questsInfo);
  10375. quests.start();
  10376. });
  10377. }
  10378.  
  10379. /**
  10380. * Automatic completion of daily quests
  10381. *
  10382. * Автоматическое выполнение ежедневных квестов
  10383. */
  10384. class dailyQuests {
  10385. /**
  10386. * Send(' {"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}').then(e => console.log(e))
  10387. * Send(' {"calls":[{"name":"heroGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  10388. * Send(' {"calls":[{"name":"titanGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  10389. * Send(' {"calls":[{"name":"inventoryGet","args":{},"ident":"body"}]}').then(e => console.log(e))
  10390. * Send(' {"calls":[{"name":"questGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  10391. * Send(' {"calls":[{"name":"bossGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  10392. */
  10393. callsList = ['userGetInfo', 'heroGetAll', 'titanGetAll', 'inventoryGet', 'questGetAll', 'bossGetAll', 'missionGetAll'];
  10394.  
  10395. dataQuests = {
  10396. 10001: {
  10397. description: 'Улучши умения героев 3 раза', // ++++++++++++++++
  10398. doItCall: () => {
  10399. const upgradeSkills = this.getUpgradeSkills();
  10400. return upgradeSkills.map(({ heroId, skill }, index) => ({
  10401. name: 'heroUpgradeSkill',
  10402. args: { heroId, skill },
  10403. ident: `heroUpgradeSkill_${index}`,
  10404. }));
  10405. },
  10406. isWeCanDo: () => {
  10407. const upgradeSkills = this.getUpgradeSkills();
  10408. let sumGold = 0;
  10409. for (const skill of upgradeSkills) {
  10410. sumGold += this.skillCost(skill.value);
  10411. if (!skill.heroId) {
  10412. return false;
  10413. }
  10414. }
  10415. return this.questInfo['userGetInfo'].gold > sumGold;
  10416. },
  10417. },
  10418. 10002: {
  10419. description: 'Пройди 10 миссий', // --------------
  10420. isWeCanDo: () => false,
  10421. },
  10422. 10003: {
  10423. description: 'Пройди 3 героические миссии', // ++++++++++++++++
  10424. isWeCanDo: () => {
  10425. const vipPoints = +this.questInfo.userGetInfo.vipPoints;
  10426. const goldTicket = !!this.questInfo.inventoryGet.consumable[151];
  10427. return (vipPoints > 100 || goldTicket) && this.getHeroicMissionId();
  10428. },
  10429. doItCall: () => {
  10430. const selectedMissionId = this.getHeroicMissionId();
  10431. const goldTicket = !!this.questInfo.inventoryGet.consumable[151];
  10432. const vipLevel = Math.max(...lib.data.level.vip.filter(l => l.vipPoints <= +this.questInfo.userGetInfo.vipPoints).map(l => l.level));
  10433. // Возвращаем массив команд для рейда
  10434. if (vipLevel >= 5 || goldTicket) {
  10435. return [{ name: 'missionRaid', args: { id: selectedMissionId, times: 3 }, ident: 'missionRaid_1' }];
  10436. } else {
  10437. return [
  10438. { name: 'missionRaid', args: { id: selectedMissionId, times: 1 }, ident: 'missionRaid_1' },
  10439. { name: 'missionRaid', args: { id: selectedMissionId, times: 1 }, ident: 'missionRaid_2' },
  10440. { name: 'missionRaid', args: { id: selectedMissionId, times: 1 }, ident: 'missionRaid_3' },
  10441. ];
  10442. }
  10443. },
  10444. },
  10445. 10004: {
  10446. description: 'Сразись 3 раза на Арене или Гранд Арене', // --------------
  10447. isWeCanDo: () => false,
  10448. },
  10449. 10006: {
  10450. description: 'Используй обмен изумрудов 1 раз', // ++++++++++++++++
  10451. doItCall: () => [
  10452. {
  10453. name: 'refillableAlchemyUse',
  10454. args: { multi: false },
  10455. ident: 'refillableAlchemyUse',
  10456. },
  10457. ],
  10458. isWeCanDo: () => {
  10459. const starMoney = this.questInfo['userGetInfo'].starMoney;
  10460. return starMoney >= 20;
  10461. },
  10462. },
  10463. 10007: {
  10464. description: 'Соверши 1 призыв в Атриуме Душ', // ++++++++++++++++
  10465. doItCall: () => [{ name: 'gacha_open', args: { ident: 'heroGacha', free: true, pack: false }, ident: 'gacha_open' }],
  10466. isWeCanDo: () => {
  10467. const soulCrystal = this.questInfo['inventoryGet'].coin[38];
  10468. return soulCrystal > 0;
  10469. },
  10470. },
  10471. 10016: {
  10472. description: 'Отправь подарки согильдийцам', // ++++++++++++++++
  10473. doItCall: () => [{ name: 'clanSendDailyGifts', args: {}, ident: 'clanSendDailyGifts' }],
  10474. isWeCanDo: () => true,
  10475. },
  10476. 10018: {
  10477. description: 'Используй зелье опыта', // ++++++++++++++++
  10478. doItCall: () => {
  10479. const expHero = this.getExpHero();
  10480. return [
  10481. {
  10482. name: 'consumableUseHeroXp',
  10483. args: {
  10484. heroId: expHero.heroId,
  10485. libId: expHero.libId,
  10486. amount: 1,
  10487. },
  10488. ident: 'consumableUseHeroXp',
  10489. },
  10490. ];
  10491. },
  10492. isWeCanDo: () => {
  10493. const expHero = this.getExpHero();
  10494. return expHero.heroId && expHero.libId;
  10495. },
  10496. },
  10497. 10019: {
  10498. description: 'Открой 1 сундук в Башне',
  10499. doItFunc: testTower,
  10500. isWeCanDo: () => false,
  10501. },
  10502. 10020: {
  10503. description: 'Открой 3 сундука в Запределье', // Готово
  10504. doItCall: () => {
  10505. return this.getOutlandChest();
  10506. },
  10507. isWeCanDo: () => {
  10508. const outlandChest = this.getOutlandChest();
  10509. return outlandChest.length > 0;
  10510. },
  10511. },
  10512. 10021: {
  10513. description: 'Собери 75 Титанита в Подземелье Гильдии',
  10514. isWeCanDo: () => false,
  10515. },
  10516. 10022: {
  10517. description: 'Собери 150 Титанита в Подземелье Гильдии',
  10518. doItFunc: testDungeon,
  10519. isWeCanDo: () => false,
  10520. },
  10521. 10023: {
  10522. description: 'Прокачай Дар Стихий на 1 уровень', // Готово
  10523. doItCall: () => {
  10524. const heroId = this.getHeroIdTitanGift();
  10525. return [
  10526. { name: 'heroTitanGiftLevelUp', args: { heroId }, ident: 'heroTitanGiftLevelUp' },
  10527. { name: 'heroTitanGiftDrop', args: { heroId }, ident: 'heroTitanGiftDrop' },
  10528. ];
  10529. },
  10530. isWeCanDo: () => {
  10531. const heroId = this.getHeroIdTitanGift();
  10532. return heroId;
  10533. },
  10534. },
  10535. 10024: {
  10536. description: 'Повысь уровень любого артефакта один раз', // Готово
  10537. doItCall: () => {
  10538. const upArtifact = this.getUpgradeArtifact();
  10539. return [
  10540. {
  10541. name: 'heroArtifactLevelUp',
  10542. args: {
  10543. heroId: upArtifact.heroId,
  10544. slotId: upArtifact.slotId,
  10545. },
  10546. ident: `heroArtifactLevelUp`,
  10547. },
  10548. ];
  10549. },
  10550. isWeCanDo: () => {
  10551. const upgradeArtifact = this.getUpgradeArtifact();
  10552. return upgradeArtifact.heroId;
  10553. },
  10554. },
  10555. 10025: {
  10556. description: 'Начни 1 Экспедицию',
  10557. doItFunc: checkExpedition,
  10558. isWeCanDo: () => false,
  10559. },
  10560. 10026: {
  10561. description: 'Начни 4 Экспедиции', // --------------
  10562. doItFunc: checkExpedition,
  10563. isWeCanDo: () => false,
  10564. },
  10565. 10027: {
  10566. description: 'Победи в 1 бою Турнира Стихий',
  10567. doItFunc: testTitanArena,
  10568. isWeCanDo: () => false,
  10569. },
  10570. 10028: {
  10571. description: 'Повысь уровень любого артефакта титанов', // Готово
  10572. doItCall: () => {
  10573. const upTitanArtifact = this.getUpgradeTitanArtifact();
  10574. return [
  10575. {
  10576. name: 'titanArtifactLevelUp',
  10577. args: {
  10578. titanId: upTitanArtifact.titanId,
  10579. slotId: upTitanArtifact.slotId,
  10580. },
  10581. ident: `titanArtifactLevelUp`,
  10582. },
  10583. ];
  10584. },
  10585. isWeCanDo: () => {
  10586. const upgradeTitanArtifact = this.getUpgradeTitanArtifact();
  10587. return upgradeTitanArtifact.titanId;
  10588. },
  10589. },
  10590. 10029: {
  10591. description: 'Открой сферу артефактов титанов', // ++++++++++++++++
  10592. doItCall: () => [{ name: 'titanArtifactChestOpen', args: { amount: 1, free: true }, ident: 'titanArtifactChestOpen' }],
  10593. isWeCanDo: () => {
  10594. return this.questInfo['inventoryGet']?.consumable[55] > 0;
  10595. },
  10596. },
  10597. 10030: {
  10598. description: 'Улучши облик любого героя 1 раз', // Готово
  10599. doItCall: () => {
  10600. const upSkin = this.getUpgradeSkin();
  10601. return [
  10602. {
  10603. name: 'heroSkinUpgrade',
  10604. args: {
  10605. heroId: upSkin.heroId,
  10606. skinId: upSkin.skinId,
  10607. },
  10608. ident: `heroSkinUpgrade`,
  10609. },
  10610. ];
  10611. },
  10612. isWeCanDo: () => {
  10613. const upgradeSkin = this.getUpgradeSkin();
  10614. return upgradeSkin.heroId;
  10615. },
  10616. },
  10617. 10031: {
  10618. description: 'Победи в 6 боях Турнира Стихий', // --------------
  10619. doItFunc: testTitanArena,
  10620. isWeCanDo: () => false,
  10621. },
  10622. 10043: {
  10623. description: 'Начни или присоеденись к Приключению', // --------------
  10624. isWeCanDo: () => false,
  10625. },
  10626. 10044: {
  10627. description: 'Воспользуйся призывом питомцев 1 раз', // ++++++++++++++++
  10628. doItCall: () => [{ name: 'pet_chestOpen', args: { amount: 1, paid: false }, ident: 'pet_chestOpen' }],
  10629. isWeCanDo: () => {
  10630. return this.questInfo['inventoryGet']?.consumable[90] > 0;
  10631. },
  10632. },
  10633. 10046: {
  10634. /**
  10635. * TODO: Watch Adventure
  10636. * TODO: Смотреть приключение
  10637. */
  10638. description: 'Открой 3 сундука в Приключениях',
  10639. isWeCanDo: () => false,
  10640. },
  10641. 10047: {
  10642. description: 'Набери 150 очков активности в Гильдии', // Готово
  10643. doItCall: () => {
  10644. const enchantRune = this.getEnchantRune();
  10645. return [
  10646. {
  10647. name: 'heroEnchantRune',
  10648. args: {
  10649. heroId: enchantRune.heroId,
  10650. tier: enchantRune.tier,
  10651. items: {
  10652. consumable: { [enchantRune.itemId]: 1 },
  10653. },
  10654. },
  10655. ident: `heroEnchantRune`,
  10656. },
  10657. ];
  10658. },
  10659. isWeCanDo: () => {
  10660. const userInfo = this.questInfo['userGetInfo'];
  10661. const enchantRune = this.getEnchantRune();
  10662. return enchantRune.heroId && userInfo.gold > 1e3;
  10663. },
  10664. },
  10665. };
  10666.  
  10667. constructor(resolve, reject, questInfo) {
  10668. this.resolve = resolve;
  10669. this.reject = reject;
  10670. }
  10671.  
  10672. init(questInfo) {
  10673. this.questInfo = questInfo;
  10674. this.isAuto = false;
  10675. }
  10676.  
  10677. async autoInit(isAuto) {
  10678. this.isAuto = isAuto || false;
  10679. const quests = {};
  10680. const calls = this.callsList.map((name) => ({
  10681. name,
  10682. args: {},
  10683. ident: name,
  10684. }));
  10685. const result = await Send(JSON.stringify({ calls })).then((e) => e.results);
  10686. for (const call of result) {
  10687. quests[call.ident] = call.result.response;
  10688. }
  10689. this.questInfo = quests;
  10690. }
  10691.  
  10692. async start() {
  10693. const weCanDo = [];
  10694. const selectedActions = getSaveVal('selectedActions', {});
  10695. for (let quest of this.questInfo['questGetAll']) {
  10696. if (quest.id in this.dataQuests && quest.state == 1) {
  10697. if (!selectedActions[quest.id]) {
  10698. selectedActions[quest.id] = {
  10699. checked: false,
  10700. };
  10701. }
  10702.  
  10703. const isWeCanDo = this.dataQuests[quest.id].isWeCanDo;
  10704. if (!isWeCanDo.call(this)) {
  10705. continue;
  10706. }
  10707.  
  10708. weCanDo.push({
  10709. name: quest.id,
  10710. label: I18N(`QUEST_${quest.id}`),
  10711. checked: selectedActions[quest.id].checked,
  10712. });
  10713. }
  10714. }
  10715.  
  10716. if (!weCanDo.length) {
  10717. this.end(I18N('NOTHING_TO_DO'));
  10718. return;
  10719. }
  10720.  
  10721. console.log(weCanDo);
  10722. let taskList = [];
  10723. if (this.isAuto) {
  10724. taskList = weCanDo;
  10725. } else {
  10726. const answer = await popup.confirm(
  10727. `${I18N('YOU_CAN_COMPLETE')}:`,
  10728. [
  10729. { msg: I18N('BTN_DO_IT'), result: true },
  10730. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  10731. ],
  10732. weCanDo
  10733. );
  10734. if (!answer) {
  10735. this.end('');
  10736. return;
  10737. }
  10738. taskList = popup.getCheckBoxes();
  10739. taskList.forEach((e) => {
  10740. selectedActions[e.name].checked = e.checked;
  10741. });
  10742. setSaveVal('selectedActions', selectedActions);
  10743. }
  10744.  
  10745. const calls = [];
  10746. let countChecked = 0;
  10747. for (const task of taskList) {
  10748. if (task.checked) {
  10749. countChecked++;
  10750. const quest = this.dataQuests[task.name];
  10751. console.log(quest.description);
  10752.  
  10753. if (quest.doItCall) {
  10754. const doItCall = quest.doItCall.call(this);
  10755. calls.push(...doItCall);
  10756. }
  10757. }
  10758. }
  10759.  
  10760. if (!countChecked) {
  10761. this.end(I18N('NOT_QUEST_COMPLETED'));
  10762. return;
  10763. }
  10764.  
  10765. const result = await Send(JSON.stringify({ calls }));
  10766. if (result.error) {
  10767. console.error(result.error, result.error.call);
  10768. }
  10769. this.end(`${I18N('COMPLETED_QUESTS')}: ${countChecked}`);
  10770. }
  10771.  
  10772. errorHandling(error) {
  10773. //console.error(error);
  10774. let errorInfo = error.toString() + '\n';
  10775. try {
  10776. const errorStack = error.stack.split('\n');
  10777. const endStack = errorStack.map((e) => e.split('@')[0]).indexOf('testDoYourBest');
  10778. errorInfo += errorStack.slice(0, endStack).join('\n');
  10779. } catch (e) {
  10780. errorInfo += error.stack;
  10781. }
  10782. copyText(errorInfo);
  10783. }
  10784.  
  10785. skillCost(lvl) {
  10786. return 573 * lvl ** 0.9 + lvl ** 2.379;
  10787. }
  10788.  
  10789. getUpgradeSkills() {
  10790. const heroes = Object.values(this.questInfo['heroGetAll']);
  10791. const upgradeSkills = [
  10792. { heroId: 0, slotId: 0, value: 130 },
  10793. { heroId: 0, slotId: 0, value: 130 },
  10794. { heroId: 0, slotId: 0, value: 130 },
  10795. ];
  10796. const skillLib = lib.getData('skill');
  10797. /**
  10798. * color - 1 (белый) открывает 1 навык
  10799. * color - 2 (зеленый) открывает 2 навык
  10800. * color - 4 (синий) открывает 3 навык
  10801. * color - 7 (фиолетовый) открывает 4 навык
  10802. */
  10803. const colors = [1, 2, 4, 7];
  10804. for (const hero of heroes) {
  10805. const level = hero.level;
  10806. const color = hero.color;
  10807. for (let skillId in hero.skills) {
  10808. const tier = skillLib[skillId].tier;
  10809. const sVal = hero.skills[skillId];
  10810. if (color < colors[tier] || tier < 1 || tier > 4) {
  10811. continue;
  10812. }
  10813. for (let upSkill of upgradeSkills) {
  10814. if (sVal < upSkill.value && sVal < level) {
  10815. upSkill.value = sVal;
  10816. upSkill.heroId = hero.id;
  10817. upSkill.skill = tier;
  10818. break;
  10819. }
  10820. }
  10821. }
  10822. }
  10823. return upgradeSkills;
  10824. }
  10825.  
  10826. getUpgradeArtifact() {
  10827. const heroes = Object.values(this.questInfo['heroGetAll']);
  10828. const inventory = this.questInfo['inventoryGet'];
  10829. const upArt = { heroId: 0, slotId: 0, level: 100 };
  10830.  
  10831. const heroLib = lib.getData('hero');
  10832. const artifactLib = lib.getData('artifact');
  10833.  
  10834. for (const hero of heroes) {
  10835. const heroInfo = heroLib[hero.id];
  10836. const level = hero.level;
  10837. if (level < 20) {
  10838. continue;
  10839. }
  10840.  
  10841. for (let slotId in hero.artifacts) {
  10842. const art = hero.artifacts[slotId];
  10843. /* Текущая звезданость арта */
  10844. const star = art.star;
  10845. if (!star) {
  10846. continue;
  10847. }
  10848. /* Текущий уровень арта */
  10849. const level = art.level;
  10850. if (level >= 100) {
  10851. continue;
  10852. }
  10853. /* Идентификатор арта в библиотеке */
  10854. const artifactId = heroInfo.artifacts[slotId];
  10855. const artInfo = artifactLib.id[artifactId];
  10856. const costNextLevel = artifactLib.type[artInfo.type].levels[level + 1].cost;
  10857.  
  10858. const costCurrency = Object.keys(costNextLevel).pop();
  10859. const costValues = Object.entries(costNextLevel[costCurrency]).pop();
  10860. const costId = costValues[0];
  10861. const costValue = +costValues[1];
  10862.  
  10863. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  10864. if (level < upArt.level && inventory[costCurrency][costId] >= costValue) {
  10865. upArt.level = level;
  10866. upArt.heroId = hero.id;
  10867. upArt.slotId = slotId;
  10868. upArt.costCurrency = costCurrency;
  10869. upArt.costId = costId;
  10870. upArt.costValue = costValue;
  10871. }
  10872. }
  10873. }
  10874. return upArt;
  10875. }
  10876.  
  10877. getUpgradeSkin() {
  10878. const heroes = Object.values(this.questInfo['heroGetAll']);
  10879. const inventory = this.questInfo['inventoryGet'];
  10880. const upSkin = { heroId: 0, skinId: 0, level: 60, cost: 1500 };
  10881.  
  10882. const skinLib = lib.getData('skin');
  10883.  
  10884. for (const hero of heroes) {
  10885. const level = hero.level;
  10886. if (level < 20) {
  10887. continue;
  10888. }
  10889.  
  10890. for (let skinId in hero.skins) {
  10891. /* Текущий уровень скина */
  10892. const level = hero.skins[skinId];
  10893. if (level >= 60) {
  10894. continue;
  10895. }
  10896. /* Идентификатор скина в библиотеке */
  10897. const skinInfo = skinLib[skinId];
  10898. if (!skinInfo.statData.levels?.[level + 1]) {
  10899. continue;
  10900. }
  10901. const costNextLevel = skinInfo.statData.levels[level + 1].cost;
  10902.  
  10903. const costCurrency = Object.keys(costNextLevel).pop();
  10904. const costCurrencyId = Object.keys(costNextLevel[costCurrency]).pop();
  10905. const costValue = +costNextLevel[costCurrency][costCurrencyId];
  10906.  
  10907. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  10908. if (level < upSkin.level && costValue < upSkin.cost && inventory[costCurrency][costCurrencyId] >= costValue) {
  10909. upSkin.cost = costValue;
  10910. upSkin.level = level;
  10911. upSkin.heroId = hero.id;
  10912. upSkin.skinId = skinId;
  10913. upSkin.costCurrency = costCurrency;
  10914. upSkin.costCurrencyId = costCurrencyId;
  10915. }
  10916. }
  10917. }
  10918. return upSkin;
  10919. }
  10920.  
  10921. getUpgradeTitanArtifact() {
  10922. const titans = Object.values(this.questInfo['titanGetAll']);
  10923. const inventory = this.questInfo['inventoryGet'];
  10924. const userInfo = this.questInfo['userGetInfo'];
  10925. const upArt = { titanId: 0, slotId: 0, level: 120 };
  10926.  
  10927. const titanLib = lib.getData('titan');
  10928. const artTitanLib = lib.getData('titanArtifact');
  10929.  
  10930. for (const titan of titans) {
  10931. const titanInfo = titanLib[titan.id];
  10932. // const level = titan.level
  10933. // if (level < 20) {
  10934. // continue;
  10935. // }
  10936.  
  10937. for (let slotId in titan.artifacts) {
  10938. const art = titan.artifacts[slotId];
  10939. /* Текущая звезданость арта */
  10940. const star = art.star;
  10941. if (!star) {
  10942. continue;
  10943. }
  10944. /* Текущий уровень арта */
  10945. const level = art.level;
  10946. if (level >= 120) {
  10947. continue;
  10948. }
  10949. /* Идентификатор арта в библиотеке */
  10950. const artifactId = titanInfo.artifacts[slotId];
  10951. const artInfo = artTitanLib.id[artifactId];
  10952. const costNextLevel = artTitanLib.type[artInfo.type].levels[level + 1].cost;
  10953.  
  10954. const costCurrency = Object.keys(costNextLevel).pop();
  10955. let costValue = 0;
  10956. let currentValue = 0;
  10957. if (costCurrency == 'gold') {
  10958. costValue = costNextLevel[costCurrency];
  10959. currentValue = userInfo.gold;
  10960. } else {
  10961. const costValues = Object.entries(costNextLevel[costCurrency]).pop();
  10962. const costId = costValues[0];
  10963. costValue = +costValues[1];
  10964. currentValue = inventory[costCurrency][costId];
  10965. }
  10966.  
  10967. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  10968. if (level < upArt.level && currentValue >= costValue) {
  10969. upArt.level = level;
  10970. upArt.titanId = titan.id;
  10971. upArt.slotId = slotId;
  10972. break;
  10973. }
  10974. }
  10975. }
  10976. return upArt;
  10977. }
  10978.  
  10979. getEnchantRune() {
  10980. const heroes = Object.values(this.questInfo['heroGetAll']);
  10981. const inventory = this.questInfo['inventoryGet'];
  10982. const enchRune = { heroId: 0, tier: 0, exp: 43750, itemId: 0 };
  10983. for (let i = 1; i <= 4; i++) {
  10984. if (inventory.consumable[i] > 0) {
  10985. enchRune.itemId = i;
  10986. break;
  10987. }
  10988. return enchRune;
  10989. }
  10990.  
  10991. const runeLib = lib.getData('rune');
  10992. const runeLvls = Object.values(runeLib.level);
  10993. /**
  10994. * color - 4 (синий) открывает 1 и 2 символ
  10995. * color - 7 (фиолетовый) открывает 3 символ
  10996. * color - 8 (фиолетовый +1) открывает 4 символ
  10997. * color - 9 (фиолетовый +2) открывает 5 символ
  10998. */
  10999. // TODO: кажется надо учесть уровень команды
  11000. const colors = [4, 4, 7, 8, 9];
  11001. for (const hero of heroes) {
  11002. const color = hero.color;
  11003.  
  11004. for (let runeTier in hero.runes) {
  11005. /* Проверка на доступность руны */
  11006. if (color < colors[runeTier]) {
  11007. continue;
  11008. }
  11009. /* Текущий опыт руны */
  11010. const exp = hero.runes[runeTier];
  11011. if (exp >= 43750) {
  11012. continue;
  11013. }
  11014.  
  11015. let level = 0;
  11016. if (exp) {
  11017. for (let lvl of runeLvls) {
  11018. if (exp >= lvl.enchantValue) {
  11019. level = lvl.level;
  11020. } else {
  11021. break;
  11022. }
  11023. }
  11024. }
  11025. /** Уровень героя необходимый для уровня руны */
  11026. const heroLevel = runeLib.level[level].heroLevel;
  11027. if (hero.level < heroLevel) {
  11028. continue;
  11029. }
  11030.  
  11031. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  11032. if (exp < enchRune.exp) {
  11033. enchRune.exp = exp;
  11034. enchRune.heroId = hero.id;
  11035. enchRune.tier = runeTier;
  11036. break;
  11037. }
  11038. }
  11039. }
  11040. return enchRune;
  11041. }
  11042.  
  11043. getOutlandChest() {
  11044. const bosses = this.questInfo['bossGetAll'];
  11045.  
  11046. const calls = [];
  11047.  
  11048. for (let boss of bosses) {
  11049. if (boss.mayRaid) {
  11050. calls.push({
  11051. name: 'bossRaid',
  11052. args: {
  11053. bossId: boss.id,
  11054. },
  11055. ident: 'bossRaid_' + boss.id,
  11056. });
  11057. calls.push({
  11058. name: 'bossOpenChest',
  11059. args: {
  11060. bossId: boss.id,
  11061. amount: 1,
  11062. starmoney: 0,
  11063. },
  11064. ident: 'bossOpenChest_' + boss.id,
  11065. });
  11066. } else if (boss.chestId == 1) {
  11067. calls.push({
  11068. name: 'bossOpenChest',
  11069. args: {
  11070. bossId: boss.id,
  11071. amount: 1,
  11072. starmoney: 0,
  11073. },
  11074. ident: 'bossOpenChest_' + boss.id,
  11075. });
  11076. }
  11077. }
  11078.  
  11079. return calls;
  11080. }
  11081.  
  11082. getExpHero() {
  11083. const heroes = Object.values(this.questInfo['heroGetAll']);
  11084. const inventory = this.questInfo['inventoryGet'];
  11085. const expHero = { heroId: 0, exp: 3625195, libId: 0 };
  11086. /** зелья опыта (consumable 9, 10, 11, 12) */
  11087. for (let i = 9; i <= 12; i++) {
  11088. if (inventory.consumable[i]) {
  11089. expHero.libId = i;
  11090. break;
  11091. }
  11092. }
  11093.  
  11094. for (const hero of heroes) {
  11095. const exp = hero.xp;
  11096. if (exp < expHero.exp) {
  11097. expHero.heroId = hero.id;
  11098. }
  11099. }
  11100. return expHero;
  11101. }
  11102.  
  11103. getHeroIdTitanGift() {
  11104. const heroes = Object.values(this.questInfo['heroGetAll']);
  11105. const inventory = this.questInfo['inventoryGet'];
  11106. const user = this.questInfo['userGetInfo'];
  11107. const titanGiftLib = lib.getData('titanGift');
  11108. /** Искры */
  11109. const titanGift = inventory.consumable[24];
  11110. let heroId = 0;
  11111. let minLevel = 30;
  11112.  
  11113. if (titanGift < 250 || user.gold < 7000) {
  11114. return 0;
  11115. }
  11116.  
  11117. for (const hero of heroes) {
  11118. if (hero.titanGiftLevel >= 30) {
  11119. continue;
  11120. }
  11121.  
  11122. if (!hero.titanGiftLevel) {
  11123. return hero.id;
  11124. }
  11125.  
  11126. const cost = titanGiftLib[hero.titanGiftLevel].cost;
  11127. if (minLevel > hero.titanGiftLevel && titanGift >= cost.consumable[24] && user.gold >= cost.gold) {
  11128. minLevel = hero.titanGiftLevel;
  11129. heroId = hero.id;
  11130. }
  11131. }
  11132.  
  11133. return heroId;
  11134. }
  11135.  
  11136. getHeroicMissionId() {
  11137. // Получаем доступные миссии с 3 звездами
  11138. const availableMissionsToRaid = Object.values(this.questInfo.missionGetAll)
  11139. .filter((mission) => mission.stars === 3)
  11140. .map((mission) => mission.id);
  11141.  
  11142. // Получаем героев для улучшения, у которых меньше 6 звезд
  11143. const heroesToUpgrade = Object.values(this.questInfo.heroGetAll)
  11144. .filter((hero) => hero.star < 6)
  11145. .sort((a, b) => b.power - a.power)
  11146. .map((hero) => hero.id);
  11147.  
  11148. // Получаем героические миссии, которые доступны для рейдов
  11149. const heroicMissions = Object.values(lib.data.mission).filter((mission) => mission.isHeroic && availableMissionsToRaid.includes(mission.id));
  11150.  
  11151. // Собираем дропы из героических миссий
  11152. const drops = heroicMissions.map((mission) => {
  11153. const lastWave = mission.normalMode.waves[mission.normalMode.waves.length - 1];
  11154. const allRewards = lastWave.enemies[lastWave.enemies.length - 1]
  11155. .drop.map((drop) => drop.reward);
  11156.  
  11157. const heroId = +Object.keys(allRewards.find((reward) => reward.fragmentHero).fragmentHero).pop();
  11158.  
  11159. return { id: mission.id, heroId };
  11160. });
  11161.  
  11162. // Определяем, какие дропы подходят для героев, которых нужно улучшить
  11163. const heroDrops = heroesToUpgrade.map((heroId) => drops.find((drop) => drop.heroId == heroId)).filter((drop) => drop);
  11164. const firstMission = heroDrops[0];
  11165. // Выбираем миссию для рейда
  11166. const selectedMissionId = firstMission ? firstMission.id : 1;
  11167.  
  11168. const stamina = this.questInfo.userGetInfo.refillable.find((x) => x.id == 1).amount;
  11169. const costMissions = 3 * lib.data.mission[selectedMissionId].normalMode.teamExp;
  11170. if (stamina < costMissions) {
  11171. console.log('Энергии не достаточно');
  11172. return 0;
  11173. }
  11174. return selectedMissionId;
  11175. }
  11176.  
  11177. end(status) {
  11178. setProgress(status, true);
  11179. this.resolve();
  11180. }
  11181. }
  11182.  
  11183. this.questRun = dailyQuests;
  11184. this.HWHClasses.dailyQuests = dailyQuests;
  11185.  
  11186. function testDoYourBest() {
  11187. const { doYourBest } = HWHClasses;
  11188. return new Promise((resolve, reject) => {
  11189. const doIt = new doYourBest(resolve, reject);
  11190. doIt.start();
  11191. });
  11192. }
  11193.  
  11194. /**
  11195. * Do everything button
  11196. *
  11197. * Кнопка сделать все
  11198. */
  11199. class doYourBest {
  11200.  
  11201. funcList = [
  11202. {
  11203. name: 'getOutland',
  11204. label: I18N('ASSEMBLE_OUTLAND'),
  11205. checked: false
  11206. },
  11207. {
  11208. name: 'testTower',
  11209. label: I18N('PASS_THE_TOWER'),
  11210. checked: false
  11211. },
  11212. {
  11213. name: 'checkExpedition',
  11214. label: I18N('CHECK_EXPEDITIONS'),
  11215. checked: false
  11216. },
  11217. {
  11218. name: 'testTitanArena',
  11219. label: I18N('COMPLETE_TOE'),
  11220. checked: false
  11221. },
  11222. {
  11223. name: 'mailGetAll',
  11224. label: I18N('COLLECT_MAIL'),
  11225. checked: false
  11226. },
  11227. {
  11228. name: 'collectAllStuff',
  11229. label: I18N('COLLECT_MISC'),
  11230. title: I18N('COLLECT_MISC_TITLE'),
  11231. checked: false
  11232. },
  11233. {
  11234. name: 'getDailyBonus',
  11235. label: I18N('DAILY_BONUS'),
  11236. checked: false
  11237. },
  11238. {
  11239. name: 'dailyQuests',
  11240. label: I18N('DO_DAILY_QUESTS'),
  11241. checked: false
  11242. },
  11243. {
  11244. name: 'rollAscension',
  11245. label: I18N('SEER_TITLE'),
  11246. checked: false
  11247. },
  11248. {
  11249. name: 'questAllFarm',
  11250. label: I18N('COLLECT_QUEST_REWARDS'),
  11251. checked: false
  11252. },
  11253. {
  11254. name: 'testDungeon',
  11255. label: I18N('COMPLETE_DUNGEON'),
  11256. checked: false
  11257. },
  11258. {
  11259. name: 'synchronization',
  11260. label: I18N('MAKE_A_SYNC'),
  11261. checked: false
  11262. },
  11263. {
  11264. name: 'reloadGame',
  11265. label: I18N('RELOAD_GAME'),
  11266. checked: false
  11267. },
  11268. ];
  11269.  
  11270. functions = {
  11271. getOutland,
  11272. testTower,
  11273. checkExpedition,
  11274. testTitanArena,
  11275. mailGetAll,
  11276. collectAllStuff: async () => {
  11277. await offerFarmAllReward();
  11278. await Send('{"calls":[{"name":"subscriptionFarm","args":{},"ident":"body"},{"name":"zeppelinGiftFarm","args":{},"ident":"zeppelinGiftFarm"},{"name":"grandFarmCoins","args":{},"ident":"grandFarmCoins"},{"name":"gacha_refill","args":{"ident":"heroGacha"},"ident":"gacha_refill"}]}');
  11279. },
  11280. dailyQuests: async function () {
  11281. const quests = new dailyQuests(() => { }, () => { });
  11282. await quests.autoInit(true);
  11283. await quests.start();
  11284. },
  11285. rollAscension,
  11286. getDailyBonus,
  11287. questAllFarm,
  11288. testDungeon,
  11289. synchronization: async () => {
  11290. cheats.refreshGame();
  11291. },
  11292. reloadGame: async () => {
  11293. location.reload();
  11294. },
  11295. }
  11296.  
  11297. constructor(resolve, reject, questInfo) {
  11298. this.resolve = resolve;
  11299. this.reject = reject;
  11300. this.questInfo = questInfo
  11301. }
  11302.  
  11303. async start() {
  11304. const selectedDoIt = getSaveVal('selectedDoIt', {});
  11305.  
  11306. this.funcList.forEach(task => {
  11307. if (!selectedDoIt[task.name]) {
  11308. selectedDoIt[task.name] = {
  11309. checked: task.checked
  11310. }
  11311. } else {
  11312. task.checked = selectedDoIt[task.name].checked
  11313. }
  11314. });
  11315.  
  11316. const answer = await popup.confirm(I18N('RUN_FUNCTION'), [
  11317. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  11318. { msg: I18N('BTN_GO'), result: true },
  11319. ], this.funcList);
  11320.  
  11321. if (!answer) {
  11322. this.end('');
  11323. return;
  11324. }
  11325.  
  11326. const taskList = popup.getCheckBoxes();
  11327. taskList.forEach(task => {
  11328. selectedDoIt[task.name].checked = task.checked;
  11329. });
  11330. setSaveVal('selectedDoIt', selectedDoIt);
  11331. for (const task of popup.getCheckBoxes()) {
  11332. if (task.checked) {
  11333. try {
  11334. setProgress(`${task.label} <br>${I18N('PERFORMED')}!`);
  11335. await this.functions[task.name]();
  11336. setProgress(`${task.label} <br>${I18N('DONE')}!`);
  11337. } catch (error) {
  11338. if (await popup.confirm(`${I18N('ERRORS_OCCURRES')}:<br> ${task.label} <br>${I18N('COPY_ERROR')}?`, [
  11339. { msg: I18N('BTN_NO'), result: false },
  11340. { msg: I18N('BTN_YES'), result: true },
  11341. ])) {
  11342. this.errorHandling(error);
  11343. }
  11344. }
  11345. }
  11346. }
  11347. setTimeout((msg) => {
  11348. this.end(msg);
  11349. }, 2000, I18N('ALL_TASK_COMPLETED'));
  11350. return;
  11351. }
  11352.  
  11353. errorHandling(error) {
  11354. //console.error(error);
  11355. let errorInfo = error.toString() + '\n';
  11356. try {
  11357. const errorStack = error.stack.split('\n');
  11358. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testDoYourBest");
  11359. errorInfo += errorStack.slice(0, endStack).join('\n');
  11360. } catch (e) {
  11361. errorInfo += error.stack;
  11362. }
  11363. copyText(errorInfo);
  11364. }
  11365.  
  11366. end(status) {
  11367. setProgress(status, true);
  11368. this.resolve();
  11369. }
  11370. }
  11371.  
  11372. this.HWHClasses.doYourBest = doYourBest;
  11373.  
  11374. /**
  11375. * Passing the adventure along the specified route
  11376. *
  11377. * Прохождение приключения по указанному маршруту
  11378. */
  11379. function testAdventure(type) {
  11380. const { executeAdventure } = HWHClasses;
  11381. return new Promise((resolve, reject) => {
  11382. const bossBattle = new executeAdventure(resolve, reject);
  11383. bossBattle.start(type);
  11384. });
  11385. }
  11386.  
  11387. /**
  11388. * Passing the adventure along the specified route
  11389. *
  11390. * Прохождение приключения по указанному маршруту
  11391. */
  11392. class executeAdventure {
  11393.  
  11394. type = 'default';
  11395.  
  11396. actions = {
  11397. default: {
  11398. getInfo: "adventure_getInfo",
  11399. startBattle: 'adventure_turnStartBattle',
  11400. endBattle: 'adventure_endBattle',
  11401. collectBuff: 'adventure_turnCollectBuff'
  11402. },
  11403. solo: {
  11404. getInfo: "adventureSolo_getInfo",
  11405. startBattle: 'adventureSolo_turnStartBattle',
  11406. endBattle: 'adventureSolo_endBattle',
  11407. collectBuff: 'adventureSolo_turnCollectBuff'
  11408. }
  11409. }
  11410.  
  11411. terminatеReason = I18N('UNKNOWN');
  11412. callAdventureInfo = {
  11413. name: "adventure_getInfo",
  11414. args: {},
  11415. ident: "adventure_getInfo"
  11416. }
  11417. callTeamGetAll = {
  11418. name: "teamGetAll",
  11419. args: {},
  11420. ident: "teamGetAll"
  11421. }
  11422. callTeamGetFavor = {
  11423. name: "teamGetFavor",
  11424. args: {},
  11425. ident: "teamGetFavor"
  11426. }
  11427. callStartBattle = {
  11428. name: "adventure_turnStartBattle",
  11429. args: {},
  11430. ident: "body"
  11431. }
  11432. callEndBattle = {
  11433. name: "adventure_endBattle",
  11434. args: {
  11435. result: {},
  11436. progress: {},
  11437. },
  11438. ident: "body"
  11439. }
  11440. callCollectBuff = {
  11441. name: "adventure_turnCollectBuff",
  11442. args: {},
  11443. ident: "body"
  11444. }
  11445.  
  11446. constructor(resolve, reject) {
  11447. this.resolve = resolve;
  11448. this.reject = reject;
  11449. }
  11450.  
  11451. async start(type) {
  11452. this.type = type || this.type;
  11453. this.callAdventureInfo.name = this.actions[this.type].getInfo;
  11454. const data = await Send(JSON.stringify({
  11455. calls: [
  11456. this.callAdventureInfo,
  11457. this.callTeamGetAll,
  11458. this.callTeamGetFavor
  11459. ]
  11460. }));
  11461. return this.checkAdventureInfo(data.results);
  11462. }
  11463.  
  11464. async getPath() {
  11465. const oldVal = getSaveVal('adventurePath', '');
  11466. const keyPath = `adventurePath:${this.mapIdent}`;
  11467. const answer = await popup.confirm(I18N('ENTER_THE_PATH'), [
  11468. {
  11469. msg: I18N('START_ADVENTURE'),
  11470. placeholder: '1,2,3,4,5,6',
  11471. isInput: true,
  11472. default: getSaveVal(keyPath, oldVal)
  11473. },
  11474. {
  11475. msg: I18N('BTN_CANCEL'),
  11476. result: false,
  11477. isCancel: true
  11478. },
  11479. ]);
  11480. if (!answer) {
  11481. this.terminatеReason = I18N('BTN_CANCELED');
  11482. return false;
  11483. }
  11484.  
  11485. let path = answer.split(',');
  11486. if (path.length < 2) {
  11487. path = answer.split('-');
  11488. }
  11489. if (path.length < 2) {
  11490. this.terminatеReason = I18N('MUST_TWO_POINTS');
  11491. return false;
  11492. }
  11493.  
  11494. for (let p in path) {
  11495. path[p] = +path[p].trim()
  11496. if (Number.isNaN(path[p])) {
  11497. this.terminatеReason = I18N('MUST_ONLY_NUMBERS');
  11498. return false;
  11499. }
  11500. }
  11501.  
  11502. if (!this.checkPath(path)) {
  11503. return false;
  11504. }
  11505. setSaveVal(keyPath, answer);
  11506. return path;
  11507. }
  11508.  
  11509. checkPath(path) {
  11510. for (let i = 0; i < path.length - 1; i++) {
  11511. const currentPoint = path[i];
  11512. const nextPoint = path[i + 1];
  11513.  
  11514. const isValidPath = this.paths.some(p =>
  11515. (p.from_id === currentPoint && p.to_id === nextPoint) ||
  11516. (p.from_id === nextPoint && p.to_id === currentPoint)
  11517. );
  11518.  
  11519. if (!isValidPath) {
  11520. this.terminatеReason = I18N('INCORRECT_WAY', {
  11521. from: currentPoint,
  11522. to: nextPoint,
  11523. });
  11524. return false;
  11525. }
  11526. }
  11527.  
  11528. return true;
  11529. }
  11530.  
  11531. async checkAdventureInfo(data) {
  11532. this.advInfo = data[0].result.response;
  11533. if (!this.advInfo) {
  11534. this.terminatеReason = I18N('NOT_ON_AN_ADVENTURE') ;
  11535. return this.end();
  11536. }
  11537. const heroesTeam = data[1].result.response.adventure_hero;
  11538. const favor = data[2]?.result.response.adventure_hero;
  11539. const heroes = heroesTeam.slice(0, 5);
  11540. const pet = heroesTeam[5];
  11541. this.args = {
  11542. pet,
  11543. heroes,
  11544. favor,
  11545. path: [],
  11546. broadcast: false
  11547. }
  11548. const advUserInfo = this.advInfo.users[userInfo.id];
  11549. this.turnsLeft = advUserInfo.turnsLeft;
  11550. this.currentNode = advUserInfo.currentNode;
  11551. this.nodes = this.advInfo.nodes;
  11552. this.paths = this.advInfo.paths;
  11553. this.mapIdent = this.advInfo.mapIdent;
  11554.  
  11555. this.path = await this.getPath();
  11556. if (!this.path) {
  11557. return this.end();
  11558. }
  11559.  
  11560. if (this.currentNode == 1 && this.path[0] != 1) {
  11561. this.path.unshift(1);
  11562. }
  11563.  
  11564. return this.loop();
  11565. }
  11566.  
  11567. async loop() {
  11568. const position = this.path.indexOf(+this.currentNode);
  11569. if (!(~position)) {
  11570. this.terminatеReason = I18N('YOU_IN_NOT_ON_THE_WAY');
  11571. return this.end();
  11572. }
  11573. this.path = this.path.slice(position);
  11574. if ((this.path.length - 1) > this.turnsLeft &&
  11575. await popup.confirm(I18N('ATTEMPTS_NOT_ENOUGH'), [
  11576. { msg: I18N('YES_CONTINUE'), result: false },
  11577. { msg: I18N('BTN_NO'), result: true },
  11578. ])) {
  11579. this.terminatеReason = I18N('NOT_ENOUGH_AP');
  11580. return this.end();
  11581. }
  11582. const toPath = [];
  11583. for (const nodeId of this.path) {
  11584. if (!this.turnsLeft) {
  11585. this.terminatеReason = I18N('ATTEMPTS_ARE_OVER');
  11586. return this.end();
  11587. }
  11588. toPath.push(nodeId);
  11589. console.log(toPath);
  11590. if (toPath.length > 1) {
  11591. setProgress(toPath.join(' > ') + ` ${I18N('MOVES')}: ` + this.turnsLeft);
  11592. }
  11593. if (nodeId == this.currentNode) {
  11594. continue;
  11595. }
  11596.  
  11597. const nodeInfo = this.getNodeInfo(nodeId);
  11598. if (nodeInfo.type == 'TYPE_COMBAT') {
  11599. if (nodeInfo.state == 'empty') {
  11600. this.turnsLeft--;
  11601. continue;
  11602. }
  11603.  
  11604. /**
  11605. * Disable regular battle cancellation
  11606. *
  11607. * Отключаем штатную отменую боя
  11608. */
  11609. setIsCancalBattle(false);
  11610. if (await this.battle(toPath)) {
  11611. this.turnsLeft--;
  11612. toPath.splice(0, toPath.indexOf(nodeId));
  11613. nodeInfo.state = 'empty';
  11614. setIsCancalBattle(true);
  11615. continue;
  11616. }
  11617. setIsCancalBattle(true);
  11618. return this.end()
  11619. }
  11620.  
  11621. if (nodeInfo.type == 'TYPE_PLAYERBUFF') {
  11622. const buff = this.checkBuff(nodeInfo);
  11623. if (buff == null) {
  11624. continue;
  11625. }
  11626.  
  11627. if (await this.collectBuff(buff, toPath)) {
  11628. this.turnsLeft--;
  11629. toPath.splice(0, toPath.indexOf(nodeId));
  11630. continue;
  11631. }
  11632. this.terminatеReason = I18N('BUFF_GET_ERROR');
  11633. return this.end();
  11634. }
  11635. }
  11636. this.terminatеReason = I18N('SUCCESS');
  11637. return this.end();
  11638. }
  11639.  
  11640. /**
  11641. * Carrying out a fight
  11642. *
  11643. * Проведение боя
  11644. */
  11645. async battle(path, preCalc = true) {
  11646. const data = await this.startBattle(path);
  11647. try {
  11648. const battle = data.results[0].result.response.battle;
  11649. const result = await Calc(battle);
  11650. if (result.result.win) {
  11651. const info = await this.endBattle(result);
  11652. if (info.results[0].result.response?.error) {
  11653. this.terminatеReason = I18N('BATTLE_END_ERROR');
  11654. return false;
  11655. }
  11656. } else {
  11657. await this.cancelBattle(result);
  11658.  
  11659. if (preCalc && await this.preCalcBattle(battle)) {
  11660. path = path.slice(-2);
  11661. for (let i = 1; i <= getInput('countAutoBattle'); i++) {
  11662. setProgress(`${I18N('AUTOBOT')}: ${i}/${getInput('countAutoBattle')}`);
  11663. const result = await this.battle(path, false);
  11664. if (result) {
  11665. setProgress(I18N('VICTORY'));
  11666. return true;
  11667. }
  11668. }
  11669. this.terminatеReason = I18N('FAILED_TO_WIN_AUTO');
  11670. return false;
  11671. }
  11672. return false;
  11673. }
  11674. } catch (error) {
  11675. console.error(error);
  11676. if (await popup.confirm(I18N('ERROR_OF_THE_BATTLE_COPY'), [
  11677. { msg: I18N('BTN_NO'), result: false },
  11678. { msg: I18N('BTN_YES'), result: true },
  11679. ])) {
  11680. this.errorHandling(error, data);
  11681. }
  11682. this.terminatеReason = I18N('ERROR_DURING_THE_BATTLE');
  11683. return false;
  11684. }
  11685. return true;
  11686. }
  11687.  
  11688. /**
  11689. * Recalculate battles
  11690. *
  11691. * Прерасчтет битвы
  11692. */
  11693. async preCalcBattle(battle) {
  11694. const countTestBattle = getInput('countTestBattle');
  11695. for (let i = 0; i < countTestBattle; i++) {
  11696. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  11697. const result = await Calc(battle);
  11698. if (result.result.win) {
  11699. console.log(i, countTestBattle);
  11700. return true;
  11701. }
  11702. }
  11703. this.terminatеReason = I18N('NO_CHANCE_WIN') + countTestBattle;
  11704. return false;
  11705. }
  11706.  
  11707. /**
  11708. * Starts a fight
  11709. *
  11710. * Начинает бой
  11711. */
  11712. startBattle(path) {
  11713. this.args.path = path;
  11714. this.callStartBattle.name = this.actions[this.type].startBattle;
  11715. this.callStartBattle.args = this.args
  11716. const calls = [this.callStartBattle];
  11717. return Send(JSON.stringify({ calls }));
  11718. }
  11719.  
  11720. cancelBattle(battle) {
  11721. const fixBattle = function (heroes) {
  11722. for (const ids in heroes) {
  11723. const hero = heroes[ids];
  11724. hero.energy = random(1, 999);
  11725. if (hero.hp > 0) {
  11726. hero.hp = random(1, hero.hp);
  11727. }
  11728. }
  11729. }
  11730. fixBattle(battle.progress[0].attackers.heroes);
  11731. fixBattle(battle.progress[0].defenders.heroes);
  11732. return this.endBattle(battle);
  11733. }
  11734.  
  11735. /**
  11736. * Ends the fight
  11737. *
  11738. * Заканчивает бой
  11739. */
  11740. endBattle(battle) {
  11741. this.callEndBattle.name = this.actions[this.type].endBattle;
  11742. this.callEndBattle.args.result = battle.result
  11743. this.callEndBattle.args.progress = battle.progress
  11744. const calls = [this.callEndBattle];
  11745. return Send(JSON.stringify({ calls }));
  11746. }
  11747.  
  11748. /**
  11749. * Checks if you can get a buff
  11750. *
  11751. * Проверяет можно ли получить баф
  11752. */
  11753. checkBuff(nodeInfo) {
  11754. let id = null;
  11755. let value = 0;
  11756. for (const buffId in nodeInfo.buffs) {
  11757. const buff = nodeInfo.buffs[buffId];
  11758. if (buff.owner == null && buff.value > value) {
  11759. id = buffId;
  11760. value = buff.value;
  11761. }
  11762. }
  11763. nodeInfo.buffs[id].owner = 'Я';
  11764. return id;
  11765. }
  11766.  
  11767. /**
  11768. * Collects a buff
  11769. *
  11770. * Собирает баф
  11771. */
  11772. async collectBuff(buff, path) {
  11773. this.callCollectBuff.name = this.actions[this.type].collectBuff;
  11774. this.callCollectBuff.args = { buff, path };
  11775. const calls = [this.callCollectBuff];
  11776. return Send(JSON.stringify({ calls }));
  11777. }
  11778.  
  11779. getNodeInfo(nodeId) {
  11780. return this.nodes.find(node => node.id == nodeId);
  11781. }
  11782.  
  11783. errorHandling(error, data) {
  11784. //console.error(error);
  11785. let errorInfo = error.toString() + '\n';
  11786. try {
  11787. const errorStack = error.stack.split('\n');
  11788. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testAdventure");
  11789. errorInfo += errorStack.slice(0, endStack).join('\n');
  11790. } catch (e) {
  11791. errorInfo += error.stack;
  11792. }
  11793. if (data) {
  11794. errorInfo += '\nData: ' + JSON.stringify(data);
  11795. }
  11796. copyText(errorInfo);
  11797. }
  11798.  
  11799. end() {
  11800. setIsCancalBattle(true);
  11801. setProgress(this.terminatеReason, true);
  11802. console.log(this.terminatеReason);
  11803. this.resolve();
  11804. }
  11805. }
  11806.  
  11807. this.HWHClasses.executeAdventure = executeAdventure;
  11808.  
  11809. /**
  11810. * Passage of brawls
  11811. *
  11812. * Прохождение потасовок
  11813. */
  11814. function testBrawls(isAuto) {
  11815. const { executeBrawls } = HWHClasses;
  11816. return new Promise((resolve, reject) => {
  11817. const brawls = new executeBrawls(resolve, reject);
  11818. brawls.start(brawlsPack, isAuto);
  11819. });
  11820. }
  11821. /**
  11822. * Passage of brawls
  11823. *
  11824. * Прохождение потасовок
  11825. */
  11826. class executeBrawls {
  11827. callBrawlQuestGetInfo = {
  11828. name: "brawl_questGetInfo",
  11829. args: {},
  11830. ident: "brawl_questGetInfo"
  11831. }
  11832. callBrawlFindEnemies = {
  11833. name: "brawl_findEnemies",
  11834. args: {},
  11835. ident: "brawl_findEnemies"
  11836. }
  11837. callBrawlQuestFarm = {
  11838. name: "brawl_questFarm",
  11839. args: {},
  11840. ident: "brawl_questFarm"
  11841. }
  11842. callUserGetInfo = {
  11843. name: "userGetInfo",
  11844. args: {},
  11845. ident: "userGetInfo"
  11846. }
  11847. callTeamGetMaxUpgrade = {
  11848. name: "teamGetMaxUpgrade",
  11849. args: {},
  11850. ident: "teamGetMaxUpgrade"
  11851. }
  11852. callBrawlGetInfo = {
  11853. name: "brawl_getInfo",
  11854. args: {},
  11855. ident: "brawl_getInfo"
  11856. }
  11857.  
  11858. stats = {
  11859. win: 0,
  11860. loss: 0,
  11861. count: 0,
  11862. }
  11863.  
  11864. stage = {
  11865. '3': 1,
  11866. '7': 2,
  11867. '12': 3,
  11868. }
  11869.  
  11870. attempts = 0;
  11871.  
  11872. constructor(resolve, reject) {
  11873. this.resolve = resolve;
  11874. this.reject = reject;
  11875.  
  11876. const allHeroIds = Object.keys(lib.getData('hero'));
  11877. this.callTeamGetMaxUpgrade.args.units = {
  11878. hero: allHeroIds.filter((id) => +id < 1000),
  11879. titan: allHeroIds.filter((id) => +id >= 4000 && +id < 4100),
  11880. pet: allHeroIds.filter((id) => +id >= 6000 && +id < 6100),
  11881. };
  11882. }
  11883.  
  11884. async start(args, isAuto) {
  11885. this.isAuto = isAuto;
  11886. this.args = args;
  11887. setIsCancalBattle(false);
  11888. this.brawlInfo = await this.getBrawlInfo();
  11889. this.attempts = this.brawlInfo.attempts;
  11890.  
  11891. if (!this.attempts && !this.info.boughtEndlessLivesToday) {
  11892. this.end(I18N('DONT_HAVE_LIVES'));
  11893. return;
  11894. }
  11895.  
  11896. while (1) {
  11897. if (!isBrawlsAutoStart) {
  11898. this.end(I18N('BTN_CANCELED'));
  11899. return;
  11900. }
  11901.  
  11902. const maxStage = this.brawlInfo.questInfo.stage;
  11903. const stage = this.stage[maxStage];
  11904. const progress = this.brawlInfo.questInfo.progress;
  11905.  
  11906. setProgress(
  11907. `${I18N('STAGE')} ${stage}: ${progress}/${maxStage}<br>${I18N('FIGHTS')}: ${this.stats.count}<br>${I18N('WINS')}: ${
  11908. this.stats.win
  11909. }<br>${I18N('LOSSES')}: ${this.stats.loss}<br>${I18N('LIVES')}: ${this.attempts}<br>${I18N('STOP')}`,
  11910. false,
  11911. function () {
  11912. isBrawlsAutoStart = false;
  11913. }
  11914. );
  11915.  
  11916. if (this.brawlInfo.questInfo.canFarm) {
  11917. const result = await this.questFarm();
  11918. console.log(result);
  11919. }
  11920.  
  11921. if (!this.continueAttack && this.brawlInfo.questInfo.stage == 12 && this.brawlInfo.questInfo.progress == 12) {
  11922. if (
  11923. await popup.confirm(I18N('BRAWL_DAILY_TASK_COMPLETED'), [
  11924. { msg: I18N('BTN_NO'), result: true },
  11925. { msg: I18N('BTN_YES'), result: false },
  11926. ])
  11927. ) {
  11928. this.end(I18N('SUCCESS'));
  11929. return;
  11930. } else {
  11931. this.continueAttack = true;
  11932. }
  11933. }
  11934.  
  11935. if (!this.attempts && !this.info.boughtEndlessLivesToday) {
  11936. this.end(I18N('DONT_HAVE_LIVES'));
  11937. return;
  11938. }
  11939.  
  11940. const enemie = Object.values(this.brawlInfo.findEnemies).shift();
  11941.  
  11942. // Автоматический подбор пачки
  11943. if (this.isAuto) {
  11944. if (this.mandatoryId <= 4000 && this.mandatoryId != 13) {
  11945. this.end(I18N('BRAWL_AUTO_PACK_NOT_CUR_HERO'));
  11946. return;
  11947. }
  11948. if (this.mandatoryId >= 4000 && this.mandatoryId < 4100) {
  11949. this.args = await this.updateTitanPack(enemie.heroes);
  11950. } else if (this.mandatoryId < 4000 && this.mandatoryId == 13) {
  11951. this.args = await this.updateHeroesPack(enemie.heroes);
  11952. }
  11953. }
  11954.  
  11955. const result = await this.battle(enemie.userId);
  11956. this.brawlInfo = {
  11957. questInfo: result[1].result.response,
  11958. findEnemies: result[2].result.response,
  11959. };
  11960. }
  11961. }
  11962.  
  11963. async updateTitanPack(enemieHeroes) {
  11964. const packs = [
  11965. [4033, 4040, 4041, 4042, 4043],
  11966. [4032, 4040, 4041, 4042, 4043],
  11967. [4031, 4040, 4041, 4042, 4043],
  11968. [4030, 4040, 4041, 4042, 4043],
  11969. [4032, 4033, 4040, 4042, 4043],
  11970. [4030, 4033, 4041, 4042, 4043],
  11971. [4031, 4033, 4040, 4042, 4043],
  11972. [4032, 4033, 4040, 4041, 4043],
  11973. [4023, 4040, 4041, 4042, 4043],
  11974. [4030, 4033, 4040, 4042, 4043],
  11975. [4031, 4033, 4040, 4041, 4043],
  11976. [4022, 4040, 4041, 4042, 4043],
  11977. [4030, 4033, 4040, 4041, 4043],
  11978. [4021, 4040, 4041, 4042, 4043],
  11979. [4020, 4040, 4041, 4042, 4043],
  11980. [4023, 4033, 4040, 4042, 4043],
  11981. [4030, 4032, 4033, 4042, 4043],
  11982. [4023, 4033, 4040, 4041, 4043],
  11983. [4031, 4032, 4033, 4040, 4043],
  11984. [4030, 4032, 4033, 4041, 4043],
  11985. [4030, 4031, 4033, 4042, 4043],
  11986. [4013, 4040, 4041, 4042, 4043],
  11987. [4030, 4032, 4033, 4040, 4043],
  11988. [4030, 4031, 4033, 4041, 4043],
  11989. [4012, 4040, 4041, 4042, 4043],
  11990. [4030, 4031, 4033, 4040, 4043],
  11991. [4011, 4040, 4041, 4042, 4043],
  11992. [4010, 4040, 4041, 4042, 4043],
  11993. [4023, 4032, 4033, 4042, 4043],
  11994. [4022, 4032, 4033, 4042, 4043],
  11995. [4023, 4032, 4033, 4041, 4043],
  11996. [4021, 4032, 4033, 4042, 4043],
  11997. [4022, 4032, 4033, 4041, 4043],
  11998. [4023, 4030, 4033, 4042, 4043],
  11999. [4023, 4032, 4033, 4040, 4043],
  12000. [4013, 4033, 4040, 4042, 4043],
  12001. [4020, 4032, 4033, 4042, 4043],
  12002. [4021, 4032, 4033, 4041, 4043],
  12003. [4022, 4030, 4033, 4042, 4043],
  12004. [4022, 4032, 4033, 4040, 4043],
  12005. [4023, 4030, 4033, 4041, 4043],
  12006. [4023, 4031, 4033, 4040, 4043],
  12007. [4013, 4033, 4040, 4041, 4043],
  12008. [4020, 4031, 4033, 4042, 4043],
  12009. [4020, 4032, 4033, 4041, 4043],
  12010. [4021, 4030, 4033, 4042, 4043],
  12011. [4021, 4032, 4033, 4040, 4043],
  12012. [4022, 4030, 4033, 4041, 4043],
  12013. [4022, 4031, 4033, 4040, 4043],
  12014. [4023, 4030, 4033, 4040, 4043],
  12015. [4030, 4031, 4032, 4033, 4043],
  12016. [4003, 4040, 4041, 4042, 4043],
  12017. [4020, 4030, 4033, 4042, 4043],
  12018. [4020, 4031, 4033, 4041, 4043],
  12019. [4020, 4032, 4033, 4040, 4043],
  12020. [4021, 4030, 4033, 4041, 4043],
  12021. [4021, 4031, 4033, 4040, 4043],
  12022. [4022, 4030, 4033, 4040, 4043],
  12023. [4030, 4031, 4032, 4033, 4042],
  12024. [4002, 4040, 4041, 4042, 4043],
  12025. [4020, 4030, 4033, 4041, 4043],
  12026. [4020, 4031, 4033, 4040, 4043],
  12027. [4021, 4030, 4033, 4040, 4043],
  12028. [4030, 4031, 4032, 4033, 4041],
  12029. [4001, 4040, 4041, 4042, 4043],
  12030. [4030, 4031, 4032, 4033, 4040],
  12031. [4000, 4040, 4041, 4042, 4043],
  12032. [4013, 4032, 4033, 4042, 4043],
  12033. [4012, 4032, 4033, 4042, 4043],
  12034. [4013, 4032, 4033, 4041, 4043],
  12035. [4023, 4031, 4032, 4033, 4043],
  12036. [4011, 4032, 4033, 4042, 4043],
  12037. [4012, 4032, 4033, 4041, 4043],
  12038. [4013, 4030, 4033, 4042, 4043],
  12039. [4013, 4032, 4033, 4040, 4043],
  12040. [4023, 4030, 4032, 4033, 4043],
  12041. [4003, 4033, 4040, 4042, 4043],
  12042. [4013, 4023, 4040, 4042, 4043],
  12043. [4010, 4032, 4033, 4042, 4043],
  12044. [4011, 4032, 4033, 4041, 4043],
  12045. [4012, 4030, 4033, 4042, 4043],
  12046. [4012, 4032, 4033, 4040, 4043],
  12047. [4013, 4030, 4033, 4041, 4043],
  12048. [4013, 4031, 4033, 4040, 4043],
  12049. [4023, 4030, 4031, 4033, 4043],
  12050. [4003, 4033, 4040, 4041, 4043],
  12051. [4013, 4023, 4040, 4041, 4043],
  12052. [4010, 4031, 4033, 4042, 4043],
  12053. [4010, 4032, 4033, 4041, 4043],
  12054. [4011, 4030, 4033, 4042, 4043],
  12055. [4011, 4032, 4033, 4040, 4043],
  12056. [4012, 4030, 4033, 4041, 4043],
  12057. [4012, 4031, 4033, 4040, 4043],
  12058. [4013, 4030, 4033, 4040, 4043],
  12059. [4010, 4030, 4033, 4042, 4043],
  12060. [4010, 4031, 4033, 4041, 4043],
  12061. [4010, 4032, 4033, 4040, 4043],
  12062. [4011, 4030, 4033, 4041, 4043],
  12063. [4011, 4031, 4033, 4040, 4043],
  12064. [4012, 4030, 4033, 4040, 4043],
  12065. [4010, 4030, 4033, 4041, 4043],
  12066. [4010, 4031, 4033, 4040, 4043],
  12067. [4011, 4030, 4033, 4040, 4043],
  12068. [4003, 4032, 4033, 4042, 4043],
  12069. [4002, 4032, 4033, 4042, 4043],
  12070. [4003, 4032, 4033, 4041, 4043],
  12071. [4013, 4031, 4032, 4033, 4043],
  12072. [4001, 4032, 4033, 4042, 4043],
  12073. [4002, 4032, 4033, 4041, 4043],
  12074. [4003, 4030, 4033, 4042, 4043],
  12075. [4003, 4032, 4033, 4040, 4043],
  12076. [4013, 4030, 4032, 4033, 4043],
  12077. [4003, 4023, 4040, 4042, 4043],
  12078. [4000, 4032, 4033, 4042, 4043],
  12079. [4001, 4032, 4033, 4041, 4043],
  12080. [4002, 4030, 4033, 4042, 4043],
  12081. [4002, 4032, 4033, 4040, 4043],
  12082. [4003, 4030, 4033, 4041, 4043],
  12083. [4003, 4031, 4033, 4040, 4043],
  12084. [4020, 4022, 4023, 4042, 4043],
  12085. [4013, 4030, 4031, 4033, 4043],
  12086. [4003, 4023, 4040, 4041, 4043],
  12087. [4000, 4031, 4033, 4042, 4043],
  12088. [4000, 4032, 4033, 4041, 4043],
  12089. [4001, 4030, 4033, 4042, 4043],
  12090. [4001, 4032, 4033, 4040, 4043],
  12091. [4002, 4030, 4033, 4041, 4043],
  12092. [4002, 4031, 4033, 4040, 4043],
  12093. [4003, 4030, 4033, 4040, 4043],
  12094. [4021, 4022, 4023, 4040, 4043],
  12095. [4020, 4022, 4023, 4041, 4043],
  12096. [4020, 4021, 4023, 4042, 4043],
  12097. [4023, 4030, 4031, 4032, 4033],
  12098. [4000, 4030, 4033, 4042, 4043],
  12099. [4000, 4031, 4033, 4041, 4043],
  12100. [4000, 4032, 4033, 4040, 4043],
  12101. [4001, 4030, 4033, 4041, 4043],
  12102. [4001, 4031, 4033, 4040, 4043],
  12103. [4002, 4030, 4033, 4040, 4043],
  12104. [4020, 4022, 4023, 4040, 4043],
  12105. [4020, 4021, 4023, 4041, 4043],
  12106. [4022, 4030, 4031, 4032, 4033],
  12107. [4000, 4030, 4033, 4041, 4043],
  12108. [4000, 4031, 4033, 4040, 4043],
  12109. [4001, 4030, 4033, 4040, 4043],
  12110. [4020, 4021, 4023, 4040, 4043],
  12111. [4021, 4030, 4031, 4032, 4033],
  12112. [4020, 4030, 4031, 4032, 4033],
  12113. [4003, 4031, 4032, 4033, 4043],
  12114. [4020, 4022, 4023, 4033, 4043],
  12115. [4003, 4030, 4032, 4033, 4043],
  12116. [4003, 4013, 4040, 4042, 4043],
  12117. [4020, 4021, 4023, 4033, 4043],
  12118. [4003, 4030, 4031, 4033, 4043],
  12119. [4003, 4013, 4040, 4041, 4043],
  12120. [4013, 4030, 4031, 4032, 4033],
  12121. [4012, 4030, 4031, 4032, 4033],
  12122. [4011, 4030, 4031, 4032, 4033],
  12123. [4010, 4030, 4031, 4032, 4033],
  12124. [4013, 4023, 4031, 4032, 4033],
  12125. [4013, 4023, 4030, 4032, 4033],
  12126. [4020, 4022, 4023, 4032, 4033],
  12127. [4013, 4023, 4030, 4031, 4033],
  12128. [4021, 4022, 4023, 4030, 4033],
  12129. [4020, 4022, 4023, 4031, 4033],
  12130. [4020, 4021, 4023, 4032, 4033],
  12131. [4020, 4021, 4022, 4023, 4043],
  12132. [4003, 4030, 4031, 4032, 4033],
  12133. [4020, 4022, 4023, 4030, 4033],
  12134. [4020, 4021, 4023, 4031, 4033],
  12135. [4020, 4021, 4022, 4023, 4042],
  12136. [4002, 4030, 4031, 4032, 4033],
  12137. [4020, 4021, 4023, 4030, 4033],
  12138. [4020, 4021, 4022, 4023, 4041],
  12139. [4001, 4030, 4031, 4032, 4033],
  12140. [4020, 4021, 4022, 4023, 4040],
  12141. [4000, 4030, 4031, 4032, 4033],
  12142. [4003, 4023, 4031, 4032, 4033],
  12143. [4013, 4020, 4022, 4023, 4043],
  12144. [4003, 4023, 4030, 4032, 4033],
  12145. [4010, 4012, 4013, 4042, 4043],
  12146. [4013, 4020, 4021, 4023, 4043],
  12147. [4003, 4023, 4030, 4031, 4033],
  12148. [4011, 4012, 4013, 4040, 4043],
  12149. [4010, 4012, 4013, 4041, 4043],
  12150. [4010, 4011, 4013, 4042, 4043],
  12151. [4020, 4021, 4022, 4023, 4033],
  12152. [4010, 4012, 4013, 4040, 4043],
  12153. [4010, 4011, 4013, 4041, 4043],
  12154. [4020, 4021, 4022, 4023, 4032],
  12155. [4010, 4011, 4013, 4040, 4043],
  12156. [4020, 4021, 4022, 4023, 4031],
  12157. [4020, 4021, 4022, 4023, 4030],
  12158. [4003, 4013, 4031, 4032, 4033],
  12159. [4010, 4012, 4013, 4033, 4043],
  12160. [4003, 4020, 4022, 4023, 4043],
  12161. [4013, 4020, 4022, 4023, 4033],
  12162. [4003, 4013, 4030, 4032, 4033],
  12163. [4010, 4011, 4013, 4033, 4043],
  12164. [4003, 4020, 4021, 4023, 4043],
  12165. [4013, 4020, 4021, 4023, 4033],
  12166. [4003, 4013, 4030, 4031, 4033],
  12167. [4010, 4012, 4013, 4023, 4043],
  12168. [4003, 4020, 4022, 4023, 4033],
  12169. [4010, 4012, 4013, 4032, 4033],
  12170. [4010, 4011, 4013, 4023, 4043],
  12171. [4003, 4020, 4021, 4023, 4033],
  12172. [4011, 4012, 4013, 4030, 4033],
  12173. [4010, 4012, 4013, 4031, 4033],
  12174. [4010, 4011, 4013, 4032, 4033],
  12175. [4013, 4020, 4021, 4022, 4023],
  12176. [4010, 4012, 4013, 4030, 4033],
  12177. [4010, 4011, 4013, 4031, 4033],
  12178. [4012, 4020, 4021, 4022, 4023],
  12179. [4010, 4011, 4013, 4030, 4033],
  12180. [4011, 4020, 4021, 4022, 4023],
  12181. [4010, 4020, 4021, 4022, 4023],
  12182. [4010, 4012, 4013, 4023, 4033],
  12183. [4000, 4002, 4003, 4042, 4043],
  12184. [4010, 4011, 4013, 4023, 4033],
  12185. [4001, 4002, 4003, 4040, 4043],
  12186. [4000, 4002, 4003, 4041, 4043],
  12187. [4000, 4001, 4003, 4042, 4043],
  12188. [4010, 4011, 4012, 4013, 4043],
  12189. [4003, 4020, 4021, 4022, 4023],
  12190. [4000, 4002, 4003, 4040, 4043],
  12191. [4000, 4001, 4003, 4041, 4043],
  12192. [4010, 4011, 4012, 4013, 4042],
  12193. [4002, 4020, 4021, 4022, 4023],
  12194. [4000, 4001, 4003, 4040, 4043],
  12195. [4010, 4011, 4012, 4013, 4041],
  12196. [4001, 4020, 4021, 4022, 4023],
  12197. [4010, 4011, 4012, 4013, 4040],
  12198. [4000, 4020, 4021, 4022, 4023],
  12199. [4001, 4002, 4003, 4033, 4043],
  12200. [4000, 4002, 4003, 4033, 4043],
  12201. [4003, 4010, 4012, 4013, 4043],
  12202. [4003, 4013, 4020, 4022, 4023],
  12203. [4000, 4001, 4003, 4033, 4043],
  12204. [4003, 4010, 4011, 4013, 4043],
  12205. [4003, 4013, 4020, 4021, 4023],
  12206. [4010, 4011, 4012, 4013, 4033],
  12207. [4010, 4011, 4012, 4013, 4032],
  12208. [4010, 4011, 4012, 4013, 4031],
  12209. [4010, 4011, 4012, 4013, 4030],
  12210. [4001, 4002, 4003, 4023, 4043],
  12211. [4000, 4002, 4003, 4023, 4043],
  12212. [4003, 4010, 4012, 4013, 4033],
  12213. [4000, 4002, 4003, 4032, 4033],
  12214. [4000, 4001, 4003, 4023, 4043],
  12215. [4003, 4010, 4011, 4013, 4033],
  12216. [4001, 4002, 4003, 4030, 4033],
  12217. [4000, 4002, 4003, 4031, 4033],
  12218. [4000, 4001, 4003, 4032, 4033],
  12219. [4010, 4011, 4012, 4013, 4023],
  12220. [4000, 4002, 4003, 4030, 4033],
  12221. [4000, 4001, 4003, 4031, 4033],
  12222. [4010, 4011, 4012, 4013, 4022],
  12223. [4000, 4001, 4003, 4030, 4033],
  12224. [4010, 4011, 4012, 4013, 4021],
  12225. [4010, 4011, 4012, 4013, 4020],
  12226. [4001, 4002, 4003, 4013, 4043],
  12227. [4001, 4002, 4003, 4023, 4033],
  12228. [4000, 4002, 4003, 4013, 4043],
  12229. [4000, 4002, 4003, 4023, 4033],
  12230. [4003, 4010, 4012, 4013, 4023],
  12231. [4000, 4001, 4003, 4013, 4043],
  12232. [4000, 4001, 4003, 4023, 4033],
  12233. [4003, 4010, 4011, 4013, 4023],
  12234. [4001, 4002, 4003, 4013, 4033],
  12235. [4000, 4002, 4003, 4013, 4033],
  12236. [4000, 4001, 4003, 4013, 4033],
  12237. [4000, 4001, 4002, 4003, 4043],
  12238. [4003, 4010, 4011, 4012, 4013],
  12239. [4000, 4001, 4002, 4003, 4042],
  12240. [4002, 4010, 4011, 4012, 4013],
  12241. [4000, 4001, 4002, 4003, 4041],
  12242. [4001, 4010, 4011, 4012, 4013],
  12243. [4000, 4001, 4002, 4003, 4040],
  12244. [4000, 4010, 4011, 4012, 4013],
  12245. [4001, 4002, 4003, 4013, 4023],
  12246. [4000, 4002, 4003, 4013, 4023],
  12247. [4000, 4001, 4003, 4013, 4023],
  12248. [4000, 4001, 4002, 4003, 4033],
  12249. [4000, 4001, 4002, 4003, 4032],
  12250. [4000, 4001, 4002, 4003, 4031],
  12251. [4000, 4001, 4002, 4003, 4030],
  12252. [4000, 4001, 4002, 4003, 4023],
  12253. [4000, 4001, 4002, 4003, 4022],
  12254. [4000, 4001, 4002, 4003, 4021],
  12255. [4000, 4001, 4002, 4003, 4020],
  12256. [4000, 4001, 4002, 4003, 4013],
  12257. [4000, 4001, 4002, 4003, 4012],
  12258. [4000, 4001, 4002, 4003, 4011],
  12259. [4000, 4001, 4002, 4003, 4010],
  12260. ].filter((p) => p.includes(this.mandatoryId));
  12261.  
  12262. const bestPack = {
  12263. pack: packs[0],
  12264. winRate: 0,
  12265. countBattle: 0,
  12266. id: 0,
  12267. };
  12268.  
  12269. for (const id in packs) {
  12270. const pack = packs[id];
  12271. const attackers = this.maxUpgrade.filter((e) => pack.includes(e.id)).reduce((obj, e) => ({ ...obj, [e.id]: e }), {});
  12272. const battle = {
  12273. attackers,
  12274. defenders: [enemieHeroes],
  12275. type: 'brawl_titan',
  12276. };
  12277. const isRandom = this.isRandomBattle(battle);
  12278. const stat = {
  12279. count: 0,
  12280. win: 0,
  12281. winRate: 0,
  12282. };
  12283. for (let i = 1; i <= 20; i++) {
  12284. battle.seed = Math.floor(Date.now() / 1000) + Math.random() * 1000;
  12285. const result = await Calc(battle);
  12286. stat.win += result.result.win;
  12287. stat.count += 1;
  12288. stat.winRate = stat.win / stat.count;
  12289. if (!isRandom || (i >= 2 && stat.winRate < 0.65) || (i >= 10 && stat.winRate == 1)) {
  12290. break;
  12291. }
  12292. }
  12293.  
  12294. if (!isRandom && stat.win) {
  12295. return {
  12296. favor: {},
  12297. heroes: pack,
  12298. };
  12299. }
  12300. if (stat.winRate > 0.85) {
  12301. return {
  12302. favor: {},
  12303. heroes: pack,
  12304. };
  12305. }
  12306. if (stat.winRate > bestPack.winRate) {
  12307. bestPack.countBattle = stat.count;
  12308. bestPack.winRate = stat.winRate;
  12309. bestPack.pack = pack;
  12310. bestPack.id = id;
  12311. }
  12312. }
  12313.  
  12314. //console.log(bestPack.id, bestPack.pack, bestPack.winRate, bestPack.countBattle);
  12315. return {
  12316. favor: {},
  12317. heroes: bestPack.pack,
  12318. };
  12319. }
  12320.  
  12321. isRandomPack(pack) {
  12322. const ids = Object.keys(pack);
  12323. return ids.includes('4023') || ids.includes('4021');
  12324. }
  12325.  
  12326. isRandomBattle(battle) {
  12327. return this.isRandomPack(battle.attackers) || this.isRandomPack(battle.defenders[0]);
  12328. }
  12329.  
  12330. async updateHeroesPack(enemieHeroes) {
  12331. const packs = [{id:1,args:{userId:-830021,heroes:[63,13,9,48,1],pet:6006,favor:{1:6004,9:6005,13:6002,48:6e3,63:6009}},attackers:{1:{id:1,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{2:130,3:130,4:130,5:130,6022:130,8268:1,8269:1},power:198058,star:6,runes:[43750,43750,43750,43750,43750],skins:{1:60,54:60,95:60,154:60,250:60,325:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6004,type:"hero",perks:[4,1],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:3093,hp:419649,intelligence:3644,physicalAttack:11481.6,strength:17049,armor:12720,dodge:17232.28,magicPenetration:22780,magicPower:55816,magicResist:1580,modifiedSkillTier:5,skin:0,favorPetId:6004,favorPower:11064},9:{id:9,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{335:130,336:130,337:130,338:130,6027:130,8270:1,8271:1},power:195886,star:6,runes:[43750,43750,43750,43750,43750],skins:{9:60,41:60,163:60,189:60,311:60,338:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6005,type:"hero",perks:[7,2,20],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:3068,hp:227134,intelligence:19003,physicalAttack:7020.32,strength:3068,armor:19995,dodge:14644,magicPower:64780.6,magicResist:31597,modifiedSkillTier:5,skin:0,favorPetId:6005,favorPower:11064},13:{id:"13",xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{452:130,453:130,454:130,455:130,6012:130,8274:1,8275:1},power:194833,star:6,runes:[43750,43750,43750,43750,43750],skins:{13:60,38:60,148:60,199:60,240:60,335:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6002,type:"hero",perks:[7,2,21],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:2885,hp:344763,intelligence:17625,physicalAttack:50,strength:3020,armor:19060,magicPenetration:58138.6,magicPower:70100.6,magicResist:27227,modifiedSkillTier:4,skin:0,favorPetId:6002,favorPower:11064},48:{id:48,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{240:130,241:130,242:130,243:130,6002:130},power:190584,star:6,runes:[43750,43750,43750,43750,43750],skins:{103:60,165:60,217:60,296:60,326:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6e3,type:"hero",perks:[5,2],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:17308,hp:397737,intelligence:2888,physicalAttack:40298.32,physicalCritChance:12280,strength:3169,armor:12185,armorPenetration:20137.6,magicResist:24816,skin:0,favorPetId:6e3,favorPower:11064},63:{id:63,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{442:130,443:130,444:130,445:130,6041:130,8272:1,8273:1},power:193520,star:6,runes:[43750,43750,43750,43750,43750],skins:{341:60,350:60,351:60,352:1},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6009,type:"hero",perks:[6,1,21],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:17931,hp:488832,intelligence:2737,physicalAttack:54213.6,strength:2877,armor:800,armorPenetration:32477.6,magicResist:8526,physicalCritChance:9545,modifiedSkillTier:3,skin:0,favorPetId:6009,favorPower:11064},6006:{id:6006,color:10,star:6,xp:450551,level:130,slots:[25,50,50,25,50,50],skills:{6030:130,6031:130},power:181943,type:"pet",perks:[5,9],name:null,intelligence:11064,magicPenetration:47911,strength:12360}}},{id:2,args:{userId:-830049,heroes:[46,13,52,49,4],pet:6006,favor:{4:6001,13:6002,46:6006,49:6004,52:6003}},attackers:{4:{id:4,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{255:130,256:130,257:130,258:130,6007:130},power:189782,star:6,runes:[43750,43750,43750,43750,43750],skins:{4:60,35:60,92:60,161:60,236:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6001,type:"hero",perks:[4,5,2,22],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:3065,hp:482631,intelligence:3402,physicalAttack:2800,strength:17488,armor:56262.6,magicPower:51021,magicResist:36971,skin:0,favorPetId:6001,favorPower:11064},13:{id:"13",xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{452:130,453:130,454:130,455:130,6012:130,8274:1,8275:1},power:194833,star:6,runes:[43750,43750,43750,43750,43750],skins:{13:60,38:60,148:60,199:60,240:60,335:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6002,type:"hero",perks:[7,2,21],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:2885,hp:344763,intelligence:17625,physicalAttack:50,strength:3020,armor:19060,magicPenetration:58138.6,magicPower:70100.6,magicResist:27227,modifiedSkillTier:4,skin:0,favorPetId:6002,favorPower:11064},46:{id:46,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{230:130,231:130,232:130,233:130,6032:130},power:189653,star:6,runes:[43750,43750,43750,43750,43750],skins:{101:60,159:60,178:60,262:60,315:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6006,type:"hero",perks:[9,5,1,22],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2122,hp:637517,intelligence:16208,physicalAttack:50,strength:5151,armor:38507.6,magicPower:74495.6,magicResist:22237,skin:0,favorPetId:6006,favorPower:11064},49:{id:49,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{245:130,246:130,247:130,248:130,6022:130},power:193163,star:6,runes:[43750,43750,43750,43750,43750],skins:{104:60,191:60,252:60,305:60,329:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6004,type:"hero",perks:[10,1,22],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:17935,hp:250405,intelligence:2790,physicalAttack:40413.6,strength:2987,armor:11655,dodge:14844.28,magicResist:3175,physicalCritChance:14135,skin:0,favorPetId:6004,favorPower:11064},52:{id:52,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{310:130,311:130,312:130,313:130,6017:130},power:185075,star:6,runes:[43750,43750,43750,43750,43750],skins:{188:60,213:60,248:60,297:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6003,type:"hero",perks:[5,8,2,13,15,22],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:18270,hp:226207,intelligence:2620,physicalAttack:44206,strength:3260,armor:13150,armorPenetration:40301,magicPower:9957.6,magicResist:33892.6,skin:0,favorPetId:6003,favorPower:11064},6006:{id:6006,color:10,star:6,xp:450551,level:130,slots:[25,50,50,25,50,50],skills:{6030:130,6031:130},power:181943,type:"pet",perks:[5,9],name:null,intelligence:11064,magicPenetration:47911,strength:12360}}},{id:3,args:{userId:8263225,heroes:[29,63,13,48,1],pet:6006,favor:{1:6004,13:6002,29:6006,48:6e3,63:6003}},attackers:{1:{id:1,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{2:130,3:130,4:130,5:130,6022:130,8268:1,8269:1},power:198058,star:6,runes:[43750,43750,43750,43750,43750],skins:{1:60,54:60,95:60,154:60,250:60,325:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6004,type:"hero",perks:[4,1],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:3093,hp:419649,intelligence:3644,physicalAttack:11481.6,strength:17049,armor:12720,dodge:17232.28,magicPenetration:22780,magicPower:55816,magicResist:1580,modifiedSkillTier:5,skin:0,favorPetId:6004,favorPower:11064},13:{id:"13",xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{452:130,453:130,454:130,455:130,6012:130,8274:1,8275:1},power:194833,star:6,runes:[43750,43750,43750,43750,43750],skins:{13:60,38:60,148:60,199:60,240:60,335:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6002,type:"hero",perks:[7,2,21],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:2885,hp:344763,intelligence:17625,physicalAttack:50,strength:3020,armor:19060,magicPenetration:58138.6,magicPower:70100.6,magicResist:27227,modifiedSkillTier:4,skin:0,favorPetId:6002,favorPower:11064},29:{id:29,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{145:130,146:130,147:130,148:130,6032:130},power:189790,star:6,runes:[43750,43750,43750,43750,43750],skins:{29:60,72:60,88:60,147:60,242:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6006,type:"hero",perks:[9,5,2,22],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2885,hp:491431,intelligence:18331,physicalAttack:106,strength:3020,armor:37716.6,magicPower:76792.6,magicResist:31377,skin:0,favorPetId:6006,favorPower:11064},48:{id:48,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{240:130,241:130,242:130,243:130,6002:130},power:190584,star:6,runes:[43750,43750,43750,43750,43750],skins:{103:60,165:60,217:60,296:60,326:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6e3,type:"hero",perks:[5,2],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:17308,hp:397737,intelligence:2888,physicalAttack:40298.32,physicalCritChance:12280,strength:3169,armor:12185,armorPenetration:20137.6,magicResist:24816,skin:0,favorPetId:6e3,favorPower:11064},63:{id:63,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{442:130,443:130,444:130,445:130,6017:130,8272:1,8273:1},power:191031,star:6,runes:[43750,43750,43750,43750,43750],skins:{341:60,350:60,351:60,352:1},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6003,type:"hero",perks:[6,1,21],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:17931,hp:488832,intelligence:2737,physicalAttack:44256,strength:2877,armor:800,armorPenetration:22520,magicPower:9957.6,magicResist:18483.6,physicalCritChance:9545,modifiedSkillTier:3,skin:0,favorPetId:6003,favorPower:11064},6006:{id:6006,color:10,star:6,xp:450551,level:130,slots:[25,50,50,25,50,50],skills:{6030:130,6031:130},power:181943,type:"pet",perks:[5,9],name:null,intelligence:11064,magicPenetration:47911,strength:12360}}},{id:4,args:{userId:8263247,heroes:[55,13,40,51,1],pet:6006,favor:{1:6007,13:6002,40:6004,51:6006,55:6001}},attackers:{1:{id:1,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{2:130,3:130,4:130,5:130,6035:130,8268:1,8269:1},power:195170,star:6,runes:[43750,43750,43750,43750,43750],skins:{1:60,54:60,95:60,154:60,250:60,325:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6007,type:"hero",perks:[4,1],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:3093,hp:419649,intelligence:3644,physicalAttack:1524,strength:17049,armor:22677.6,dodge:14245,magicPenetration:22780,magicPower:65773.6,magicResist:1580,modifiedSkillTier:5,skin:0,favorPetId:6007,favorPower:11064},13:{id:"13",xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{452:130,453:130,454:130,455:130,6012:130,8274:1,8275:1},power:194833,star:6,runes:[43750,43750,43750,43750,43750],skins:{13:60,38:60,148:60,199:60,240:60,335:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6002,type:"hero",perks:[7,2,21],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:2885,hp:344763,intelligence:17625,physicalAttack:50,strength:3020,armor:19060,magicPenetration:58138.6,magicPower:70100.6,magicResist:27227,modifiedSkillTier:4,skin:0,favorPetId:6002,favorPower:11064},40:{id:40,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{200:130,201:130,202:130,203:130,6022:130,8244:1,8245:1},power:192541,star:6,runes:[43750,43750,43750,43750,43750],skins:{53:60,89:60,129:60,168:60,314:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6004,type:"hero",perks:[5,9,1],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:17540,hp:343191,intelligence:2805,physicalAttack:48430.6,strength:2976,armor:24410,dodge:15732.28,magicResist:17633,modifiedSkillTier:3,skin:0,favorPetId:6004,favorPower:11064},51:{id:51,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{305:130,306:130,307:130,308:130,6032:130},power:190005,star:6,runes:[43750,43750,43750,43750,43750],skins:{181:60,219:60,260:60,290:60,334:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6006,type:"hero",perks:[5,9,1,12],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2526,hp:438205,intelligence:18851,physicalAttack:50,strength:2921,armor:39442.6,magicPower:88978.6,magicResist:22960,skin:0,favorPetId:6006,favorPower:11064},55:{id:55,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{325:130,326:130,327:130,328:130,6007:130},power:190529,star:6,runes:[43750,43750,43750,43750,43750],skins:{239:60,278:60,309:60,327:60,346:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6001,type:"hero",perks:[7,1],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2631,hp:499591,intelligence:19438,physicalAttack:50,strength:3286,armor:32892.6,armorPenetration:36870,magicPower:60704,magicResist:10010,skin:0,favorPetId:6001,favorPower:11064},6006:{id:6006,color:10,star:6,xp:450551,level:130,slots:[25,50,50,25,50,50],skills:{6030:130,6031:130},power:181943,type:"pet",perks:[5,9],name:null,intelligence:11064,magicPenetration:47911,strength:12360}}},{id:5,args:{userId:8263303,heroes:[31,29,13,40,1],pet:6004,favor:{1:6001,13:6007,29:6002,31:6006,40:6004}},attackers:{1:{id:1,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{2:130,3:130,4:130,5:130,6007:130,8268:1,8269:1},power:195170,star:6,runes:[43750,43750,43750,43750,43750],skins:{1:60,54:60,95:60,154:60,250:60,325:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6001,type:"hero",perks:[4,1],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:3093,hp:519225,intelligence:3644,physicalAttack:1524,strength:17049,armor:22677.6,dodge:14245,magicPenetration:22780,magicPower:55816,magicResist:1580,modifiedSkillTier:5,skin:0,favorPetId:6001,favorPower:11064},13:{id:"13",xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{452:130,453:130,454:130,455:130,6035:130,8274:1,8275:1},power:194833,star:6,runes:[43750,43750,43750,43750,43750],skins:{13:60,38:60,148:60,199:60,240:60,335:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6007,type:"hero",perks:[7,2,21],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:2885,hp:344763,intelligence:17625,physicalAttack:50,strength:3020,armor:29017.6,magicPenetration:48181,magicPower:70100.6,magicResist:27227,modifiedSkillTier:4,skin:0,favorPetId:6007,favorPower:11064},29:{id:29,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{145:130,146:130,147:130,148:130,6012:130},power:189790,star:6,runes:[43750,43750,43750,43750,43750],skins:{29:60,72:60,88:60,147:60,242:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6002,type:"hero",perks:[9,5,2,22],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2885,hp:491431,intelligence:18331,physicalAttack:106,strength:3020,armor:27759,magicPenetration:9957.6,magicPower:76792.6,magicResist:31377,skin:0,favorPetId:6002,favorPower:11064},31:{id:31,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{155:130,156:130,157:130,158:130,6032:130},power:190305,star:6,runes:[43750,43750,43750,43750,43750],skins:{44:60,94:60,133:60,200:60,295:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6006,type:"hero",perks:[9,5,2,20],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2781,dodge:12620,hp:374484,intelligence:18945,physicalAttack:78,strength:2916,armor:28049.6,magicPower:67686.6,magicResist:15252,skin:0,favorPetId:6006,favorPower:11064},40:{id:40,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{200:130,201:130,202:130,203:130,6022:130,8244:1,8245:1},power:192541,star:6,runes:[43750,43750,43750,43750,43750],skins:{53:60,89:60,129:60,168:60,314:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6004,type:"hero",perks:[5,9,1],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:17540,hp:343191,intelligence:2805,physicalAttack:48430.6,strength:2976,armor:24410,dodge:15732.28,magicResist:17633,modifiedSkillTier:3,skin:0,favorPetId:6004,favorPower:11064},6004:{id:6004,color:10,star:6,xp:450551,level:130,slots:[25,50,50,25,50,50],skills:{6020:130,6021:130},power:181943,type:"pet",perks:[5],name:null,armorPenetration:47911,intelligence:11064,strength:12360}}},{id:6,args:{userId:8263317,heroes:[62,13,9,56,61],pet:6003,favor:{9:6004,13:6002,56:6006,61:6001,62:6003}},attackers:{9:{id:9,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{335:130,336:130,337:130,338:130,6022:130,8270:1,8271:1},power:198525,star:6,runes:[43750,43750,43750,43750,43750],skins:{9:60,41:60,163:60,189:60,311:60,338:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6004,type:"hero",perks:[7,2,20],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:3068,hp:227134,intelligence:19003,physicalAttack:10007.6,strength:3068,armor:19995,dodge:17631.28,magicPower:54823,magicResist:31597,modifiedSkillTier:5,skin:0,favorPetId:6004,favorPower:11064},13:{id:"13",xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{452:130,453:130,454:130,455:130,6012:130,8274:1,8275:1},power:194833,star:6,runes:[43750,43750,43750,43750,43750],skins:{13:60,38:60,148:60,199:60,240:60,335:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6002,type:"hero",perks:[7,2,21],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:2885,hp:344763,intelligence:17625,physicalAttack:50,strength:3020,armor:19060,magicPenetration:58138.6,magicPower:70100.6,magicResist:27227,modifiedSkillTier:4,skin:0,favorPetId:6002,favorPower:11064},56:{id:56,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{376:130,377:130,378:130,379:130,6032:130},power:184420,star:6,runes:[43750,43750,43750,43750,43750],skins:{264:60,279:60,294:60,321:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6006,type:"hero",perks:[5,7,1,21],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2791,hp:235111,intelligence:18813,physicalAttack:50,strength:2656,armor:22982.6,magicPenetration:48159,magicPower:75598.6,magicResist:13990,skin:0,favorPetId:6006,favorPower:11064},61:{id:61,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{411:130,412:130,413:130,414:130,6007:130},power:184868,star:6,runes:[43750,43750,43750,43750,43750],skins:{302:60,306:60,323:60,340:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6001,type:"hero",perks:[4,2,22],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2545,hp:466176,intelligence:3320,physicalAttack:34305,strength:18309,armor:31077.6,magicResist:24101,physicalCritChance:9009,skin:0,favorPetId:6001,favorPower:11064},62:{id:62,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{437:130,438:130,439:130,440:130,6017:130},power:173991,star:6,runes:[43750,43750,43750,43750,43750],skins:{320:60,343:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6003,type:"hero",perks:[8,7,2,22],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2530,hp:276010,intelligence:19245,physicalAttack:50,strength:3543,armor:12890,magicPenetration:23658,magicPower:80966.6,magicResist:12447.6,skin:0,favorPetId:6003,favorPower:11064},6003:{id:6003,color:10,star:6,xp:450551,level:130,slots:[25,50,50,25,50,50],skills:{6015:130,6016:130},power:181943,type:"pet",perks:[8],name:null,intelligence:11064,magicPenetration:47911,strength:12360}}},{id:7,args:{userId:8263335,heroes:[32,29,13,43,1],pet:6006,favor:{1:6004,13:6008,29:6006,32:6002,43:6007}},attackers:{1:{id:1,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{2:130,3:130,4:130,5:130,6022:130,8268:1,8269:1},power:198058,star:6,runes:[43750,43750,43750,43750,43750],skins:{1:60,54:60,95:60,154:60,250:60,325:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6004,type:"hero",perks:[4,1],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:3093,hp:419649,intelligence:3644,physicalAttack:11481.6,strength:17049,armor:12720,dodge:17232.28,magicPenetration:22780,magicPower:55816,magicResist:1580,modifiedSkillTier:5,skin:0,favorPetId:6004,favorPower:11064},13:{id:"13",xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{452:130,453:130,454:130,455:130,6038:130,8274:1,8275:1},power:194833,star:6,runes:[43750,43750,43750,43750,43750],skins:{13:60,38:60,148:60,199:60,240:60,335:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6008,type:"hero",perks:[7,2,21],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:2885,hp:344763,intelligence:17625,physicalAttack:50,strength:3020,armor:29017.6,magicPenetration:48181,magicPower:70100.6,magicResist:27227,modifiedSkillTier:4,skin:0,favorPetId:6008,favorPower:11064},29:{id:29,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{145:130,146:130,147:130,148:130,6032:130},power:189790,star:6,runes:[43750,43750,43750,43750,43750],skins:{29:60,72:60,88:60,147:60,242:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6006,type:"hero",perks:[9,5,2,22],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2885,hp:491431,intelligence:18331,physicalAttack:106,strength:3020,armor:37716.6,magicPower:76792.6,magicResist:31377,skin:0,favorPetId:6006,favorPower:11064},32:{id:32,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{160:130,161:130,162:130,163:130,6012:130},power:189956,star:6,runes:[43750,43750,43750,43750,43750],skins:{45:60,73:60,81:60,135:60,212:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6002,type:"hero",perks:[7,5,2,22],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2815,hp:551066,intelligence:18800,physicalAttack:50,strength:2810,armor:19040,magicPenetration:9957.6,magicPower:89495.6,magicResist:20805,skin:0,favorPetId:6002,favorPower:11064},43:{id:43,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{215:130,216:130,217:130,218:130,6035:130},power:189593,star:6,runes:[43750,43750,43750,43750,43750],skins:{98:60,130:60,169:60,201:60,304:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6007,type:"hero",perks:[7,9,1,21],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2447,hp:265217,intelligence:18758,physicalAttack:50,strength:2842,armor:18637.6,magicPenetration:52439,magicPower:75465.6,magicResist:22695,skin:0,favorPetId:6007,favorPower:11064},6006:{id:6006,color:10,star:6,xp:450551,level:130,slots:[25,50,50,25,50,50],skills:{6030:130,6031:130},power:181943,type:"pet",perks:[5,9],name:null,intelligence:11064,magicPenetration:47911,strength:12360}}}];
  12332.  
  12333. const bestPack = {
  12334. pack: packs[0],
  12335. countWin: 0,
  12336. }
  12337.  
  12338. for (const pack of packs) {
  12339. const attackers = pack.attackers;
  12340. const battle = {
  12341. attackers,
  12342. defenders: [enemieHeroes],
  12343. type: 'brawl',
  12344. };
  12345.  
  12346. let countWinBattles = 0;
  12347. let countTestBattle = 10;
  12348. for (let i = 0; i < countTestBattle; i++) {
  12349. battle.seed = Math.floor(Date.now() / 1000) + Math.random() * 1000;
  12350. const result = await Calc(battle);
  12351. if (result.result.win) {
  12352. countWinBattles++;
  12353. }
  12354. if (countWinBattles > 7) {
  12355. console.log(pack)
  12356. return pack.args;
  12357. }
  12358. }
  12359. if (countWinBattles > bestPack.countWin) {
  12360. bestPack.countWin = countWinBattles;
  12361. bestPack.pack = pack.args;
  12362. }
  12363. }
  12364.  
  12365. console.log(bestPack);
  12366. return bestPack.pack;
  12367. }
  12368.  
  12369. async questFarm() {
  12370. const calls = [this.callBrawlQuestFarm];
  12371. const result = await Send(JSON.stringify({ calls }));
  12372. return result.results[0].result.response;
  12373. }
  12374.  
  12375. async getBrawlInfo() {
  12376. const data = await Send(JSON.stringify({
  12377. calls: [
  12378. this.callUserGetInfo,
  12379. this.callBrawlQuestGetInfo,
  12380. this.callBrawlFindEnemies,
  12381. this.callTeamGetMaxUpgrade,
  12382. this.callBrawlGetInfo,
  12383. ]
  12384. }));
  12385.  
  12386. let attempts = data.results[0].result.response.refillable.find(n => n.id == 48);
  12387.  
  12388. const maxUpgrade = data.results[3].result.response;
  12389. const maxHero = Object.values(maxUpgrade.hero);
  12390. const maxTitan = Object.values(maxUpgrade.titan);
  12391. const maxPet = Object.values(maxUpgrade.pet);
  12392. this.maxUpgrade = [...maxHero, ...maxPet, ...maxTitan];
  12393.  
  12394. this.info = data.results[4].result.response;
  12395. this.mandatoryId = lib.data.brawl.promoHero[this.info.id].promoHero;
  12396. return {
  12397. attempts: attempts.amount,
  12398. questInfo: data.results[1].result.response,
  12399. findEnemies: data.results[2].result.response,
  12400. }
  12401. }
  12402.  
  12403. /**
  12404. * Carrying out a fight
  12405. *
  12406. * Проведение боя
  12407. */
  12408. async battle(userId) {
  12409. this.stats.count++;
  12410. const battle = await this.startBattle(userId, this.args);
  12411. const result = await Calc(battle);
  12412. console.log(result.result);
  12413. if (result.result.win) {
  12414. this.stats.win++;
  12415. } else {
  12416. this.stats.loss++;
  12417. if (!this.info.boughtEndlessLivesToday) {
  12418. this.attempts--;
  12419. }
  12420. }
  12421. return await this.endBattle(result);
  12422. // return await this.cancelBattle(result);
  12423. }
  12424.  
  12425. /**
  12426. * Starts a fight
  12427. *
  12428. * Начинает бой
  12429. */
  12430. async startBattle(userId, args) {
  12431. const call = {
  12432. name: "brawl_startBattle",
  12433. args,
  12434. ident: "brawl_startBattle"
  12435. }
  12436. call.args.userId = userId;
  12437. const calls = [call];
  12438. const result = await Send(JSON.stringify({ calls }));
  12439. return result.results[0].result.response;
  12440. }
  12441.  
  12442. cancelBattle(battle) {
  12443. const fixBattle = function (heroes) {
  12444. for (const ids in heroes) {
  12445. const hero = heroes[ids];
  12446. hero.energy = random(1, 999);
  12447. if (hero.hp > 0) {
  12448. hero.hp = random(1, hero.hp);
  12449. }
  12450. }
  12451. }
  12452. fixBattle(battle.progress[0].attackers.heroes);
  12453. fixBattle(battle.progress[0].defenders.heroes);
  12454. return this.endBattle(battle);
  12455. }
  12456.  
  12457. /**
  12458. * Ends the fight
  12459. *
  12460. * Заканчивает бой
  12461. */
  12462. async endBattle(battle) {
  12463. battle.progress[0].attackers.input = ['auto', 0, 0, 'auto', 0, 0];
  12464. const calls = [{
  12465. name: "brawl_endBattle",
  12466. args: {
  12467. result: battle.result,
  12468. progress: battle.progress
  12469. },
  12470. ident: "brawl_endBattle"
  12471. },
  12472. this.callBrawlQuestGetInfo,
  12473. this.callBrawlFindEnemies,
  12474. ];
  12475. const result = await Send(JSON.stringify({ calls }));
  12476. return result.results;
  12477. }
  12478.  
  12479. end(endReason) {
  12480. setIsCancalBattle(true);
  12481. isBrawlsAutoStart = false;
  12482. setProgress(endReason, true);
  12483. console.log(endReason);
  12484. this.resolve();
  12485. }
  12486. }
  12487.  
  12488. this.HWHClasses.executeBrawls = executeBrawls;
  12489.  
  12490. })();
  12491.  
  12492. /**
  12493. * TODO:
  12494. * Получение всех уровней при сборе всех наград (квест на титанит и на энку) +-
  12495. * Добивание на арене титанов
  12496. * Закрытие окошек по Esc +-
  12497. * Починить работу скрипта на уровне команды ниже 10 +-
  12498. * Написать номальную синхронизацию
  12499. * Запрет сбора квестов и отправки экспеиций в промежуток между локальным обновлением и глобальным обновлением дня
  12500. * Улучшение боев
  12501. */