HeroWarsHelper

Automation of actions for the game Hero Wars

  1. // ==UserScript==
  2. // @name HeroWarsHelper
  3. // @name:en HeroWarsHelper
  4. // @name:ru HeroWarsHelper
  5. // @namespace HeroWarsHelper
  6. // @version 2.345
  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: 'Adv.',
  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_ACCEPT: 'Accept',
  297. BTN_OK: 'OK',
  298. MSG_HAVE_BEEN_DEFEATED: 'You have been defeated!',
  299. BTN_AUTO: 'Auto',
  300. MSG_YOU_APPLIED: 'You applied',
  301. MSG_DAMAGE: 'damage',
  302. MSG_CANCEL_AND_STAT: 'Auto (F5) and show statistic',
  303. MSG_REPEAT_MISSION: 'Repeat the mission?',
  304. BTN_REPEAT: 'Repeat',
  305. BTN_NO: 'No',
  306. MSG_SPECIFY_QUANT: 'Specify Quantity:',
  307. BTN_OPEN: 'Open',
  308. QUESTION_COPY: 'Question copied to clipboard',
  309. ANSWER_KNOWN: 'The answer is known',
  310. ANSWER_NOT_KNOWN: 'ATTENTION THE ANSWER IS NOT KNOWN',
  311. BEING_RECALC: 'The battle is being recalculated',
  312. THIS_TIME: 'This time',
  313. VICTORY: '<span style="color:green;">VICTORY</span>',
  314. DEFEAT: '<span style="color:red;">DEFEAT</span>',
  315. CHANCE_TO_WIN: 'Chance to win <span style="color: red;">based on pre-calculation</span>',
  316. OPEN_DOLLS: 'nesting dolls recursively',
  317. SENT_QUESTION: 'Question sent',
  318. SETTINGS: 'Settings',
  319. MSG_BAN_ATTENTION: '<p style="color:red;">Using this feature may result in a ban.</p> Continue?',
  320. BTN_YES_I_AGREE: 'Yes, I understand the risks!',
  321. BTN_NO_I_AM_AGAINST: 'No, I refuse it!',
  322. VALUES: 'Values',
  323. EXPEDITIONS_SENT: 'Expeditions:<br>Collected: {countGet}<br>Sent: {countSend}',
  324. EXPEDITIONS_NOTHING: 'Nothing to collect/send',
  325. EXPEDITIONS_NOTTIME: 'It is not time for expeditions',
  326. TITANIT: 'Titanit',
  327. COMPLETED: 'completed',
  328. FLOOR: 'Floor',
  329. LEVEL: 'Level',
  330. BATTLES: 'battles',
  331. EVENT: 'Event',
  332. NOT_AVAILABLE: 'not available',
  333. NO_HEROES: 'No heroes',
  334. DAMAGE_AMOUNT: 'Damage amount',
  335. NOTHING_TO_COLLECT: 'Nothing to collect',
  336. COLLECTED: 'Collected',
  337. REWARD: 'rewards',
  338. REMAINING_ATTEMPTS: 'Remaining attempts',
  339. BATTLES_CANCELED: 'Battles canceled',
  340. MINION_RAID: 'Minion Raid',
  341. STOPPED: 'Stopped',
  342. REPETITIONS: 'Repetitions',
  343. MISSIONS_PASSED: 'Missions passed',
  344. STOP: 'stop',
  345. TOTAL_OPEN: 'Total open',
  346. OPEN: 'Open',
  347. ROUND_STAT: 'Damage statistics for ',
  348. BATTLE: 'battles',
  349. MINIMUM: 'Minimum',
  350. MAXIMUM: 'Maximum',
  351. AVERAGE: 'Average',
  352. NOT_THIS_TIME: 'Not this time',
  353. RETRY_LIMIT_EXCEEDED: 'Retry limit exceeded',
  354. SUCCESS: 'Success',
  355. RECEIVED: 'Received',
  356. LETTERS: 'letters',
  357. PORTALS: 'portals',
  358. ATTEMPTS: 'attempts',
  359. /* Quests */
  360. QUEST_10001: 'Upgrade the skills of heroes 3 times',
  361. QUEST_10002: 'Complete 10 missions',
  362. QUEST_10003: 'Complete 3 heroic missions',
  363. QUEST_10004: 'Fight 3 times in the Arena or Grand Arena',
  364. QUEST_10006: 'Use the exchange of emeralds 1 time',
  365. QUEST_10007: 'Perform 1 summon in the Soul Atrium',
  366. QUEST_10016: 'Send gifts to guildmates',
  367. QUEST_10018: 'Use an experience potion',
  368. QUEST_10019: 'Open 1 chest in the Tower',
  369. QUEST_10020: 'Open 3 chests in Outland',
  370. QUEST_10021: 'Collect 75 Titanite in the Guild Dungeon',
  371. QUEST_10021: 'Collect 150 Titanite in the Guild Dungeon',
  372. QUEST_10023: 'Upgrade Gift of the Elements by 1 level',
  373. QUEST_10024: 'Level up any artifact once',
  374. QUEST_10025: 'Start Expedition 1',
  375. QUEST_10026: 'Start 4 Expeditions',
  376. QUEST_10027: 'Win 1 battle of the Tournament of Elements',
  377. QUEST_10028: 'Level up any titan artifact',
  378. QUEST_10029: 'Unlock the Orb of Titan Artifacts',
  379. QUEST_10030: 'Upgrade any Skin of any hero 1 time',
  380. QUEST_10031: 'Win 6 battles of the Tournament of Elements',
  381. QUEST_10043: 'Start or Join an Adventure',
  382. QUEST_10044: 'Use Summon Pets 1 time',
  383. QUEST_10046: 'Open 3 chests in Adventure',
  384. QUEST_10047: 'Get 150 Guild Activity Points',
  385. NOTHING_TO_DO: 'Nothing to do',
  386. YOU_CAN_COMPLETE: 'You can complete quests',
  387. BTN_DO_IT: 'Do it',
  388. NOT_QUEST_COMPLETED: 'Not a single quest completed',
  389. COMPLETED_QUESTS: 'Completed quests',
  390. /* everything button */
  391. ASSEMBLE_OUTLAND: 'Assemble Outland',
  392. PASS_THE_TOWER: 'Pass the tower',
  393. CHECK_EXPEDITIONS: 'Check Expeditions',
  394. COMPLETE_TOE: 'Complete ToE',
  395. COMPLETE_DUNGEON: 'Complete the dungeon',
  396. COLLECT_MAIL: 'Collect mail',
  397. COLLECT_MISC: 'Collect some bullshit',
  398. COLLECT_MISC_TITLE: 'Collect Easter Eggs, Skin Gems, Keys, Arena Coins and Soul Crystal',
  399. COLLECT_QUEST_REWARDS: 'Collect quest rewards',
  400. MAKE_A_SYNC: 'Make a sync',
  401.  
  402. RUN_FUNCTION: 'Run the following functions?',
  403. BTN_GO: 'Go!',
  404. PERFORMED: 'Performed',
  405. DONE: 'Done',
  406. ERRORS_OCCURRES: 'Errors occurred while executing',
  407. COPY_ERROR: 'Copy error information to clipboard',
  408. BTN_YES: 'Yes',
  409. ALL_TASK_COMPLETED: 'All tasks completed',
  410.  
  411. UNKNOWN: 'unknown',
  412. ENTER_THE_PATH: 'Enter the path of adventure using commas or dashes',
  413. START_ADVENTURE: 'Start your adventure along this path!',
  414. INCORRECT_WAY: 'Incorrect path in adventure: {from} -> {to}',
  415. BTN_CANCELED: 'Canceled',
  416. MUST_TWO_POINTS: 'The path must contain at least 2 points.',
  417. MUST_ONLY_NUMBERS: 'The path must contain only numbers and commas',
  418. NOT_ON_AN_ADVENTURE: 'You are not on an adventure',
  419. YOU_IN_NOT_ON_THE_WAY: 'Your location is not on the way',
  420. ATTEMPTS_NOT_ENOUGH: 'Your attempts are not enough to complete the path, continue?',
  421. YES_CONTINUE: 'Yes, continue!',
  422. NOT_ENOUGH_AP: 'Not enough action points',
  423. ATTEMPTS_ARE_OVER: 'The attempts are over',
  424. MOVES: 'Moves',
  425. BUFF_GET_ERROR: 'Buff getting error',
  426. BATTLE_END_ERROR: 'Battle end error',
  427. AUTOBOT: 'Autobot',
  428. FAILED_TO_WIN_AUTO: 'Failed to win the auto battle',
  429. ERROR_OF_THE_BATTLE_COPY: 'An error occurred during the passage of the battle<br>Copy the error to the clipboard?',
  430. ERROR_DURING_THE_BATTLE: 'Error during the battle',
  431. NO_CHANCE_WIN: 'No chance of winning this fight: 0/',
  432. LOST_HEROES: 'You have won, but you have lost one or several heroes',
  433. VICTORY_IMPOSSIBLE: 'Is victory impossible, should we focus on the result?',
  434. FIND_COEFF: 'Find the coefficient greater than',
  435. BTN_PASS: 'PASS',
  436. BRAWLS: 'Brawls',
  437. BRAWLS_TITLE: 'Activates the ability to auto-brawl',
  438. START_AUTO_BRAWLS: 'Start Auto Brawls?',
  439. LOSSES: 'Losses',
  440. WINS: 'Wins',
  441. FIGHTS: 'Fights',
  442. STAGE: 'Stage',
  443. DONT_HAVE_LIVES: "You don't have lives",
  444. LIVES: 'Lives',
  445. SECRET_WEALTH_ALREADY: 'Item for Pet Potions already purchased',
  446. SECRET_WEALTH_NOT_ENOUGH: 'Not Enough Pet Potion, You Have {available}, Need {need}',
  447. SECRET_WEALTH_UPGRADE_NEW_PET: 'After purchasing the Pet Potion, it will not be enough to upgrade a new pet',
  448. SECRET_WEALTH_PURCHASED: 'Purchased {count} {name}',
  449. SECRET_WEALTH_CANCELED: 'Secret Wealth: Purchase Canceled',
  450. SECRET_WEALTH_BUY: 'You have {available} Pet Potion.<br>Do you want to buy {countBuy} {name} for {price} Pet Potion?',
  451. DAILY_BONUS: 'Daily bonus',
  452. DO_DAILY_QUESTS: 'Do daily quests',
  453. ACTIONS: 'Actions',
  454. ACTIONS_TITLE: 'Dialog box with various actions',
  455. OTHERS: 'Others',
  456. OTHERS_TITLE: 'Others',
  457. CHOOSE_ACTION: 'Choose an action',
  458. OPEN_LOOTBOX: 'You have {lootBox} boxes, should we open them?',
  459. STAMINA: 'Energy',
  460. BOXES_OVER: 'The boxes are over',
  461. NO_BOXES: 'No boxes',
  462. NO_MORE_ACTIVITY: 'No more activity for items today',
  463. EXCHANGE_ITEMS: 'Exchange items for activity points (max {maxActive})?',
  464. GET_ACTIVITY: 'Get Activity',
  465. NOT_ENOUGH_ITEMS: 'Not enough items',
  466. ACTIVITY_RECEIVED: 'Activity received',
  467. NO_PURCHASABLE_HERO_SOULS: 'No purchasable Hero Souls',
  468. PURCHASED_HERO_SOULS: 'Purchased {countHeroSouls} Hero Souls',
  469. NOT_ENOUGH_EMERALDS_540: 'Not enough emeralds, you need {imgEmerald}540 you have {imgEmerald}{currentStarMoney}',
  470. BUY_OUTLAND_BTN: 'Buy {count} chests {imgEmerald}{countEmerald}',
  471. CHESTS_NOT_AVAILABLE: 'Chests not available',
  472. OUTLAND_CHESTS_RECEIVED: 'Outland chests received',
  473. RAID_NOT_AVAILABLE: 'The raid is not available or there are no spheres',
  474. RAID_ADVENTURE: 'Raid {adventureId} adventure!',
  475. SOMETHING_WENT_WRONG: 'Something went wrong',
  476. ADVENTURE_COMPLETED: 'Adventure {adventureId} completed {times} times',
  477. CLAN_STAT_COPY: 'Clan statistics copied to clipboard',
  478. GET_ENERGY: 'Get Energy',
  479. GET_ENERGY_TITLE: 'Opens platinum boxes one at a time until you get 250 energy',
  480. ITEM_EXCHANGE: 'Item Exchange',
  481. ITEM_EXCHANGE_TITLE: 'Exchanges items for the specified amount of activity',
  482. BUY_SOULS: 'Buy souls',
  483. BUY_SOULS_TITLE: 'Buy hero souls from all available shops',
  484. BUY_OUTLAND: 'Buy Outland',
  485. BUY_OUTLAND_TITLE: 'Buy 9 chests in Outland for 540 emeralds',
  486. RAID: 'Raid',
  487. AUTO_RAID_ADVENTURE: 'Raid',
  488. AUTO_RAID_ADVENTURE_TITLE: 'Raid adventure set number of times',
  489. CLAN_STAT: 'Clan statistics',
  490. CLAN_STAT_TITLE: 'Copies clan statistics to the clipboard',
  491. BTN_AUTO_F5: 'Auto (F5)',
  492. BOSS_DAMAGE: 'Boss Damage: ',
  493. NOTHING_BUY: 'Nothing to buy',
  494. LOTS_BOUGHT: '{countBuy} lots bought for gold',
  495. BUY_FOR_GOLD: 'Buy for gold',
  496. BUY_FOR_GOLD_TITLE: 'Buy items for gold in the Town Shop and in the Pet Soul Stone Shop',
  497. REWARDS_AND_MAIL: 'Rewards and Mail',
  498. REWARDS_AND_MAIL_TITLE: 'Collects rewards and mail',
  499. COLLECT_REWARDS_AND_MAIL: 'Collected {countQuests} rewards and {countMail} letters',
  500. TIMER_ALREADY: 'Timer already started {time}',
  501. NO_ATTEMPTS_TIMER_START: 'No attempts, timer started {time}',
  502. EPIC_BRAWL_RESULT: 'Wins: {wins}/{attempts}, Coins: {coins}, Streak: {progress}/{nextStage} [Close]{end}',
  503. ATTEMPT_ENDED: '<br>Attempts ended, timer started {time}',
  504. EPIC_BRAWL: 'Cosmic Battle',
  505. EPIC_BRAWL_TITLE: 'Spends attempts in the Cosmic Battle',
  506. RELOAD_GAME: 'Reload game',
  507. TIMER: 'Timer:',
  508. SHOW_ERRORS: 'Show errors',
  509. SHOW_ERRORS_TITLE: 'Show server request errors',
  510. ERROR_MSG: 'Error: {name}<br>{description}',
  511. EVENT_AUTO_BOSS:
  512. '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?',
  513. BEST_SLOW: 'Best (slower)',
  514. FIRST_FAST: 'First (faster)',
  515. FREEZE_INTERFACE: 'Calculating... <br>The interface may freeze.',
  516. ERROR_F12: 'Error, details in the console (F12)',
  517. FAILED_FIND_WIN_PACK: 'Failed to find a winning pack',
  518. BEST_PACK: 'Best pack:',
  519. BOSS_HAS_BEEN_DEF: 'Boss {bossLvl} has been defeated.',
  520. NOT_ENOUGH_ATTEMPTS_BOSS: 'Not enough attempts to defeat boss {bossLvl}, retry?',
  521. BOSS_VICTORY_IMPOSSIBLE:
  522. '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?',
  523. BOSS_HAS_BEEN_DEF_TEXT:
  524. 'Boss {bossLvl} defeated in<br>{countBattle}/{countMaxBattle} attempts{winTimer}<br>(Please synchronize or restart the game to update the data)',
  525. MAP: 'Map: ',
  526. PLAYER_POS: 'Player positions:',
  527. NY_GIFTS: 'Gifts',
  528. NY_GIFTS_TITLE: "Open all New Year's gifts",
  529. NY_NO_GIFTS: 'No gifts not received',
  530. NY_GIFTS_COLLECTED: '{count} gifts collected',
  531. CHANGE_MAP: 'Island map',
  532. CHANGE_MAP_TITLE: 'Change island map',
  533. SELECT_ISLAND_MAP: 'Select an island map:',
  534. MAP_NUM: 'Map {num}',
  535. SECRET_WEALTH_SHOP: 'Secret Wealth {name}: ',
  536. SHOPS: 'Shops',
  537. SHOPS_DEFAULT: 'Default',
  538. SHOPS_DEFAULT_TITLE: 'Default stores',
  539. SHOPS_LIST: 'Shops {number}',
  540. SHOPS_LIST_TITLE: 'List of shops {number}',
  541. SHOPS_WARNING:
  542. '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>',
  543. MINIONS_WARNING: 'The hero packs for attacking minions are incomplete, should I continue?',
  544. FAST_SEASON: 'Fast season',
  545. FAST_SEASON_TITLE: 'Skip the map selection screen in a season',
  546. SET_NUMBER_LEVELS: 'Specify the number of levels:',
  547. POSSIBLE_IMPROVE_LEVELS: 'It is possible to improve only {count} levels.<br>Improving?',
  548. NOT_ENOUGH_RESOURECES: 'Not enough resources',
  549. IMPROVED_LEVELS: 'Improved levels: {count}',
  550. ARTIFACTS_UPGRADE: 'Artifacts Upgrade',
  551. ARTIFACTS_UPGRADE_TITLE: 'Upgrades the specified amount of the cheapest hero artifacts',
  552. SKINS_UPGRADE: 'Skins Upgrade',
  553. SKINS_UPGRADE_TITLE: 'Upgrades the specified amount of the cheapest hero skins',
  554. HINT: '<br>Hint: ',
  555. PICTURE: '<br>Picture: ',
  556. ANSWER: '<br>Answer: ',
  557. NO_HEROES_PACK: 'Fight at least one battle to save the attacking team',
  558. BRAWL_AUTO_PACK: 'Automatic selection of packs',
  559. BRAWL_AUTO_PACK_NOT_CUR_HERO: 'Automatic pack selection is not suitable for the current hero',
  560. BRAWL_DAILY_TASK_COMPLETED: 'Daily task completed, continue attacking?',
  561. CALC_STAT: 'Calculate statistics',
  562. ELEMENT_TOURNAMENT_REWARD: 'Unclaimed bonus for Elemental Tournament',
  563. BTN_TRY_FIX_IT: 'Fix it',
  564. BTN_TRY_FIX_IT_TITLE: 'Enable auto attack combat correction',
  565. DAMAGE_FIXED: 'Damage fixed from {lastDamage} to {maxDamage}!',
  566. DAMAGE_NO_FIXED: 'Failed to fix damage: {lastDamage}',
  567. LETS_FIX: "Let's fix",
  568. COUNT_FIXED: 'For {count} attempts',
  569. DEFEAT_TURN_TIMER: 'Defeat! Turn on the timer to complete the mission?',
  570. SEASON_REWARD: 'Season Rewards',
  571. SEASON_REWARD_TITLE: 'Collects available free rewards from all current seasons',
  572. SEASON_REWARD_COLLECTED: 'Collected {count} season rewards',
  573. SELL_HERO_SOULS: 'Sell ​​souls',
  574. SELL_HERO_SOULS_TITLE: 'Exchanges all absolute star hero souls for gold',
  575. GOLD_RECEIVED: 'Gold received: {gold}',
  576. OPEN_ALL_EQUIP_BOXES: 'Open all Equipment Fragment Box?',
  577. SERVER_NOT_ACCEPT: 'The server did not accept the result',
  578. INVASION_BOSS_BUFF: 'For {bossLvl} boss need buff {needBuff} you have {haveBuff}}',
  579. HERO_POWER: 'Hero Power',
  580. HERO_POWER_TITLE: 'Displays the current and maximum power of heroes',
  581. MAX_POWER_REACHED: 'Maximum power reached: {power}',
  582. CURRENT_POWER: 'Current power: {power}',
  583. POWER_TO_MAX: 'Power left to reach maximum: <span style="color:{color};">{power}</span><br>',
  584. BEST_RESULT: 'Best result: {value}%',
  585. GUILD_ISLAND_TITLE: 'Fast travel to Guild Island',
  586. TITAN_VALLEY_TITLE: 'Fast travel to Titan Valley',
  587. },
  588. ru: {
  589. /* Чекбоксы */
  590. SKIP_FIGHTS: 'Пропуск боев',
  591. SKIP_FIGHTS_TITLE: 'Пропуск боев в запределье и арене титанов, автопропуск в башне и кампании',
  592. ENDLESS_CARDS: 'Бесконечные карты',
  593. ENDLESS_CARDS_TITLE: 'Отключить трату карт предсказаний',
  594. AUTO_EXPEDITION: 'АвтоЭкспедиции',
  595. AUTO_EXPEDITION_TITLE: 'Автоотправка экспедиций',
  596. CANCEL_FIGHT: 'Отмена боя',
  597. CANCEL_FIGHT_TITLE: 'Возможность отмены ручного боя на ВГ, СМ и в Асгарде',
  598. GIFTS: 'Подарки',
  599. GIFTS_TITLE: 'Собирать подарки автоматически',
  600. BATTLE_RECALCULATION: 'Прерасчет боя',
  601. BATTLE_RECALCULATION_TITLE: 'Предварительный расчет боя',
  602. QUANTITY_CONTROL: 'Контроль кол-ва',
  603. QUANTITY_CONTROL_TITLE: 'Возможность указывать количество открываемых "лутбоксов"',
  604. REPEAT_CAMPAIGN: 'Повтор в кампании',
  605. REPEAT_CAMPAIGN_TITLE: 'Автоповтор боев в кампании',
  606. DISABLE_DONAT: 'Отключить донат',
  607. DISABLE_DONAT_TITLE: 'Убирает все предложения доната',
  608. DAILY_QUESTS: 'Квесты',
  609. DAILY_QUESTS_TITLE: 'Выполнять ежедневные квесты',
  610. AUTO_QUIZ: 'АвтоВикторина',
  611. AUTO_QUIZ_TITLE: 'Автоматическое получение правильных ответов на вопросы викторины',
  612. SECRET_WEALTH_CHECKBOX: 'Автоматическая покупка в магазине "Тайное Богатство" при заходе в игру',
  613. HIDE_SERVERS: 'Свернуть сервера',
  614. HIDE_SERVERS_TITLE: 'Скрывать неиспользуемые сервера',
  615. /* Поля ввода */
  616. HOW_MUCH_TITANITE: 'Сколько фармим титанита',
  617. COMBAT_SPEED: 'Множитель ускорения боя',
  618. NUMBER_OF_TEST: 'Количество тестовых боев',
  619. NUMBER_OF_AUTO_BATTLE: 'Количество попыток автобоев',
  620. /* Кнопки */
  621. RUN_SCRIPT: 'Запустить скрипт',
  622. TO_DO_EVERYTHING: 'Сделать все',
  623. TO_DO_EVERYTHING_TITLE: 'Выполнить несколько действий',
  624. OUTLAND: 'Запределье',
  625. OUTLAND_TITLE: 'Собрать Запределье',
  626. TITAN_ARENA: 'Турн.Стихий',
  627. TITAN_ARENA_TITLE: 'Автопрохождение Турнира Стихий',
  628. DUNGEON: 'Подземелье',
  629. DUNGEON_TITLE: 'Автопрохождение подземелья',
  630. SEER: 'Провидец',
  631. SEER_TITLE: 'Покрутить Провидца',
  632. TOWER: 'Башня',
  633. TOWER_TITLE: 'Автопрохождение башни',
  634. EXPEDITIONS: 'Экспедиции',
  635. EXPEDITIONS_TITLE: 'Отправка и сбор экспедиций',
  636. SYNC: 'Синхронизация',
  637. SYNC_TITLE: 'Частичная синхронизация данных игры без перезагрузки сатраницы',
  638. ARCHDEMON: 'Архидемон',
  639. FURNACE_OF_SOULS: 'Горнило душ',
  640. ARCHDEMON_TITLE: 'Набивает килы и собирает награду',
  641. ESTER_EGGS: 'Пасхалки',
  642. ESTER_EGGS_TITLE: 'Собрать все пасхалки или награды',
  643. REWARDS: 'Награды',
  644. REWARDS_TITLE: 'Собрать все награды за задания',
  645. MAIL: 'Почта',
  646. MAIL_TITLE: 'Собрать всю почту, кроме писем с энергией и зарядами портала',
  647. MINIONS: 'Прислужники',
  648. MINIONS_TITLE: 'Атакует прислужников сохраннеными пачками',
  649. ADVENTURE: 'Прикл',
  650. ADVENTURE_TITLE: 'Проходит приключение по указанному маршруту',
  651. STORM: 'Буря',
  652. STORM_TITLE: 'Проходит бурю по указанному маршруту',
  653. SANCTUARY: 'Святилище',
  654. SANCTUARY_TITLE: 'Быстрый переход к Святилищу',
  655. GUILD_WAR: 'Война гильдий',
  656. GUILD_WAR_TITLE: 'Быстрый переход к Войне гильдий',
  657. SECRET_WEALTH: 'Тайное богатство',
  658. SECRET_WEALTH_TITLE: 'Купить что-то в магазине "Тайное богатство"',
  659. /* Разное */
  660. BOTTOM_URLS:
  661. '<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>',
  662. GIFTS_SENT: 'Подарки отправлены!',
  663. DO_YOU_WANT: 'Вы действительно хотите это сделать?',
  664. BTN_RUN: 'Запускай',
  665. BTN_CANCEL: 'Отмена',
  666. BTN_ACCEPT: 'Принять',
  667. BTN_OK: 'Ок',
  668. MSG_HAVE_BEEN_DEFEATED: 'Вы потерпели поражение!',
  669. BTN_AUTO: 'Авто',
  670. MSG_YOU_APPLIED: 'Вы нанесли',
  671. MSG_DAMAGE: 'урона',
  672. MSG_CANCEL_AND_STAT: 'Авто (F5) и показать Статистику',
  673. MSG_REPEAT_MISSION: 'Повторить миссию?',
  674. BTN_REPEAT: 'Повторить',
  675. BTN_NO: 'Нет',
  676. MSG_SPECIFY_QUANT: 'Указать количество:',
  677. BTN_OPEN: 'Открыть',
  678. QUESTION_COPY: 'Вопрос скопирован в буфер обмена',
  679. ANSWER_KNOWN: 'Ответ известен',
  680. ANSWER_NOT_KNOWN: 'ВНИМАНИЕ ОТВЕТ НЕ ИЗВЕСТЕН',
  681. BEING_RECALC: 'Идет прерасчет боя',
  682. THIS_TIME: 'На этот раз',
  683. VICTORY: '<span style="color:green;">ПОБЕДА</span>',
  684. DEFEAT: '<span style="color:red;">ПОРАЖЕНИЕ</span>',
  685. CHANCE_TO_WIN: 'Шансы на победу <span style="color:red;">на основе прерасчета</span>',
  686. OPEN_DOLLS: 'матрешек рекурсивно',
  687. SENT_QUESTION: 'Вопрос отправлен',
  688. SETTINGS: 'Настройки',
  689. MSG_BAN_ATTENTION: '<p style="color:red;">Использование этой функции может привести к бану.</p> Продолжить?',
  690. BTN_YES_I_AGREE: 'Да, я беру на себя все риски!',
  691. BTN_NO_I_AM_AGAINST: 'Нет, я отказываюсь от этого!',
  692. VALUES: 'Значения',
  693. EXPEDITIONS_SENT: 'Экспедиции:<br>Собрано: {countGet}<br>Отправлено: {countSend}',
  694. EXPEDITIONS_NOTHING: 'Нечего собирать/отправлять',
  695. EXPEDITIONS_NOTTIME: 'Не время для экспедиций',
  696. TITANIT: 'Титанит',
  697. COMPLETED: 'завершено',
  698. FLOOR: 'Этаж',
  699. LEVEL: 'Уровень',
  700. BATTLES: 'бои',
  701. EVENT: 'Эвент',
  702. NOT_AVAILABLE: 'недоступен',
  703. NO_HEROES: 'Нет героев',
  704. DAMAGE_AMOUNT: 'Количество урона',
  705. NOTHING_TO_COLLECT: 'Нечего собирать',
  706. COLLECTED: 'Собрано',
  707. REWARD: 'наград',
  708. REMAINING_ATTEMPTS: 'Осталось попыток',
  709. BATTLES_CANCELED: 'Битв отменено',
  710. MINION_RAID: 'Рейд прислужников',
  711. STOPPED: 'Остановлено',
  712. REPETITIONS: 'Повторений',
  713. MISSIONS_PASSED: 'Миссий пройдено',
  714. STOP: 'остановить',
  715. TOTAL_OPEN: 'Всего открыто',
  716. OPEN: 'Открыто',
  717. ROUND_STAT: 'Статистика урона за',
  718. BATTLE: 'боев',
  719. MINIMUM: 'Минимальный',
  720. MAXIMUM: 'Максимальный',
  721. AVERAGE: 'Средний',
  722. NOT_THIS_TIME: 'Не в этот раз',
  723. RETRY_LIMIT_EXCEEDED: 'Превышен лимит попыток',
  724. SUCCESS: 'Успех',
  725. RECEIVED: 'Получено',
  726. LETTERS: 'писем',
  727. PORTALS: 'порталов',
  728. ATTEMPTS: 'попыток',
  729. QUEST_10001: 'Улучши умения героев 3 раза',
  730. QUEST_10002: 'Пройди 10 миссий',
  731. QUEST_10003: 'Пройди 3 героические миссии',
  732. QUEST_10004: 'Сразись 3 раза на Арене или Гранд Арене',
  733. QUEST_10006: 'Используй обмен изумрудов 1 раз',
  734. QUEST_10007: 'Соверши 1 призыв в Атриуме Душ',
  735. QUEST_10016: 'Отправь подарки согильдийцам',
  736. QUEST_10018: 'Используй зелье опыта',
  737. QUEST_10019: 'Открой 1 сундук в Башне',
  738. QUEST_10020: 'Открой 3 сундука в Запределье',
  739. QUEST_10021: 'Собери 75 Титанита в Подземелье Гильдии',
  740. QUEST_10021: 'Собери 150 Титанита в Подземелье Гильдии',
  741. QUEST_10023: 'Прокачай Дар Стихий на 1 уровень',
  742. QUEST_10024: 'Повысь уровень любого артефакта один раз',
  743. QUEST_10025: 'Начни 1 Экспедицию',
  744. QUEST_10026: 'Начни 4 Экспедиции',
  745. QUEST_10027: 'Победи в 1 бою Турнира Стихий',
  746. QUEST_10028: 'Повысь уровень любого артефакта титанов',
  747. QUEST_10029: 'Открой сферу артефактов титанов',
  748. QUEST_10030: 'Улучши облик любого героя 1 раз',
  749. QUEST_10031: 'Победи в 6 боях Турнира Стихий',
  750. QUEST_10043: 'Начни или присоеденись к Приключению',
  751. QUEST_10044: 'Воспользуйся призывом питомцев 1 раз',
  752. QUEST_10046: 'Открой 3 сундука в Приключениях',
  753. QUEST_10047: 'Набери 150 очков активности в Гильдии',
  754. NOTHING_TO_DO: 'Нечего выполнять',
  755. YOU_CAN_COMPLETE: 'Можно выполнить квесты',
  756. BTN_DO_IT: 'Выполняй',
  757. NOT_QUEST_COMPLETED: 'Ни одного квеста не выполенно',
  758. COMPLETED_QUESTS: 'Выполнено квестов',
  759. /* everything button */
  760. ASSEMBLE_OUTLAND: 'Собрать Запределье',
  761. PASS_THE_TOWER: 'Пройти башню',
  762. CHECK_EXPEDITIONS: 'Проверить экспедиции',
  763. COMPLETE_TOE: 'Пройти Турнир Стихий',
  764. COMPLETE_DUNGEON: 'Пройти подземелье',
  765. COLLECT_MAIL: 'Собрать почту',
  766. COLLECT_MISC: 'Собрать всякую херню',
  767. COLLECT_MISC_TITLE: 'Собрать пасхалки, камни облика, ключи, монеты арены и Хрусталь души',
  768. COLLECT_QUEST_REWARDS: 'Собрать награды за квесты',
  769. MAKE_A_SYNC: 'Сделать синхронизацию',
  770.  
  771. RUN_FUNCTION: 'Выполнить следующие функции?',
  772. BTN_GO: 'Погнали!',
  773. PERFORMED: 'Выполняется',
  774. DONE: 'Выполнено',
  775. ERRORS_OCCURRES: 'Призошли ошибки при выполнении',
  776. COPY_ERROR: 'Скопировать в буфер информацию об ошибке',
  777. BTN_YES: 'Да',
  778. ALL_TASK_COMPLETED: 'Все задачи выполнены',
  779.  
  780. UNKNOWN: 'Неизвестно',
  781. ENTER_THE_PATH: 'Введите путь приключения через запятые или дефисы',
  782. START_ADVENTURE: 'Начать приключение по этому пути!',
  783. INCORRECT_WAY: 'Неверный путь в приключении: {from} -> {to}',
  784. BTN_CANCELED: 'Отменено',
  785. MUST_TWO_POINTS: 'Путь должен состоять минимум из 2х точек',
  786. MUST_ONLY_NUMBERS: 'Путь должен содержать только цифры и запятые',
  787. NOT_ON_AN_ADVENTURE: 'Вы не в приключении',
  788. YOU_IN_NOT_ON_THE_WAY: 'Указанный путь должен включать точку вашего положения',
  789. ATTEMPTS_NOT_ENOUGH: 'Ваших попыток не достаточно для завершения пути, продолжить?',
  790. YES_CONTINUE: 'Да, продолжай!',
  791. NOT_ENOUGH_AP: 'Попыток не достаточно',
  792. ATTEMPTS_ARE_OVER: 'Попытки закончились',
  793. MOVES: 'Ходы',
  794. BUFF_GET_ERROR: 'Ошибка при получении бафа',
  795. BATTLE_END_ERROR: 'Ошибка завершения боя',
  796. AUTOBOT: 'АвтоБой',
  797. FAILED_TO_WIN_AUTO: 'Не удалось победить в автобою',
  798. ERROR_OF_THE_BATTLE_COPY: 'Призошли ошибка в процессе прохождения боя<br>Скопировать ошибку в буфер обмена?',
  799. ERROR_DURING_THE_BATTLE: 'Ошибка в процессе прохождения боя',
  800. NO_CHANCE_WIN: 'Нет шансов победить в этом бою: 0/',
  801. LOST_HEROES: 'Вы победили, но потеряли одного или несколько героев!',
  802. VICTORY_IMPOSSIBLE: 'Победа не возможна, бъем на результат?',
  803. FIND_COEFF: 'Поиск коэффициента больше чем',
  804. BTN_PASS: 'ПРОПУСК',
  805. BRAWLS: 'Потасовки',
  806. BRAWLS_TITLE: 'Включает возможность автопотасовок',
  807. START_AUTO_BRAWLS: 'Запустить Автопотасовки?',
  808. LOSSES: 'Поражений',
  809. WINS: 'Побед',
  810. FIGHTS: 'Боев',
  811. STAGE: 'Стадия',
  812. DONT_HAVE_LIVES: 'У Вас нет жизней',
  813. LIVES: 'Жизни',
  814. SECRET_WEALTH_ALREADY: 'товар за Зелья питомцев уже куплен',
  815. SECRET_WEALTH_NOT_ENOUGH: 'Не достаточно Зелье Питомца, у Вас {available}, нужно {need}',
  816. SECRET_WEALTH_UPGRADE_NEW_PET: 'После покупки Зелье Питомца будет не достаточно для прокачки нового питомца',
  817. SECRET_WEALTH_PURCHASED: 'Куплено {count} {name}',
  818. SECRET_WEALTH_CANCELED: 'Тайное богатство: покупка отменена',
  819. SECRET_WEALTH_BUY: 'У вас {available} Зелье Питомца.<br>Вы хотите купить {countBuy} {name} за {price} Зелье Питомца?',
  820. DAILY_BONUS: 'Ежедневная награда',
  821. DO_DAILY_QUESTS: 'Сделать ежедневные квесты',
  822. ACTIONS: 'Действия',
  823. ACTIONS_TITLE: 'Диалоговое окно с различными действиями',
  824. OTHERS: 'Разное',
  825. OTHERS_TITLE: 'Диалоговое окно с дополнительными различными действиями',
  826. CHOOSE_ACTION: 'Выберите действие',
  827. OPEN_LOOTBOX: 'У Вас {lootBox} ящиков, откываем?',
  828. STAMINA: 'Энергия',
  829. BOXES_OVER: 'Ящики закончились',
  830. NO_BOXES: 'Нет ящиков',
  831. NO_MORE_ACTIVITY: 'Больше активности за предметы сегодня не получить',
  832. EXCHANGE_ITEMS: 'Обменять предметы на очки активности (не более {maxActive})?',
  833. GET_ACTIVITY: 'Получить активность',
  834. NOT_ENOUGH_ITEMS: 'Предметов недостаточно',
  835. ACTIVITY_RECEIVED: 'Получено активности',
  836. NO_PURCHASABLE_HERO_SOULS: 'Нет доступных для покупки душ героев',
  837. PURCHASED_HERO_SOULS: 'Куплено {countHeroSouls} душ героев',
  838. NOT_ENOUGH_EMERALDS_540: 'Недостаточно изюма, нужно {imgEmerald}540 у Вас {imgEmerald}{currentStarMoney}',
  839. BUY_OUTLAND_BTN: 'Купить {count} сундуков {imgEmerald}{countEmerald}',
  840. CHESTS_NOT_AVAILABLE: 'Сундуки не доступны',
  841. OUTLAND_CHESTS_RECEIVED: 'Получено сундуков Запределья',
  842. RAID_NOT_AVAILABLE: 'Рейд не доступен или сфер нет',
  843. RAID_ADVENTURE: 'Рейд {adventureId} приключения!',
  844. SOMETHING_WENT_WRONG: 'Что-то пошло не так',
  845. ADVENTURE_COMPLETED: 'Приключение {adventureId} пройдено {times} раз',
  846. CLAN_STAT_COPY: 'Клановая статистика скопирована в буфер обмена',
  847. GET_ENERGY: 'Получить энергию',
  848. GET_ENERGY_TITLE: 'Открывает платиновые шкатулки по одной до получения 250 энергии',
  849. ITEM_EXCHANGE: 'Обмен предметов',
  850. ITEM_EXCHANGE_TITLE: 'Обменивает предметы на указанное количество активности',
  851. BUY_SOULS: 'Купить души',
  852. BUY_SOULS_TITLE: 'Купить души героев из всех доступных магазинов',
  853. BUY_OUTLAND: 'Купить Запределье',
  854. BUY_OUTLAND_TITLE: 'Купить 9 сундуков в Запределье за 540 изумрудов',
  855. RAID: 'Рейд',
  856. AUTO_RAID_ADVENTURE: 'Рейд',
  857. AUTO_RAID_ADVENTURE_TITLE: 'Рейд приключения заданное количество раз',
  858. CLAN_STAT: 'Клановая статистика',
  859. CLAN_STAT_TITLE: 'Копирует клановую статистику в буфер обмена',
  860. BTN_AUTO_F5: 'Авто (F5)',
  861. BOSS_DAMAGE: 'Урон по боссу: ',
  862. NOTHING_BUY: 'Нечего покупать',
  863. LOTS_BOUGHT: 'За золото куплено {countBuy} лотов',
  864. BUY_FOR_GOLD: 'Скупить за золото',
  865. BUY_FOR_GOLD_TITLE: 'Скупить предметы за золото в Городской лавке и в магазине Камней Душ Питомцев',
  866. REWARDS_AND_MAIL: 'Награды и почта',
  867. REWARDS_AND_MAIL_TITLE: 'Собирает награды и почту',
  868. COLLECT_REWARDS_AND_MAIL: 'Собрано {countQuests} наград и {countMail} писем',
  869. TIMER_ALREADY: 'Таймер уже запущен {time}',
  870. NO_ATTEMPTS_TIMER_START: 'Попыток нет, запущен таймер {time}',
  871. EPIC_BRAWL_RESULT: '{i} Победы: {wins}/{attempts}, Монеты: {coins}, Серия: {progress}/{nextStage} [Закрыть]{end}',
  872. ATTEMPT_ENDED: '<br>Попытки закончились, запущен таймер {time}',
  873. EPIC_BRAWL: 'Вселенская битва',
  874. EPIC_BRAWL_TITLE: 'Тратит попытки во Вселенской битве',
  875. RELOAD_GAME: 'Перезагрузить игру',
  876. TIMER: 'Таймер:',
  877. SHOW_ERRORS: 'Отображать ошибки',
  878. SHOW_ERRORS_TITLE: 'Отображать ошибки запросов к серверу',
  879. ERROR_MSG: 'Ошибка: {name}<br>{description}',
  880. EVENT_AUTO_BOSS:
  881. 'Максимальное количество боев для расчета:</br>{length} * {countTestBattle} = {maxCalcBattle}</br>Если у Вас слабый компьютер на это может потребоваться много времени, нажмите крестик для отмены.</br>Искать лучший пак из всех или первый подходящий?',
  882. BEST_SLOW: 'Лучший (медленее)',
  883. FIRST_FAST: 'Первый (быстрее)',
  884. FREEZE_INTERFACE: 'Идет расчет... <br> Интерфейс может зависнуть.',
  885. ERROR_F12: 'Ошибка, подробности в консоли (F12)',
  886. FAILED_FIND_WIN_PACK: 'Победный пак найти не удалось',
  887. BEST_PACK: 'Наилучший пак: ',
  888. BOSS_HAS_BEEN_DEF: 'Босс {bossLvl} побежден',
  889. NOT_ENOUGH_ATTEMPTS_BOSS: 'Для победы босса ${bossLvl} не хватило попыток, повторить?',
  890. BOSS_VICTORY_IMPOSSIBLE:
  891. 'По результатам прерасчета {battles} боев победу получить не удалось. Вы хотите продолжить поиск победного боя на реальных боях?',
  892. BOSS_HAS_BEEN_DEF_TEXT:
  893. 'Босс {bossLvl} побежден за<br>{countBattle}/{countMaxBattle} попыток{winTimer}<br>(Сделайте синхронизацию или перезагрузите игру для обновления данных)',
  894. MAP: 'Карта: ',
  895. PLAYER_POS: 'Позиции игроков:',
  896. NY_GIFTS: 'Подарки',
  897. NY_GIFTS_TITLE: 'Открыть все новогодние подарки',
  898. NY_NO_GIFTS: 'Нет не полученных подарков',
  899. NY_GIFTS_COLLECTED: 'Собрано {count} подарков',
  900. CHANGE_MAP: 'Карта острова',
  901. CHANGE_MAP_TITLE: 'Сменить карту острова',
  902. SELECT_ISLAND_MAP: 'Выберите карту острова:',
  903. MAP_NUM: 'Карта {num}',
  904. SECRET_WEALTH_SHOP: 'Тайное богатство {name}: ',
  905. SHOPS: 'Магазины',
  906. SHOPS_DEFAULT: 'Стандартные',
  907. SHOPS_DEFAULT_TITLE: 'Стандартные магазины',
  908. SHOPS_LIST: 'Магазины {number}',
  909. SHOPS_LIST_TITLE: 'Список магазинов {number}',
  910. SHOPS_WARNING:
  911. 'Магазины<br><span style="color:red">Если Вы купите монеты магазинов потасовок за изумруды, то их надо использовать сразу, иначе после перезагрузки игры они пропадут!</span>',
  912. MINIONS_WARNING: 'Пачки героев для атаки приспешников неполные, продолжить?',
  913. FAST_SEASON: 'Быстрый сезон',
  914. FAST_SEASON_TITLE: 'Пропуск экрана с выбором карты в сезоне',
  915. SET_NUMBER_LEVELS: 'Указать колличество уровней:',
  916. POSSIBLE_IMPROVE_LEVELS: 'Возможно улучшить только {count} уровней.<br>Улучшаем?',
  917. NOT_ENOUGH_RESOURECES: 'Не хватает ресурсов',
  918. IMPROVED_LEVELS: 'Улучшено уровней: {count}',
  919. ARTIFACTS_UPGRADE: 'Улучшение артефактов',
  920. ARTIFACTS_UPGRADE_TITLE: 'Улучшает указанное количество самых дешевых артефактов героев',
  921. SKINS_UPGRADE: 'Улучшение обликов',
  922. SKINS_UPGRADE_TITLE: 'Улучшает указанное количество самых дешевых обликов героев',
  923. HINT: '<br>Подсказка: ',
  924. PICTURE: '<br>На картинке: ',
  925. ANSWER: '<br>Ответ: ',
  926. NO_HEROES_PACK: 'Проведите хотя бы один бой для сохранения атакующей команды',
  927. BRAWL_AUTO_PACK: 'Автоподбор пачки',
  928. BRAWL_AUTO_PACK_NOT_CUR_HERO: 'Автоматический подбор пачки не подходит для текущего героя',
  929. BRAWL_DAILY_TASK_COMPLETED: 'Ежедневное задание выполнено, продолжить атаку?',
  930. CALC_STAT: 'Посчитать статистику',
  931. ELEMENT_TOURNAMENT_REWARD: 'Несобранная награда за Турнир Стихий',
  932. BTN_TRY_FIX_IT: 'Исправить',
  933. BTN_TRY_FIX_IT_TITLE: 'Включить исправление боев при автоатаке',
  934. DAMAGE_FIXED: 'Урон исправлен с {lastDamage} до {maxDamage}!',
  935. DAMAGE_NO_FIXED: 'Не удалось исправить урон: {lastDamage}',
  936. LETS_FIX: 'Исправляем',
  937. COUNT_FIXED: 'За {count} попыток',
  938. DEFEAT_TURN_TIMER: 'Поражение! Включить таймер для завершения миссии?',
  939. SEASON_REWARD: 'Награды сезонов',
  940. SEASON_REWARD_TITLE: 'Собирает доступные бесплатные награды со всех текущих сезонов',
  941. SEASON_REWARD_COLLECTED: 'Собрано {count} наград сезонов',
  942. SELL_HERO_SOULS: 'Продать души',
  943. SELL_HERO_SOULS_TITLE: 'Обменивает все души героев с абсолютной звездой на золото',
  944. GOLD_RECEIVED: 'Получено золота: {gold}',
  945. OPEN_ALL_EQUIP_BOXES: 'Открыть все ящики фрагментов экипировки?',
  946. SERVER_NOT_ACCEPT: 'Сервер не принял результат',
  947. INVASION_BOSS_BUFF: 'Для {bossLvl} босса нужен баф {needBuff} у вас {haveBuff}',
  948. HERO_POWER: 'Сила героев',
  949. HERO_POWER_TITLE: 'Отображает текущую и максимальную силу героев',
  950. MAX_POWER_REACHED: 'Максимальная достигнутая мощь: {power}',
  951. CURRENT_POWER: 'Текущая мощь: {power}',
  952. POWER_TO_MAX: 'До максимума мощи осталось: <span style="color:{color};">{power}</span><br>',
  953. BEST_RESULT: 'Лучший результат: {value}%',
  954. GUILD_ISLAND_TITLE: 'Перейти к Острову гильдии',
  955. TITAN_VALLEY_TITLE: 'Перейти к Долине титанов',
  956. },
  957. };
  958.  
  959. function getLang() {
  960. let lang = '';
  961. if (typeof NXFlashVars !== 'undefined') {
  962. lang = NXFlashVars.interface_lang
  963. }
  964. if (!lang) {
  965. lang = (navigator.language || navigator.userLanguage).substr(0, 2);
  966. }
  967. const { i18nLangData } = HWHData;
  968. if (i18nLangData[lang]) {
  969. return lang;
  970. }
  971. return 'en';
  972. }
  973.  
  974. this.I18N = function (constant, replace) {
  975. const { i18nLangData } = HWHData;
  976. const selectLang = getLang();
  977. if (constant && constant in i18nLangData[selectLang]) {
  978. const result = i18nLangData[selectLang][constant];
  979. if (replace) {
  980. return result.sprintf(replace);
  981. }
  982. return result;
  983. }
  984. console.warn('Language constant not found', {constant, replace});
  985. if (i18nLangData['en'][constant]) {
  986. const result = i18nLangData[selectLang][constant];
  987. if (replace) {
  988. return result.sprintf(replace);
  989. }
  990. return result;
  991. }
  992. return `% ${constant} %`;
  993. };
  994.  
  995. String.prototype.sprintf = String.prototype.sprintf ||
  996. function () {
  997. "use strict";
  998. var str = this.toString();
  999. if (arguments.length) {
  1000. var t = typeof arguments[0];
  1001. var key;
  1002. var args = ("string" === t || "number" === t) ?
  1003. Array.prototype.slice.call(arguments)
  1004. : arguments[0];
  1005.  
  1006. for (key in args) {
  1007. str = str.replace(new RegExp("\\{" + key + "\\}", "gi"), args[key]);
  1008. }
  1009. }
  1010.  
  1011. return str;
  1012. };
  1013.  
  1014. /**
  1015. * Checkboxes
  1016. *
  1017. * Чекбоксы
  1018. */
  1019. const checkboxes = {
  1020. passBattle: {
  1021. get label() { return I18N('SKIP_FIGHTS'); },
  1022. cbox: null,
  1023. get title() { return I18N('SKIP_FIGHTS_TITLE'); },
  1024. default: false,
  1025. },
  1026. sendExpedition: {
  1027. get label() { return I18N('AUTO_EXPEDITION'); },
  1028. cbox: null,
  1029. get title() { return I18N('AUTO_EXPEDITION_TITLE'); },
  1030. default: false,
  1031. },
  1032. cancelBattle: {
  1033. get label() { return I18N('CANCEL_FIGHT'); },
  1034. cbox: null,
  1035. get title() { return I18N('CANCEL_FIGHT_TITLE'); },
  1036. default: false,
  1037. },
  1038. preCalcBattle: {
  1039. get label() { return I18N('BATTLE_RECALCULATION'); },
  1040. cbox: null,
  1041. get title() { return I18N('BATTLE_RECALCULATION_TITLE'); },
  1042. default: false,
  1043. },
  1044. countControl: {
  1045. get label() { return I18N('QUANTITY_CONTROL'); },
  1046. cbox: null,
  1047. get title() { return I18N('QUANTITY_CONTROL_TITLE'); },
  1048. default: true,
  1049. },
  1050. repeatMission: {
  1051. get label() { return I18N('REPEAT_CAMPAIGN'); },
  1052. cbox: null,
  1053. get title() { return I18N('REPEAT_CAMPAIGN_TITLE'); },
  1054. default: false,
  1055. },
  1056. noOfferDonat: {
  1057. get label() { return I18N('DISABLE_DONAT'); },
  1058. cbox: null,
  1059. get title() { return I18N('DISABLE_DONAT_TITLE'); },
  1060. /**
  1061. * A crutch to get the field before getting the character id
  1062. *
  1063. * Костыль чтоб получать поле до получения id персонажа
  1064. */
  1065. default: (() => {
  1066. $result = false;
  1067. try {
  1068. $result = JSON.parse(localStorage[GM_info.script.name + ':noOfferDonat']);
  1069. } catch (e) {
  1070. $result = false;
  1071. }
  1072. return $result || false;
  1073. })(),
  1074. },
  1075. dailyQuests: {
  1076. get label() { return I18N('DAILY_QUESTS'); },
  1077. cbox: null,
  1078. get title() { return I18N('DAILY_QUESTS_TITLE'); },
  1079. default: false,
  1080. },
  1081. // Потасовки
  1082. autoBrawls: {
  1083. get label() { return I18N('BRAWLS'); },
  1084. cbox: null,
  1085. get title() { return I18N('BRAWLS_TITLE'); },
  1086. default: (() => {
  1087. $result = false;
  1088. try {
  1089. $result = JSON.parse(localStorage[GM_info.script.name + ':autoBrawls']);
  1090. } catch (e) {
  1091. $result = false;
  1092. }
  1093. return $result || false;
  1094. })(),
  1095. hide: false,
  1096. },
  1097. getAnswer: {
  1098. get label() { return I18N('AUTO_QUIZ'); },
  1099. cbox: null,
  1100. get title() { return I18N('AUTO_QUIZ_TITLE'); },
  1101. default: false,
  1102. hide: false,
  1103. },
  1104. tryFixIt_v2: {
  1105. get label() { return I18N('BTN_TRY_FIX_IT'); },
  1106. cbox: null,
  1107. get title() { return I18N('BTN_TRY_FIX_IT_TITLE'); },
  1108. default: false,
  1109. hide: false,
  1110. },
  1111. showErrors: {
  1112. get label() { return I18N('SHOW_ERRORS'); },
  1113. cbox: null,
  1114. get title() { return I18N('SHOW_ERRORS_TITLE'); },
  1115. default: true,
  1116. },
  1117. buyForGold: {
  1118. get label() { return I18N('BUY_FOR_GOLD'); },
  1119. cbox: null,
  1120. get title() { return I18N('BUY_FOR_GOLD_TITLE'); },
  1121. default: false,
  1122. },
  1123. hideServers: {
  1124. get label() { return I18N('HIDE_SERVERS'); },
  1125. cbox: null,
  1126. get title() { return I18N('HIDE_SERVERS_TITLE'); },
  1127. default: false,
  1128. },
  1129. fastSeason: {
  1130. get label() { return I18N('FAST_SEASON'); },
  1131. cbox: null,
  1132. get title() { return I18N('FAST_SEASON_TITLE'); },
  1133. default: false,
  1134. },
  1135. };
  1136. /**
  1137. * Get checkbox state
  1138. *
  1139. * Получить состояние чекбокса
  1140. */
  1141. function isChecked(checkBox) {
  1142. const { checkboxes } = HWHData;
  1143. if (!(checkBox in checkboxes)) {
  1144. return false;
  1145. }
  1146. return checkboxes[checkBox].cbox?.checked;
  1147. }
  1148. /**
  1149. * Input fields
  1150. *
  1151. * Поля ввода
  1152. */
  1153. const inputs = {
  1154. countTitanit: {
  1155. input: null,
  1156. get title() { return I18N('HOW_MUCH_TITANITE'); },
  1157. default: 150,
  1158. },
  1159. speedBattle: {
  1160. input: null,
  1161. get title() { return I18N('COMBAT_SPEED'); },
  1162. default: 5,
  1163. },
  1164. countTestBattle: {
  1165. input: null,
  1166. get title() { return I18N('NUMBER_OF_TEST'); },
  1167. default: 10,
  1168. },
  1169. countAutoBattle: {
  1170. input: null,
  1171. get title() { return I18N('NUMBER_OF_AUTO_BATTLE'); },
  1172. default: 10,
  1173. },
  1174. FPS: {
  1175. input: null,
  1176. title: 'FPS',
  1177. default: 60,
  1178. }
  1179. }
  1180. /**
  1181. * Checks the checkbox
  1182. *
  1183. * Поплучить данные поля ввода
  1184. */
  1185. function getInput(inputName) {
  1186. const { inputs } = HWHData;
  1187. return inputs[inputName]?.input?.value;
  1188. }
  1189.  
  1190. /**
  1191. * Control FPS
  1192. *
  1193. * Контроль FPS
  1194. */
  1195. let nextAnimationFrame = Date.now();
  1196. const oldRequestAnimationFrame = this.requestAnimationFrame;
  1197. this.requestAnimationFrame = async function (e) {
  1198. const FPS = Number(getInput('FPS')) || -1;
  1199. const now = Date.now();
  1200. const delay = nextAnimationFrame - now;
  1201. nextAnimationFrame = Math.max(now, nextAnimationFrame) + Math.min(1e3 / FPS, 1e3);
  1202. if (delay > 0) {
  1203. await new Promise((e) => setTimeout(e, delay));
  1204. }
  1205. oldRequestAnimationFrame(e);
  1206. };
  1207. /**
  1208. * Button List
  1209. *
  1210. * Список кнопочек
  1211. */
  1212. const buttons = {
  1213. getOutland: {
  1214. get name() { return I18N('TO_DO_EVERYTHING'); },
  1215. get title() { return I18N('TO_DO_EVERYTHING_TITLE'); },
  1216. onClick: testDoYourBest,
  1217. },
  1218. doActions: {
  1219. get name() { return I18N('ACTIONS'); },
  1220. get title() { return I18N('ACTIONS_TITLE'); },
  1221. onClick: async function () {
  1222. const popupButtons = [
  1223. {
  1224. msg: I18N('OUTLAND'),
  1225. result: function () {
  1226. confShow(`${I18N('RUN_SCRIPT')} ${I18N('OUTLAND')}?`, getOutland);
  1227. },
  1228. get title() { return I18N('OUTLAND_TITLE'); },
  1229. },
  1230. {
  1231. msg: I18N('TOWER'),
  1232. result: function () {
  1233. confShow(`${I18N('RUN_SCRIPT')} ${I18N('TOWER')}?`, testTower);
  1234. },
  1235. get title() { return I18N('TOWER_TITLE'); },
  1236. },
  1237. {
  1238. msg: I18N('EXPEDITIONS'),
  1239. result: function () {
  1240. confShow(`${I18N('RUN_SCRIPT')} ${I18N('EXPEDITIONS')}?`, checkExpedition);
  1241. },
  1242. get title() { return I18N('EXPEDITIONS_TITLE'); },
  1243. },
  1244. {
  1245. msg: I18N('MINIONS'),
  1246. result: function () {
  1247. confShow(`${I18N('RUN_SCRIPT')} ${I18N('MINIONS')}?`, testRaidNodes);
  1248. },
  1249. get title() { return I18N('MINIONS_TITLE'); },
  1250. },
  1251. {
  1252. msg: I18N('ESTER_EGGS'),
  1253. result: function () {
  1254. confShow(`${I18N('RUN_SCRIPT')} ${I18N('ESTER_EGGS')}?`, offerFarmAllReward);
  1255. },
  1256. get title() { return I18N('ESTER_EGGS_TITLE'); },
  1257. },
  1258. {
  1259. msg: I18N('STORM'),
  1260. result: function () {
  1261. testAdventure('solo');
  1262. },
  1263. get title() { return I18N('STORM_TITLE'); },
  1264. },
  1265. {
  1266. msg: I18N('REWARDS'),
  1267. result: function () {
  1268. confShow(`${I18N('RUN_SCRIPT')} ${I18N('REWARDS')}?`, questAllFarm);
  1269. },
  1270. get title() { return I18N('REWARDS_TITLE'); },
  1271. },
  1272. {
  1273. msg: I18N('MAIL'),
  1274. result: function () {
  1275. confShow(`${I18N('RUN_SCRIPT')} ${I18N('MAIL')}?`, mailGetAll);
  1276. },
  1277. get title() { return I18N('MAIL_TITLE'); },
  1278. },
  1279. {
  1280. msg: I18N('SEER'),
  1281. result: function () {
  1282. confShow(`${I18N('RUN_SCRIPT')} ${I18N('SEER')}?`, rollAscension);
  1283. },
  1284. get title() { return I18N('SEER_TITLE'); },
  1285. },
  1286. /*
  1287. {
  1288. msg: I18N('NY_GIFTS'),
  1289. result: getGiftNewYear,
  1290. get title() { return I18N('NY_GIFTS_TITLE'); },
  1291. },
  1292. */
  1293. ];
  1294. popupButtons.push({ result: false, isClose: true });
  1295. const answer = await popup.confirm(`${I18N('CHOOSE_ACTION')}:`, popupButtons);
  1296. if (typeof answer === 'function') {
  1297. answer();
  1298. }
  1299. },
  1300. },
  1301. doOthers: {
  1302. get name() { return I18N('OTHERS'); },
  1303. get title() { return I18N('OTHERS_TITLE'); },
  1304. onClick: async function () {
  1305. const popupButtons = [
  1306. {
  1307. msg: I18N('GET_ENERGY'),
  1308. result: farmStamina,
  1309. get title() { return I18N('GET_ENERGY_TITLE'); },
  1310. },
  1311. {
  1312. msg: I18N('ITEM_EXCHANGE'),
  1313. result: fillActive,
  1314. get title() { return I18N('ITEM_EXCHANGE_TITLE'); },
  1315. },
  1316. {
  1317. msg: I18N('BUY_SOULS'),
  1318. result: function () {
  1319. confShow(`${I18N('RUN_SCRIPT')} ${I18N('BUY_SOULS')}?`, buyHeroFragments);
  1320. },
  1321. get title() { return I18N('BUY_SOULS_TITLE'); },
  1322. },
  1323. {
  1324. msg: I18N('BUY_FOR_GOLD'),
  1325. result: function () {
  1326. confShow(`${I18N('RUN_SCRIPT')} ${I18N('BUY_FOR_GOLD')}?`, buyInStoreForGold);
  1327. },
  1328. get title() { return I18N('BUY_FOR_GOLD_TITLE'); },
  1329. },
  1330. {
  1331. msg: I18N('BUY_OUTLAND'),
  1332. result: bossOpenChestPay,
  1333. get title() { return I18N('BUY_OUTLAND_TITLE'); },
  1334. },
  1335. {
  1336. msg: I18N('CLAN_STAT'),
  1337. result: clanStatistic,
  1338. get title() { return I18N('CLAN_STAT_TITLE'); },
  1339. },
  1340. {
  1341. msg: I18N('EPIC_BRAWL'),
  1342. result: async function () {
  1343. confShow(`${I18N('RUN_SCRIPT')} ${I18N('EPIC_BRAWL')}?`, () => {
  1344. const brawl = new epicBrawl();
  1345. brawl.start();
  1346. });
  1347. },
  1348. get title() { return I18N('EPIC_BRAWL_TITLE'); },
  1349. },
  1350. {
  1351. msg: I18N('ARTIFACTS_UPGRADE'),
  1352. result: updateArtifacts,
  1353. get title() { return I18N('ARTIFACTS_UPGRADE_TITLE'); },
  1354. },
  1355. {
  1356. msg: I18N('SKINS_UPGRADE'),
  1357. result: updateSkins,
  1358. get title() { return I18N('SKINS_UPGRADE_TITLE'); },
  1359. },
  1360. {
  1361. msg: I18N('SEASON_REWARD'),
  1362. result: farmBattlePass,
  1363. get title() { return I18N('SEASON_REWARD_TITLE'); },
  1364. },
  1365. {
  1366. msg: I18N('SELL_HERO_SOULS'),
  1367. result: sellHeroSoulsForGold,
  1368. get title() { return I18N('SELL_HERO_SOULS_TITLE'); },
  1369. },
  1370. {
  1371. msg: I18N('CHANGE_MAP'),
  1372. result: async function () {
  1373. const maps = Object.values(lib.data.seasonAdventure.list)
  1374. .filter((e) => e.map.cells.length > 2)
  1375. .map((i) => ({
  1376. msg: I18N('MAP_NUM', { num: i.id }),
  1377. result: i.id,
  1378. }));
  1379.  
  1380. const result = await popup.confirm(I18N('SELECT_ISLAND_MAP'), [...maps, { result: false, isClose: true }]);
  1381. if (result) {
  1382. cheats.changeIslandMap(result);
  1383. }
  1384. },
  1385. get title() { return I18N('CHANGE_MAP_TITLE'); },
  1386. },
  1387. {
  1388. msg: I18N('HERO_POWER'),
  1389. result: async () => {
  1390. const calls = ['userGetInfo', 'heroGetAll'].map((name) => ({
  1391. name,
  1392. args: {},
  1393. ident: name,
  1394. }));
  1395. const [maxHeroSumPower, heroSumPower] = await Send({ calls }).then((e) => [
  1396. e.results[0].result.response.maxSumPower.heroes,
  1397. Object.values(e.results[1].result.response).reduce((a, e) => a + e.power, 0),
  1398. ]);
  1399. const power = maxHeroSumPower - heroSumPower;
  1400. let msg =
  1401. I18N('MAX_POWER_REACHED', { power: maxHeroSumPower.toLocaleString() }) +
  1402. '<br>' +
  1403. I18N('CURRENT_POWER', { power: heroSumPower.toLocaleString() }) +
  1404. '<br>' +
  1405. I18N('POWER_TO_MAX', { power: power.toLocaleString(), color: power >= 4000 ? 'green' : 'red' });
  1406. await popup.confirm(msg, [{ msg: I18N('BTN_OK'), result: 0 }]);
  1407. },
  1408. get title() { return I18N('HERO_POWER_TITLE'); },
  1409. },
  1410. ];
  1411. popupButtons.push({ result: false, isClose: true });
  1412. const answer = await popup.confirm(`${I18N('CHOOSE_ACTION')}:`, popupButtons);
  1413. if (typeof answer === 'function') {
  1414. answer();
  1415. }
  1416. },
  1417. },
  1418. testTitanArena: {
  1419. isCombine: true,
  1420. combineList: [
  1421. {
  1422. get name() { return I18N('TITAN_ARENA'); },
  1423. get title() { return I18N('TITAN_ARENA_TITLE'); },
  1424. onClick: function () {
  1425. confShow(`${I18N('RUN_SCRIPT')} ${I18N('TITAN_ARENA')}?`, testTitanArena);
  1426. },
  1427. },
  1428. {
  1429. name: '>>',
  1430. onClick: cheats.goTitanValley,
  1431. get title() { return I18N('TITAN_VALLEY_TITLE'); },
  1432. color: 'green',
  1433. },
  1434. ],
  1435. },
  1436. testDungeon: {
  1437. isCombine: true,
  1438. combineList: [
  1439. {
  1440. get name() { return I18N('DUNGEON'); },
  1441. onClick: function () {
  1442. confShow(`${I18N('RUN_SCRIPT')} ${I18N('DUNGEON')}?`, testDungeon);
  1443. },
  1444. get title() { return I18N('DUNGEON_TITLE'); },
  1445. },
  1446. {
  1447. name: '>>',
  1448. onClick: cheats.goClanIsland,
  1449. get title() { return I18N('GUILD_ISLAND_TITLE'); },
  1450. color: 'green',
  1451. },
  1452. ],
  1453. },
  1454. testAdventure: {
  1455. isCombine: true,
  1456. combineList: [
  1457. {
  1458. get name() { return I18N('ADVENTURE'); },
  1459. onClick: () => {
  1460. testAdventure();
  1461. },
  1462. get title() { return I18N('ADVENTURE_TITLE'); },
  1463. },
  1464. {
  1465. get name() { return I18N('AUTO_RAID_ADVENTURE'); },
  1466. onClick: autoRaidAdventure,
  1467. get title() { return I18N('AUTO_RAID_ADVENTURE_TITLE'); },
  1468. },
  1469. {
  1470. name: '>>',
  1471. onClick: cheats.goSanctuary,
  1472. get title() { return I18N('SANCTUARY_TITLE'); },
  1473. color: 'green',
  1474. },
  1475. ],
  1476. },
  1477. rewardsAndMailFarm: {
  1478. get name() { return I18N('REWARDS_AND_MAIL'); },
  1479. get title() { return I18N('REWARDS_AND_MAIL_TITLE'); },
  1480. onClick: function () {
  1481. confShow(`${I18N('RUN_SCRIPT')} ${I18N('REWARDS_AND_MAIL')}?`, rewardsAndMailFarm);
  1482. },
  1483. },
  1484. goToClanWar: {
  1485. get name() { return I18N('GUILD_WAR'); },
  1486. get title() { return I18N('GUILD_WAR_TITLE'); },
  1487. onClick: cheats.goClanWar,
  1488. dot: true,
  1489. },
  1490. dailyQuests: {
  1491. get name() { return I18N('DAILY_QUESTS'); },
  1492. get title() { return I18N('DAILY_QUESTS_TITLE'); },
  1493. onClick: async function () {
  1494. const quests = new dailyQuests(
  1495. () => {},
  1496. () => {}
  1497. );
  1498. await quests.autoInit();
  1499. quests.start();
  1500. },
  1501. },
  1502. newDay: {
  1503. get name() { return I18N('SYNC'); },
  1504. get title() { return I18N('SYNC_TITLE'); },
  1505. onClick: function () {
  1506. confShow(`${I18N('RUN_SCRIPT')} ${I18N('SYNC')}?`, cheats.refreshGame);
  1507. },
  1508. },
  1509. // Архидемон
  1510. bossRatingEventDemon: {
  1511. get name() { return I18N('ARCHDEMON'); },
  1512. get title() { return I18N('ARCHDEMON_TITLE'); },
  1513. onClick: function () {
  1514. confShow(`${I18N('RUN_SCRIPT')} ${I18N('ARCHDEMON')}?`, bossRatingEvent);
  1515. },
  1516. hide: true,
  1517. color: 'red',
  1518. },
  1519. // Горнило душ
  1520. bossRatingEventSouls: {
  1521. get name() { return I18N('FURNACE_OF_SOULS'); },
  1522. get title() { return I18N('ARCHDEMON_TITLE'); },
  1523. onClick: function () {
  1524. confShow(`${I18N('RUN_SCRIPT')} ${I18N('FURNACE_OF_SOULS')}?`, bossRatingEventSouls);
  1525. },
  1526. hide: true,
  1527. color: 'red',
  1528. },
  1529. };
  1530. /**
  1531. * Display buttons
  1532. *
  1533. * Вывести кнопочки
  1534. */
  1535. function addControlButtons() {
  1536. const { ScriptMenu } = HWHClasses;
  1537. const scriptMenu = ScriptMenu.getInst();
  1538. const { buttons } = HWHData;
  1539. for (let name in buttons) {
  1540. button = buttons[name];
  1541. if (button.hide) {
  1542. continue;
  1543. }
  1544. if (button.isCombine) {
  1545. button['button'] = scriptMenu.addCombinedButton(button.combineList);
  1546. continue;
  1547. }
  1548. button['button'] = scriptMenu.addButton(button);
  1549. }
  1550. }
  1551. /**
  1552. * Adds links
  1553. *
  1554. * Добавляет ссылки
  1555. */
  1556. function addBottomUrls() {
  1557. const { ScriptMenu } = HWHClasses;
  1558. const scriptMenu = ScriptMenu.getInst();
  1559. scriptMenu.addHeader(I18N('BOTTOM_URLS'));
  1560. }
  1561. /**
  1562. * Stop repetition of the mission
  1563. *
  1564. * Остановить повтор миссии
  1565. */
  1566. let isStopSendMission = false;
  1567. /**
  1568. * There is a repetition of the mission
  1569. *
  1570. * Идет повтор миссии
  1571. */
  1572. let isSendsMission = false;
  1573. /**
  1574. * Data on the past mission
  1575. *
  1576. * Данные о прошедшей мисии
  1577. */
  1578. let lastMissionStart = {}
  1579. /**
  1580. * Start time of the last battle in the company
  1581. *
  1582. * Время начала последнего боя в кампании
  1583. */
  1584. let lastMissionBattleStart = 0;
  1585. /**
  1586. * Data for calculating the last battle with the boss
  1587. *
  1588. * Данные для расчете последнего боя с боссом
  1589. */
  1590. let lastBossBattle = null;
  1591. /**
  1592. * Information about the last battle
  1593. *
  1594. * Данные о прошедшей битве
  1595. */
  1596. let lastBattleArg = {}
  1597. let lastBossBattleStart = null;
  1598. this.addBattleTimer = 4;
  1599. this.invasionTimer = 2500;
  1600. const invasionInfo = {
  1601. id: 225,
  1602. buff: 0,
  1603. bossLvl: 130,
  1604. };
  1605. const invasionDataPacks = {
  1606. 130: { buff: 0, pet: 6005, heroes: [9, 62, 10, 1, 66], favor: { 9: 6006 } },
  1607. 140: { buff: 0, pet: 6005, heroes: [9, 62, 10, 1, 66], favor: {} },
  1608. 150: { buff: 0, pet: 6005, heroes: [9, 62, 10, 1, 66], favor: {} },
  1609. 160: { buff: 0, pet: 6005, heroes: [64, 66, 13, 9, 4], favor: { 4: 6006, 9: 6004, 13: 6003, 64: 6005, 66: 6002 } },
  1610. 170: { buff: 0, pet: 6005, heroes: [9, 62, 10, 1, 66], favor: { 1: 6006, 9: 6005, 10: 6008, 62: 6003, 66: 6002 } },
  1611. 180: { buff: 0, pet: 6006, heroes: [62, 10, 2, 4, 66], favor: { 2: 6005, 4: 6001, 10: 6006, 62: 6003 } },
  1612. 190: { buff: 40, pet: 6005, heroes: [9, 2, 43, 45, 66], favor: { 9: 6005, 45: 6002, 66: 6006 } },
  1613. 200: { buff: 20, pet: 6005, heroes: [9, 62, 1, 48, 66], favor: { 9: 6007, 62: 6003 } },
  1614. 210: { buff: 10, pet: 6008, heroes: [9, 10, 4, 32, 66], favor: { 9: 6005, 10: 6003, 32: 6007, 66: 6006 } },
  1615. 220: { buff: 20, pet: 6004, heroes: [9, 1, 48, 43, 66], favor: { 9: 6005, 43: 6006, 48: 6000, 66: 6002 } },
  1616. 230: { buff: 45, pet: 6001, heroes: [9, 7, 40, 43, 66], favor: { 7: 6006, 9: 6005, 40: 6004, 43: 6006, 66: 6006 } },
  1617. 240: { buff: 50, pet: 6009, heroes: [9, 40, 43, 51, 66], favor: { 9: 6005, 40: 6004, 43: 6002, 66: 6007 } },
  1618. 250: { buff: 70, pet: 6005, heroes: [9, 10, 13, 43, 66], favor: { 9: 6005, 10: 6002, 13: 6002, 43: 6006, 66: 6006 } },
  1619. 260: { buff: 80, pet: 6008, heroes: [9, 40, 43, 4, 66], favor: { 4: 6001, 9: 6006, 43: 6006 } },
  1620. 270: { buff: 115, pet: 6001, heroes: [9, 13, 43, 51, 66], favor: { 9: 6006, 43: 6006, 51: 6001 } },
  1621. 280: { buff: 80, pet: 6008, heroes: [9, 13, 43, 56, 66], favor: { 9: 6004, 13: 6006, 43: 6006, 66: 6006 } },
  1622. 290: { buff: 60, pet: 6005, heroes: [9, 10, 43, 56, 66], favor: { 9: 6005, 10: 6002, 43: 6006 } },
  1623. 300: { buff: 75, pet: 6006, heroes: [9, 62, 1, 45, 66], favor: { 1: 6006, 9: 6005, 45: 6002, 66: 6007 } },
  1624. };
  1625. /**
  1626. * The name of the function of the beginning of the battle
  1627. *
  1628. * Имя функции начала боя
  1629. */
  1630. let nameFuncStartBattle = '';
  1631. /**
  1632. * The name of the function of the end of the battle
  1633. *
  1634. * Имя функции конца боя
  1635. */
  1636. let nameFuncEndBattle = '';
  1637. /**
  1638. * Data for calculating the last battle
  1639. *
  1640. * Данные для расчета последнего боя
  1641. */
  1642. let lastBattleInfo = null;
  1643. /**
  1644. * The ability to cancel the battle
  1645. *
  1646. * Возможность отменить бой
  1647. */
  1648. let isCancalBattle = true;
  1649.  
  1650. function setIsCancalBattle(value) {
  1651. isCancalBattle = value;
  1652. }
  1653.  
  1654. /**
  1655. * Certificator of the last open nesting doll
  1656. *
  1657. * Идетификатор последней открытой матрешки
  1658. */
  1659. let lastRussianDollId = null;
  1660. /**
  1661. * Cancel the training guide
  1662. *
  1663. * Отменить обучающее руководство
  1664. */
  1665. this.isCanceledTutorial = false;
  1666.  
  1667. /**
  1668. * Data from the last question of the quiz
  1669. *
  1670. * Данные последнего вопроса викторины
  1671. */
  1672. let lastQuestion = null;
  1673. /**
  1674. * Answer to the last question of the quiz
  1675. *
  1676. * Ответ на последний вопрос викторины
  1677. */
  1678. let lastAnswer = null;
  1679. /**
  1680. * Flag for opening keys or titan artifact spheres
  1681. *
  1682. * Флаг открытия ключей или сфер артефактов титанов
  1683. */
  1684. let artifactChestOpen = false;
  1685. /**
  1686. * The name of the function to open keys or orbs of titan artifacts
  1687. *
  1688. * Имя функции открытия ключей или сфер артефактов титанов
  1689. */
  1690. let artifactChestOpenCallName = '';
  1691. let correctShowOpenArtifact = 0;
  1692. /**
  1693. * Data for the last battle in the dungeon
  1694. * (Fix endless cards)
  1695. *
  1696. * Данные для последнего боя в подземке
  1697. * (Исправление бесконечных карт)
  1698. */
  1699. let lastDungeonBattleData = null;
  1700. /**
  1701. * Start time of the last battle in the dungeon
  1702. *
  1703. * Время начала последнего боя в подземелье
  1704. */
  1705. let lastDungeonBattleStart = 0;
  1706. /**
  1707. * Subscription end time
  1708. *
  1709. * Время окончания подписки
  1710. */
  1711. let subEndTime = 0;
  1712. /**
  1713. * Number of prediction cards
  1714. *
  1715. * Количество карт предсказаний
  1716. */
  1717. let countPredictionCard = 0;
  1718.  
  1719. /**
  1720. * Brawl pack
  1721. *
  1722. * Пачка для потасовок
  1723. */
  1724. let brawlsPack = null;
  1725. /**
  1726. * Autobrawl started
  1727. *
  1728. * Автопотасовка запущена
  1729. */
  1730. let isBrawlsAutoStart = false;
  1731. let clanDominationGetInfo = null;
  1732. /**
  1733. * Copies the text to the clipboard
  1734. *
  1735. * Копирует тест в буфер обмена
  1736. * @param {*} text copied text // копируемый текст
  1737. */
  1738. function copyText(text) {
  1739. let copyTextarea = document.createElement("textarea");
  1740. copyTextarea.style.opacity = "0";
  1741. copyTextarea.textContent = text;
  1742. document.body.appendChild(copyTextarea);
  1743. copyTextarea.select();
  1744. document.execCommand("copy");
  1745. document.body.removeChild(copyTextarea);
  1746. delete copyTextarea;
  1747. }
  1748. /**
  1749. * Returns the history of requests
  1750. *
  1751. * Возвращает историю запросов
  1752. */
  1753. this.getRequestHistory = function() {
  1754. return requestHistory;
  1755. }
  1756. /**
  1757. * Generates a random integer from min to max
  1758. *
  1759. * Гененирует случайное целое число от min до max
  1760. */
  1761. const random = function (min, max) {
  1762. return Math.floor(Math.random() * (max - min + 1) + min);
  1763. }
  1764. const randf = function (min, max) {
  1765. return Math.random() * (max - min + 1) + min;
  1766. };
  1767. /**
  1768. * Clearing the request history
  1769. *
  1770. * Очистка истоии запросов
  1771. */
  1772. setInterval(function () {
  1773. let now = Date.now();
  1774. for (let i in requestHistory) {
  1775. const time = +i.split('_')[0];
  1776. if (now - time > 300000) {
  1777. delete requestHistory[i];
  1778. }
  1779. }
  1780. }, 300000);
  1781. /**
  1782. * Displays the dialog box
  1783. *
  1784. * Отображает диалоговое окно
  1785. */
  1786. function confShow(message, yesCallback, noCallback) {
  1787. let buts = [];
  1788. message = message || I18N('DO_YOU_WANT');
  1789. noCallback = noCallback || (() => {});
  1790. if (yesCallback) {
  1791. buts = [
  1792. { msg: I18N('BTN_RUN'), result: true},
  1793. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true},
  1794. ]
  1795. } else {
  1796. yesCallback = () => {};
  1797. buts = [
  1798. { msg: I18N('BTN_OK'), result: true},
  1799. ];
  1800. }
  1801. popup.confirm(message, buts).then((e) => {
  1802. // dialogPromice = null;
  1803. if (e) {
  1804. yesCallback();
  1805. } else {
  1806. noCallback();
  1807. }
  1808. });
  1809. }
  1810. /**
  1811. * Override/proxy the method for creating a WS package send
  1812. *
  1813. * Переопределяем/проксируем метод создания отправки WS пакета
  1814. */
  1815. WebSocket.prototype.send = function (data) {
  1816. if (!this.isSetOnMessage) {
  1817. const oldOnmessage = this.onmessage;
  1818. this.onmessage = function (event) {
  1819. try {
  1820. const data = JSON.parse(event.data);
  1821. if (!this.isWebSocketLogin && data.result.type == "iframeEvent.login") {
  1822. this.isWebSocketLogin = true;
  1823. } else if (data.result.type == "iframeEvent.login") {
  1824. return;
  1825. }
  1826. } catch (e) { }
  1827. return oldOnmessage.apply(this, arguments);
  1828. }
  1829. this.isSetOnMessage = true;
  1830. }
  1831. original.SendWebSocket.call(this, data);
  1832. }
  1833. /**
  1834. * Overriding/Proxying the Ajax Request Creation Method
  1835. *
  1836. * Переопределяем/проксируем метод создания Ajax запроса
  1837. */
  1838. XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
  1839. this.uniqid = Date.now() + '_' + random(1000000, 10000000);
  1840. this.errorRequest = false;
  1841. if (method == 'POST' && url.includes('.nextersglobal.com/api/') && /api\/$/.test(url)) {
  1842. if (!apiUrl) {
  1843. apiUrl = url;
  1844. const socialInfo = /heroes-(.+?)\./.exec(apiUrl);
  1845. console.log(socialInfo);
  1846. }
  1847. requestHistory[this.uniqid] = {
  1848. method,
  1849. url,
  1850. error: [],
  1851. headers: {},
  1852. request: null,
  1853. response: null,
  1854. signature: [],
  1855. calls: {},
  1856. };
  1857. } else if (method == 'POST' && url.includes('error.nextersglobal.com/client/')) {
  1858. this.errorRequest = true;
  1859. }
  1860. return original.open.call(this, method, url, async, user, password);
  1861. };
  1862. /**
  1863. * Overriding/Proxying the header setting method for the AJAX request
  1864. *
  1865. * Переопределяем/проксируем метод установки заголовков для AJAX запроса
  1866. */
  1867. XMLHttpRequest.prototype.setRequestHeader = function (name, value, check) {
  1868. if (this.uniqid in requestHistory) {
  1869. requestHistory[this.uniqid].headers[name] = value;
  1870. if (name == 'X-Auth-Signature') {
  1871. requestHistory[this.uniqid].signature.push(value);
  1872. if (!check) {
  1873. return;
  1874. }
  1875. }
  1876. } else {
  1877. check = true;
  1878. }
  1879. return original.setRequestHeader.call(this, name, value);
  1880. };
  1881. /**
  1882. * Overriding/Proxying the AJAX Request Sending Method
  1883. *
  1884. * Переопределяем/проксируем метод отправки AJAX запроса
  1885. */
  1886. XMLHttpRequest.prototype.send = async function (sourceData) {
  1887. if (this.uniqid in requestHistory) {
  1888. let tempData = null;
  1889. if (getClass(sourceData) == "ArrayBuffer") {
  1890. tempData = decoder.decode(sourceData);
  1891. } else {
  1892. tempData = sourceData;
  1893. }
  1894. requestHistory[this.uniqid].request = tempData;
  1895. let headers = requestHistory[this.uniqid].headers;
  1896. lastHeaders = Object.assign({}, headers);
  1897. /**
  1898. * Game loading event
  1899. *
  1900. * Событие загрузки игры
  1901. */
  1902. if (headers["X-Request-Id"] > 2 && !isLoadGame) {
  1903. isLoadGame = true;
  1904. if (cheats.libGame) {
  1905. lib.setData(cheats.libGame);
  1906. } else {
  1907. lib.setData(await cheats.LibLoad());
  1908. }
  1909. addControls();
  1910. addControlButtons();
  1911. addBottomUrls();
  1912.  
  1913. if (isChecked('sendExpedition')) {
  1914. const isTimeBetweenDays = isTimeBetweenNewDays();
  1915. if (!isTimeBetweenDays) {
  1916. checkExpedition();
  1917. } else {
  1918. setProgress(I18N('EXPEDITIONS_NOTTIME'), true);
  1919. }
  1920. }
  1921.  
  1922. getAutoGifts();
  1923.  
  1924. cheats.activateHacks();
  1925. justInfo();
  1926. if (isChecked('dailyQuests')) {
  1927. testDailyQuests();
  1928. }
  1929.  
  1930. if (isChecked('buyForGold')) {
  1931. buyInStoreForGold();
  1932. }
  1933. }
  1934. /**
  1935. * Outgoing request data processing
  1936. *
  1937. * Обработка данных исходящего запроса
  1938. */
  1939. sourceData = await checkChangeSend.call(this, sourceData, tempData);
  1940. /**
  1941. * Handling incoming request data
  1942. *
  1943. * Обработка данных входящего запроса
  1944. */
  1945. const oldReady = this.onreadystatechange;
  1946. this.onreadystatechange = async function (e) {
  1947. if (this.errorRequest) {
  1948. return oldReady.apply(this, arguments);
  1949. }
  1950. if(this.readyState == 4 && this.status == 200) {
  1951. isTextResponse = this.responseType === "text" || this.responseType === "";
  1952. let response = isTextResponse ? this.responseText : this.response;
  1953. requestHistory[this.uniqid].response = response;
  1954. /**
  1955. * Replacing incoming request data
  1956. *
  1957. * Заменна данных входящего запроса
  1958. */
  1959. if (isTextResponse) {
  1960. await checkChangeResponse.call(this, response);
  1961. }
  1962. /**
  1963. * A function to run after the request is executed
  1964. *
  1965. * Функция запускаемая после выполения запроса
  1966. */
  1967. if (typeof this.onReadySuccess == 'function') {
  1968. setTimeout(this.onReadySuccess, 500);
  1969. }
  1970. /** Удаляем из истории запросов битвы с боссом */
  1971. if ('invasion_bossStart' in requestHistory[this.uniqid].calls) delete requestHistory[this.uniqid];
  1972. }
  1973. if (oldReady) {
  1974. try {
  1975. return oldReady.apply(this, arguments);
  1976. } catch(e) {
  1977. console.log(oldReady);
  1978. console.error('Error in oldReady:', e);
  1979. }
  1980.  
  1981. }
  1982. }
  1983. }
  1984. if (this.errorRequest) {
  1985. const oldReady = this.onreadystatechange;
  1986. this.onreadystatechange = function () {
  1987. Object.defineProperty(this, 'status', {
  1988. writable: true
  1989. });
  1990. this.status = 200;
  1991. Object.defineProperty(this, 'readyState', {
  1992. writable: true
  1993. });
  1994. this.readyState = 4;
  1995. Object.defineProperty(this, 'responseText', {
  1996. writable: true
  1997. });
  1998. this.responseText = JSON.stringify({
  1999. "result": true
  2000. });
  2001. if (typeof this.onReadySuccess == 'function') {
  2002. setTimeout(this.onReadySuccess, 200);
  2003. }
  2004. return oldReady.apply(this, arguments);
  2005. }
  2006. this.onreadystatechange();
  2007. } else {
  2008. try {
  2009. if (this.checkRequest) {
  2010. console.log(requestHistory[this.uniqid]);
  2011. debugger;
  2012. }
  2013. return original.send.call(this, sourceData);
  2014. } catch(e) {
  2015. debugger;
  2016. }
  2017. }
  2018. };
  2019. /**
  2020. * Processing and substitution of outgoing data
  2021. *
  2022. * Обработка и подмена исходящих данных
  2023. */
  2024. async function checkChangeSend(sourceData, tempData) {
  2025. try {
  2026. /**
  2027. * A function that replaces battle data with incorrect ones to cancel combatя
  2028. *
  2029. * Функция заменяющая данные боя на неверные для отмены боя
  2030. */
  2031. const fixBattle = function (heroes) {
  2032. for (const ids in heroes) {
  2033. hero = heroes[ids];
  2034. hero.energy = random(1, 999);
  2035. if (hero.hp > 0) {
  2036. hero.hp = random(1, hero.hp);
  2037. }
  2038. }
  2039. }
  2040. /**
  2041. * Dialog window 2
  2042. *
  2043. * Диалоговое окно 2
  2044. */
  2045. const showMsg = async function (msg, ansF, ansS) {
  2046. if (typeof popup == 'object') {
  2047. return await popup.confirm(msg, [
  2048. {msg: ansF, result: false},
  2049. {msg: ansS, result: true},
  2050. ]);
  2051. } else {
  2052. return !confirm(`${msg}\n ${ansF} (${I18N('BTN_OK')})\n ${ansS} (${I18N('BTN_CANCEL')})`);
  2053. }
  2054. }
  2055. /**
  2056. * Dialog window 3
  2057. *
  2058. * Диалоговое окно 3
  2059. */
  2060. const showMsgs = async function (msg, ansF, ansS, ansT) {
  2061. return await popup.confirm(msg, [
  2062. {msg: ansF, result: 0},
  2063. {msg: ansS, result: 1},
  2064. {msg: ansT, result: 2},
  2065. ]);
  2066. }
  2067.  
  2068. let changeRequest = false;
  2069. const testData = JSON.parse(tempData);
  2070. for (const call of testData.calls) {
  2071. if (!artifactChestOpen) {
  2072. requestHistory[this.uniqid].calls[call.name] = call.ident;
  2073. }
  2074. /**
  2075. * Cancellation of the battle in adventures, on VG and with minions of Asgard
  2076. * Отмена боя в приключениях, на ВГ и с прислужниками Асгарда
  2077. */
  2078. if ((call.name == 'adventure_endBattle' ||
  2079. call.name == 'adventureSolo_endBattle' ||
  2080. call.name == 'clanWarEndBattle' &&
  2081. isChecked('cancelBattle') ||
  2082. call.name == 'crossClanWar_endBattle' &&
  2083. isChecked('cancelBattle') ||
  2084. call.name == 'brawl_endBattle' ||
  2085. call.name == 'towerEndBattle' ||
  2086. call.name == 'invasion_bossEnd' ||
  2087. call.name == 'titanArenaEndBattle' ||
  2088. call.name == 'bossEndBattle' ||
  2089. call.name == 'clanRaid_endNodeBattle') &&
  2090. isCancalBattle) {
  2091. nameFuncEndBattle = call.name;
  2092.  
  2093. if (isChecked('tryFixIt_v2') &&
  2094. !call.args.result.win &&
  2095. (call.name == 'brawl_endBattle' ||
  2096. //call.name == 'crossClanWar_endBattle' ||
  2097. call.name == 'epicBrawl_endBattle' ||
  2098. //call.name == 'clanWarEndBattle' ||
  2099. call.name == 'adventure_endBattle' ||
  2100. call.name == 'titanArenaEndBattle' ||
  2101. call.name == 'bossEndBattle' ||
  2102. call.name == 'adventureSolo_endBattle') &&
  2103. lastBattleInfo) {
  2104. const noFixWin = call.name == 'clanWarEndBattle' || call.name == 'crossClanWar_endBattle';
  2105. const cloneBattle = structuredClone(lastBattleInfo);
  2106. lastBattleInfo = null;
  2107. try {
  2108. const { BestOrWinFixBattle } = HWHClasses;
  2109. const bFix = new BestOrWinFixBattle(cloneBattle);
  2110. bFix.setNoMakeWin(noFixWin);
  2111. let endTime = Date.now() + 3e4;
  2112. if (endTime < cloneBattle.endTime) {
  2113. endTime = cloneBattle.endTime;
  2114. }
  2115. const result = await bFix.start(cloneBattle.endTime, Infinity);
  2116.  
  2117. if (result.result.win) {
  2118. call.args.result = result.result;
  2119. call.args.progress = result.progress;
  2120. changeRequest = true;
  2121. } else if (result.value) {
  2122. if (
  2123. await popup.confirm(I18N('DEFEAT') + '<br>' + I18N('BEST_RESULT', { value: result.value }), [
  2124. { msg: I18N('BTN_CANCEL'), result: 0 },
  2125. { msg: I18N('BTN_ACCEPT'), result: 1 },
  2126. ])
  2127. ) {
  2128. call.args.result = result.result;
  2129. call.args.progress = result.progress;
  2130. changeRequest = true;
  2131. }
  2132. }
  2133. } catch (error) {
  2134. console.error(error);
  2135. }
  2136. }
  2137.  
  2138. if (isChecked('tryFixIt_v2') && !call.args.result.win && call.name == 'invasion_bossEnd' && lastBattleInfo) {
  2139. setProgress(I18N('LETS_FIX'), false);
  2140. const cloneBattle = structuredClone(lastBattleInfo);
  2141. const bFix = new WinFixBattle(cloneBattle);
  2142. const result = await bFix.start(cloneBattle.endTime, Infinity);
  2143. console.log(result);
  2144. let msgResult = I18N('DEFEAT');
  2145. if (result.value > 0) {
  2146. call.args.result = result.result;
  2147. call.args.progress = result.progress;
  2148. msgResult = I18N('VICTORY');
  2149. changeRequest = true;
  2150. }
  2151. setProgress(msgResult, false, hideProgress);
  2152. if (lastBattleInfo.seed === 8008) {
  2153. let timer = result.battleTimer;
  2154. const period = Math.ceil((Date.now() - lastBossBattleStart) / 1000);
  2155. console.log(timer, period);
  2156. if (period < timer) {
  2157. timer = timer - period;
  2158. await countdownTimer(timer);
  2159. lastBattleInfo.timer = true;
  2160. }
  2161. }
  2162. }
  2163.  
  2164. if (!call.args.result.win) {
  2165. let resultPopup = false;
  2166. if (call.name == 'adventure_endBattle' ||
  2167. //call.name == 'invasion_bossEnd' ||
  2168. call.name == 'bossEndBattle' ||
  2169. call.name == 'adventureSolo_endBattle') {
  2170. resultPopup = await showMsgs(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_CANCEL'), I18N('BTN_AUTO'));
  2171. } else if (call.name == 'clanWarEndBattle' ||
  2172. call.name == 'crossClanWar_endBattle') {
  2173. resultPopup = await showMsg(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_AUTO_F5'));
  2174. } else if (call.name !== 'epicBrawl_endBattle' && call.name !== 'titanArenaEndBattle') {
  2175. resultPopup = await showMsg(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_CANCEL'));
  2176. }
  2177. if (resultPopup) {
  2178. if (call.name == 'invasion_bossEnd') {
  2179. this.errorRequest = true;
  2180. }
  2181. fixBattle(call.args.progress[0].attackers.heroes);
  2182. fixBattle(call.args.progress[0].defenders.heroes);
  2183. changeRequest = true;
  2184. if (resultPopup > 1) {
  2185. this.onReadySuccess = testAutoBattle;
  2186. // setTimeout(bossBattle, 1000);
  2187. }
  2188. this.checkRequest = true;
  2189. console.log(requestHistory[this.uniqid]);
  2190. }
  2191. } else if (call.args.result.stars < 3 && call.name == 'towerEndBattle') {
  2192. resultPopup = await showMsg(I18N('LOST_HEROES'), I18N('BTN_OK'), I18N('BTN_CANCEL'), I18N('BTN_AUTO'));
  2193. if (resultPopup) {
  2194. fixBattle(call.args.progress[0].attackers.heroes);
  2195. fixBattle(call.args.progress[0].defenders.heroes);
  2196. changeRequest = true;
  2197. if (resultPopup > 1) {
  2198. this.onReadySuccess = testAutoBattle;
  2199. }
  2200. }
  2201. }
  2202. // Потасовки
  2203. if (isChecked('autoBrawls') && !isBrawlsAutoStart && call.name == 'brawl_endBattle') {}
  2204. }
  2205. /**
  2206. * Save pack for Brawls
  2207. *
  2208. * Сохраняем пачку для потасовок
  2209. */
  2210. if (isChecked('autoBrawls') && !isBrawlsAutoStart && call.name == 'brawl_startBattle') {
  2211. console.log(JSON.stringify(call.args));
  2212. brawlsPack = call.args;
  2213. if (
  2214. await popup.confirm(
  2215. I18N('START_AUTO_BRAWLS'),
  2216. [
  2217. { msg: I18N('BTN_NO'), result: false },
  2218. { msg: I18N('BTN_YES'), result: true },
  2219. ],
  2220. [
  2221. {
  2222. name: 'isAuto',
  2223. get label() { return I18N('BRAWL_AUTO_PACK'); },
  2224. checked: false,
  2225. },
  2226. ]
  2227. )
  2228. ) {
  2229. isBrawlsAutoStart = true;
  2230. const isAuto = popup.getCheckBoxes().find((e) => e.name === 'isAuto');
  2231. this.errorRequest = true;
  2232. testBrawls(isAuto.checked);
  2233. }
  2234. }
  2235. /**
  2236. * Canceled fight in Asgard
  2237. * Отмена боя в Асгарде
  2238. */
  2239. if (call.name == 'clanRaid_endBossBattle' && isChecked('cancelBattle')) {
  2240. const bossDamage = call.args.progress[0].defenders.heroes[1].extra;
  2241. let maxDamage = bossDamage.damageTaken + bossDamage.damageTakenNextLevel;
  2242. const lastDamage = maxDamage;
  2243.  
  2244. const testFunc = [];
  2245.  
  2246. if (testFuntions.masterFix) {
  2247. testFunc.push({ msg: 'masterFix', isInput: true, default: 100 });
  2248. }
  2249.  
  2250. const resultPopup = await popup.confirm(
  2251. `${I18N('MSG_YOU_APPLIED')} ${lastDamage.toLocaleString()} ${I18N('MSG_DAMAGE')}.`,
  2252. [
  2253. { msg: I18N('BTN_OK'), result: false },
  2254. { msg: I18N('BTN_AUTO_F5'), result: 1 },
  2255. { msg: I18N('BTN_TRY_FIX_IT'), result: 2 },
  2256. ...testFunc,
  2257. ],
  2258. [
  2259. {
  2260. name: 'isStat',
  2261. get label() { return I18N('CALC_STAT'); },
  2262. checked: false,
  2263. },
  2264. ]
  2265. );
  2266. if (resultPopup) {
  2267. if (resultPopup == 2) {
  2268. setProgress(I18N('LETS_FIX'), false);
  2269. await new Promise((e) => setTimeout(e, 0));
  2270. const cloneBattle = structuredClone(lastBossBattle);
  2271. const endTime = cloneBattle.endTime - 15e3;
  2272. console.log('fixBossBattleStart');
  2273.  
  2274. const { BossFixBattle } = HWHClasses;
  2275. const bFix = new BossFixBattle(cloneBattle);
  2276. const result = await bFix.start(endTime, Infinity);
  2277. console.log(result);
  2278.  
  2279. let msgResult = I18N('DAMAGE_NO_FIXED', {
  2280. lastDamage: lastDamage.toLocaleString()
  2281. });
  2282. if (result.value > lastDamage) {
  2283. call.args.result = result.result;
  2284. call.args.progress = result.progress;
  2285. msgResult = I18N('DAMAGE_FIXED', {
  2286. lastDamage: lastDamage.toLocaleString(),
  2287. maxDamage: result.value.toLocaleString(),
  2288. });
  2289. }
  2290. console.log(lastDamage, '>', result.value);
  2291. setProgress(
  2292. msgResult +
  2293. '<br/>' +
  2294. I18N('COUNT_FIXED', {
  2295. count: result.maxCount,
  2296. }),
  2297. false,
  2298. hideProgress
  2299. );
  2300. } else if (resultPopup > 3) {
  2301. const cloneBattle = structuredClone(lastBossBattle);
  2302. const { masterFixBattle } = HWHClasses;
  2303. const mFix = new masterFixBattle(cloneBattle);
  2304. const result = await mFix.start(cloneBattle.endTime, resultPopup);
  2305. console.log(result);
  2306. let msgResult = I18N('DAMAGE_NO_FIXED', {
  2307. lastDamage: lastDamage.toLocaleString(),
  2308. });
  2309. if (result.value > lastDamage) {
  2310. maxDamage = result.value;
  2311. call.args.result = result.result;
  2312. call.args.progress = result.progress;
  2313. msgResult = I18N('DAMAGE_FIXED', {
  2314. lastDamage: lastDamage.toLocaleString(),
  2315. maxDamage: maxDamage.toLocaleString(),
  2316. });
  2317. }
  2318. console.log('Урон:', lastDamage, maxDamage);
  2319. setProgress(msgResult, false, hideProgress);
  2320. } else {
  2321. fixBattle(call.args.progress[0].attackers.heroes);
  2322. fixBattle(call.args.progress[0].defenders.heroes);
  2323. }
  2324. changeRequest = true;
  2325. }
  2326. const isStat = popup.getCheckBoxes().find((e) => e.name === 'isStat');
  2327. if (isStat.checked) {
  2328. this.onReadySuccess = testBossBattle;
  2329. }
  2330. }
  2331. /**
  2332. * Save the Asgard Boss Attack Pack
  2333. * Сохраняем пачку для атаки босса Асгарда
  2334. */
  2335. if (call.name == 'clanRaid_startBossBattle') {
  2336. console.log(JSON.stringify(call.args));
  2337. }
  2338. /**
  2339. * Saving the request to start the last battle
  2340. * Сохранение запроса начала последнего боя
  2341. */
  2342. if (
  2343. call.name == 'clanWarAttack' ||
  2344. call.name == 'crossClanWar_startBattle' ||
  2345. call.name == 'adventure_turnStartBattle' ||
  2346. call.name == 'adventureSolo_turnStartBattle' ||
  2347. call.name == 'bossAttack' ||
  2348. call.name == 'invasion_bossStart' ||
  2349. call.name == 'towerStartBattle'
  2350. ) {
  2351. nameFuncStartBattle = call.name;
  2352. lastBattleArg = call.args;
  2353.  
  2354. if (call.name == 'invasion_bossStart') {
  2355. const timePassed = Date.now() - lastBossBattleStart;
  2356. if (timePassed < invasionTimer) {
  2357. await new Promise((e) => setTimeout(e, invasionTimer - timePassed));
  2358. }
  2359. invasionTimer -= 1;
  2360. }
  2361. lastBossBattleStart = Date.now();
  2362. }
  2363. if (call.name == 'invasion_bossEnd') {
  2364. const lastBattle = lastBattleInfo;
  2365. if (lastBattle && call.args.result.win) {
  2366. if (lastBattle.seed === 8008) {
  2367. lastBattle.progress = call.args.progress;
  2368. const result = await Calc(lastBattle);
  2369. let timer = getTimer(result.battleTime, 1) + addBattleTimer;
  2370. const period = Math.ceil((Date.now() - lastBossBattleStart) / 1000);
  2371. console.log(timer, period);
  2372. if (period < timer) {
  2373. timer = timer - period;
  2374. await countdownTimer(timer);
  2375. }
  2376. }
  2377. }
  2378. }
  2379. /**
  2380. * Disable spending divination cards
  2381. * Отключить трату карт предсказаний
  2382. */
  2383. if (call.name == 'dungeonEndBattle') {
  2384. if (call.args.isRaid) {
  2385. if (countPredictionCard <= 0) {
  2386. delete call.args.isRaid;
  2387. changeRequest = true;
  2388. } else if (countPredictionCard > 0) {
  2389. countPredictionCard--;
  2390. }
  2391. }
  2392. console.log(`Cards: ${countPredictionCard}`);
  2393. /**
  2394. * Fix endless cards
  2395. * Исправление бесконечных карт
  2396. */
  2397. const lastBattle = lastDungeonBattleData;
  2398. if (lastBattle && !call.args.isRaid) {
  2399. if (changeRequest) {
  2400. lastBattle.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  2401. } else {
  2402. lastBattle.progress = call.args.progress;
  2403. }
  2404. const result = await Calc(lastBattle);
  2405.  
  2406. if (changeRequest) {
  2407. call.args.progress = result.progress;
  2408. call.args.result = result.result;
  2409. }
  2410. let timer = result.battleTimer + addBattleTimer;
  2411. const period = Math.ceil((Date.now() - lastDungeonBattleStart) / 1000);
  2412. console.log(timer, period);
  2413. if (period < timer) {
  2414. timer = timer - period;
  2415. await countdownTimer(timer);
  2416. }
  2417. }
  2418. }
  2419. /**
  2420. * Quiz Answer
  2421. * Ответ на викторину
  2422. */
  2423. if (call.name == 'quiz_answer') {
  2424. /**
  2425. * Automatically changes the answer to the correct one if there is one.
  2426. * Автоматически меняет ответ на правильный если он есть
  2427. */
  2428. if (lastAnswer && isChecked('getAnswer')) {
  2429. call.args.answerId = lastAnswer;
  2430. lastAnswer = null;
  2431. changeRequest = true;
  2432. }
  2433. }
  2434. /**
  2435. * Present
  2436. * Подарки
  2437. */
  2438. if (call.name == 'freebieCheck') {
  2439. freebieCheckInfo = call;
  2440. }
  2441. /** missionTimer */
  2442. if (call.name == 'missionEnd' && missionBattle) {
  2443. let startTimer = false;
  2444. if (!call.args.result.win) {
  2445. startTimer = await popup.confirm(I18N('DEFEAT_TURN_TIMER'), [
  2446. { msg: I18N('BTN_NO'), result: false },
  2447. { msg: I18N('BTN_YES'), result: true },
  2448. ]);
  2449. }
  2450.  
  2451. if (call.args.result.win || startTimer) {
  2452. missionBattle.progress = call.args.progress;
  2453. missionBattle.result = call.args.result;
  2454. const result = await Calc(missionBattle);
  2455.  
  2456. let timer = result.battleTimer + addBattleTimer;
  2457. const period = Math.ceil((Date.now() - lastMissionBattleStart) / 1000);
  2458. if (period < timer) {
  2459. timer = timer - period;
  2460. await countdownTimer(timer);
  2461. }
  2462. missionBattle = null;
  2463. } else {
  2464. this.errorRequest = true;
  2465. }
  2466. }
  2467. /**
  2468. * Getting mission data for auto-repeat
  2469. * Получение данных миссии для автоповтора
  2470. */
  2471. if (isChecked('repeatMission') &&
  2472. call.name == 'missionEnd') {
  2473. let missionInfo = {
  2474. id: call.args.id,
  2475. result: call.args.result,
  2476. heroes: call.args.progress[0].attackers.heroes,
  2477. count: 0,
  2478. }
  2479. setTimeout(async () => {
  2480. if (!isSendsMission && await popup.confirm(I18N('MSG_REPEAT_MISSION'), [
  2481. { msg: I18N('BTN_REPEAT'), result: true},
  2482. { msg: I18N('BTN_NO'), result: false},
  2483. ])) {
  2484. isStopSendMission = false;
  2485. isSendsMission = true;
  2486. sendsMission(missionInfo);
  2487. }
  2488. }, 0);
  2489. }
  2490. /**
  2491. * Getting mission data
  2492. * Получение данных миссии
  2493. * missionTimer
  2494. */
  2495. if (call.name == 'missionStart') {
  2496. lastMissionStart = call.args;
  2497. lastMissionBattleStart = Date.now();
  2498. }
  2499. /**
  2500. * Specify the quantity for Titan Orbs and Pet Eggs
  2501. * Указать количество для сфер титанов и яиц петов
  2502. */
  2503. if (isChecked('countControl') &&
  2504. (call.name == 'pet_chestOpen' ||
  2505. call.name == 'titanUseSummonCircle') &&
  2506. call.args.amount > 1) {
  2507. const startAmount = call.args.amount;
  2508. const result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2509. { msg: I18N('BTN_OPEN'), isInput: true, default: 1},
  2510. ]);
  2511. if (result) {
  2512. const item = call.name == 'pet_chestOpen' ? { id: 90, type: 'consumable' } : { id: 13, type: 'coin' };
  2513. cheats.updateInventory({
  2514. [item.type]: {
  2515. [item.id]: -(result - startAmount),
  2516. },
  2517. });
  2518. call.args.amount = result;
  2519. changeRequest = true;
  2520. }
  2521. }
  2522. /**
  2523. * Specify the amount for keys and spheres of titan artifacts
  2524. * Указать колличество для ключей и сфер артефактов титанов
  2525. */
  2526. if (isChecked('countControl') &&
  2527. (call.name == 'artifactChestOpen' ||
  2528. call.name == 'titanArtifactChestOpen') &&
  2529. call.args.amount > 1 &&
  2530. call.args.free &&
  2531. !changeRequest) {
  2532. artifactChestOpenCallName = call.name;
  2533. const startAmount = call.args.amount;
  2534. let result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2535. { msg: I18N('BTN_OPEN'), isInput: true, default: 1 },
  2536. ]);
  2537. if (result) {
  2538. const openChests = result;
  2539. let sphere = result < 10 ? 1 : 10;
  2540. call.args.amount = sphere;
  2541. for (let count = openChests - sphere; count > 0; count -= sphere) {
  2542. if (count < 10) sphere = 1;
  2543. const ident = artifactChestOpenCallName + "_" + count;
  2544. testData.calls.push({
  2545. name: artifactChestOpenCallName,
  2546. args: {
  2547. amount: sphere,
  2548. free: true,
  2549. },
  2550. ident: ident
  2551. });
  2552. if (!Array.isArray(requestHistory[this.uniqid].calls[call.name])) {
  2553. requestHistory[this.uniqid].calls[call.name] = [requestHistory[this.uniqid].calls[call.name]];
  2554. }
  2555. requestHistory[this.uniqid].calls[call.name].push(ident);
  2556. }
  2557.  
  2558. const consumableId = call.name == 'artifactChestOpen' ? 45 : 55;
  2559. cheats.updateInventory({
  2560. consumable: {
  2561. [consumableId]: -(openChests - startAmount),
  2562. },
  2563. });
  2564. artifactChestOpen = true;
  2565. changeRequest = true;
  2566. }
  2567. }
  2568. if (call.name == 'consumableUseLootBox') {
  2569. lastRussianDollId = call.args.libId;
  2570. /**
  2571. * Specify quantity for gold caskets
  2572. * Указать количество для золотых шкатулок
  2573. */
  2574. if (isChecked('countControl') &&
  2575. call.args.libId == 148 &&
  2576. call.args.amount > 1) {
  2577. const result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2578. { msg: I18N('BTN_OPEN'), isInput: true, default: call.args.amount},
  2579. ]);
  2580. call.args.amount = result;
  2581. changeRequest = true;
  2582. }
  2583. if (isChecked('countControl') && call.args.libId >= 362 && call.args.libId <= 389) {
  2584. this.massOpen = call.args.libId;
  2585. }
  2586. }
  2587. if (call.name == 'invasion_bossStart' && isChecked('tryFixIt_v2')) {
  2588. const { invasionInfo, invasionDataPacks } = HWHData;
  2589. if (call.args.id == invasionInfo.id) {
  2590. const pack = invasionDataPacks[invasionInfo.bossLvl];
  2591. if (pack) {
  2592. if (pack.buff != invasionInfo.buff) {
  2593. setProgress(
  2594. I18N('INVASION_BOSS_BUFF', {
  2595. bossLvl: invasionInfo.bossLvl,
  2596. needBuff: pack.buff,
  2597. haveBuff: invasionInfo.buff,
  2598. }),
  2599. false
  2600. );
  2601. } else {
  2602. call.args.pet = pack.pet;
  2603. call.args.heroes = pack.heroes;
  2604. call.args.favor = pack.favor;
  2605. changeRequest = true;
  2606. }
  2607. }
  2608. }
  2609. }
  2610. if (call.name == 'workshopBuff_create') {
  2611. const { invasionInfo, invasionDataPacks } = HWHData;
  2612. const pack = invasionDataPacks[invasionInfo.bossLvl];
  2613. if (pack) {
  2614. const addBuff = call.args.amount * 5;
  2615. if (pack.buff < addBuff + invasionInfo.buff) {
  2616. this.errorRequest = true;
  2617. }
  2618. setProgress(
  2619. I18N('INVASION_BOSS_BUFF', {
  2620. bossLvl: invasionInfo.bossLvl,
  2621. needBuff: pack.buff,
  2622. haveBuff: invasionInfo.buff,
  2623. }),
  2624. false
  2625. );
  2626. }
  2627. }
  2628. if (call.name == 'saleShowcase_rewardInfo') {
  2629. this[call.name] = {
  2630. offerId: call.args.offerId,
  2631. };
  2632. }
  2633. /**
  2634. * Changing the maximum number of raids in the campaign
  2635. * Изменение максимального количества рейдов в кампании
  2636. */
  2637. // if (call.name == 'missionRaid') {
  2638. // if (isChecked('countControl') && call.args.times > 1) {
  2639. // const result = +(await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2640. // { msg: I18N('BTN_RUN'), isInput: true, default: call.args.times },
  2641. // ]));
  2642. // call.args.times = result > call.args.times ? call.args.times : result;
  2643. // changeRequest = true;
  2644. // }
  2645. // }
  2646. }
  2647.  
  2648. let headers = requestHistory[this.uniqid].headers;
  2649. if (changeRequest) {
  2650. sourceData = JSON.stringify(testData);
  2651. headers['X-Auth-Signature'] = getSignature(headers, sourceData);
  2652. }
  2653.  
  2654. let signature = headers['X-Auth-Signature'];
  2655. if (signature) {
  2656. original.setRequestHeader.call(this, 'X-Auth-Signature', signature);
  2657. }
  2658.  
  2659. if (this.checkRequest) {
  2660. console.log(requestHistory[this.uniqid]);
  2661. debugger;
  2662. }
  2663. } catch (err) {
  2664. console.log("Request(send, " + this.uniqid + "):\n", sourceData, "Error:\n", err);
  2665. }
  2666. return sourceData;
  2667. }
  2668. /**
  2669. * Processing and substitution of incoming data
  2670. *
  2671. * Обработка и подмена входящих данных
  2672. */
  2673. async function checkChangeResponse(response) {
  2674. try {
  2675. isChange = false;
  2676. let nowTime = Math.round(Date.now() / 1000);
  2677. callsIdent = requestHistory[this.uniqid].calls;
  2678. respond = JSON.parse(response);
  2679. /**
  2680. * If the request returned an error removes the error (removes synchronization errors)
  2681. * Если запрос вернул ошибку удаляет ошибку (убирает ошибки синхронизации)
  2682. */
  2683. if (respond.error) {
  2684. isChange = true;
  2685. console.error(respond.error);
  2686. if (isChecked('showErrors')) {
  2687. popup.confirm(I18N('ERROR_MSG', {
  2688. name: respond.error.name,
  2689. description: respond.error.description,
  2690. }));
  2691. }
  2692. if (respond.error.name != 'AccountBan') {
  2693. delete respond.error;
  2694. respond.results = [];
  2695. }
  2696. }
  2697. let mainReward = null;
  2698. const allReward = {};
  2699. let countTypeReward = 0;
  2700. let readQuestInfo = false;
  2701. for (const call of respond.results) {
  2702. /**
  2703. * Obtaining initial data for completing quests
  2704. * Получение исходных данных для выполнения квестов
  2705. */
  2706. if (readQuestInfo) {
  2707. questsInfo[call.ident] = call.result.response;
  2708. }
  2709. /**
  2710. * Getting a user ID
  2711. * Получение идетификатора пользователя
  2712. */
  2713. if (call.ident == callsIdent['registration']) {
  2714. userId = call.result.response.userId;
  2715. if (localStorage['userId'] != userId) {
  2716. localStorage['newGiftSendIds'] = '';
  2717. localStorage['userId'] = userId;
  2718. }
  2719. await openOrMigrateDatabase(userId);
  2720. readQuestInfo = true;
  2721. }
  2722. /**
  2723. * Hiding donation offers 1
  2724. * Скрываем предложения доната 1
  2725. */
  2726. if (call.ident == callsIdent['billingGetAll'] && getSaveVal('noOfferDonat')) {
  2727. const billings = call.result.response?.billings;
  2728. const bundle = call.result.response?.bundle;
  2729. if (billings && bundle) {
  2730. call.result.response.billings = call.result.response.billings.filter((e) => ['repeatableOffer'].includes(e.type));
  2731. call.result.response.bundle = [];
  2732. isChange = true;
  2733. }
  2734. }
  2735. /**
  2736. * Hiding donation offers 2
  2737. * Скрываем предложения доната 2
  2738. */
  2739. if (getSaveVal('noOfferDonat') &&
  2740. (call.ident == callsIdent['offerGetAll'] ||
  2741. call.ident == callsIdent['specialOffer_getAll'])) {
  2742. let offers = call.result.response;
  2743. if (offers) {
  2744. call.result.response = offers.filter(
  2745. (e) => !['addBilling', 'bundleCarousel'].includes(e.type) || ['idleResource', 'stagesOffer'].includes(e.offerType)
  2746. );
  2747. isChange = true;
  2748. }
  2749. }
  2750. /**
  2751. * Hiding donation offers 3
  2752. * Скрываем предложения доната 3
  2753. */
  2754. if (getSaveVal('noOfferDonat') && call.result?.bundleUpdate) {
  2755. delete call.result.bundleUpdate;
  2756. isChange = true;
  2757. }
  2758. /**
  2759. * Hiding donation offers 4
  2760. * Скрываем предложения доната 4
  2761. */
  2762. if (call.result?.specialOffers) {
  2763. const offers = call.result.specialOffers;
  2764. call.result.specialOffers = offers.filter(
  2765. (e) => !['addBilling', 'bundleCarousel'].includes(e.type) || ['idleResource', 'stagesOffer'].includes(e.offerType)
  2766. );
  2767. isChange = true;
  2768. }
  2769. /**
  2770. * Copies a quiz question to the clipboard
  2771. * Копирует вопрос викторины в буфер обмена и получает на него ответ если есть
  2772. */
  2773. if (call.ident == callsIdent['quiz_getNewQuestion']) {
  2774. let quest = call.result.response;
  2775. console.log(quest.question);
  2776. copyText(quest.question);
  2777. setProgress(I18N('QUESTION_COPY'), true);
  2778. quest.lang = null;
  2779. if (typeof NXFlashVars !== 'undefined') {
  2780. quest.lang = NXFlashVars.interface_lang;
  2781. }
  2782. lastQuestion = quest;
  2783. if (isChecked('getAnswer')) {
  2784. const answer = await getAnswer(lastQuestion);
  2785. let showText = '';
  2786. if (answer) {
  2787. lastAnswer = answer;
  2788. console.log(answer);
  2789. showText = `${I18N('ANSWER_KNOWN')}: ${answer}`;
  2790. } else {
  2791. showText = I18N('ANSWER_NOT_KNOWN');
  2792. }
  2793.  
  2794. try {
  2795. const hint = hintQuest(quest);
  2796. if (hint) {
  2797. showText += I18N('HINT') + hint;
  2798. }
  2799. } catch (e) {}
  2800.  
  2801. setProgress(showText, true);
  2802. }
  2803. }
  2804. /**
  2805. * Submits a question with an answer to the database
  2806. * Отправляет вопрос с ответом в базу данных
  2807. */
  2808. if (call.ident == callsIdent['quiz_answer']) {
  2809. const answer = call.result.response;
  2810. if (lastQuestion) {
  2811. const answerInfo = {
  2812. answer,
  2813. question: lastQuestion,
  2814. lang: null,
  2815. };
  2816. if (typeof NXFlashVars !== 'undefined') {
  2817. answerInfo.lang = NXFlashVars.interface_lang;
  2818. }
  2819. lastQuestion = null;
  2820. setTimeout(sendAnswerInfo, 0, answerInfo);
  2821. }
  2822. }
  2823. /**
  2824. * Get user data
  2825. * Получить даныне пользователя
  2826. */
  2827. if (call.ident == callsIdent['userGetInfo']) {
  2828. let user = call.result.response;
  2829. document.title = user.name;
  2830. userInfo = Object.assign({}, user);
  2831. delete userInfo.refillable;
  2832. if (!questsInfo['userGetInfo']) {
  2833. questsInfo['userGetInfo'] = user;
  2834. }
  2835. }
  2836. /**
  2837. * Start of the battle for recalculation
  2838. * Начало боя для прерасчета
  2839. */
  2840. if (call.ident == callsIdent['clanWarAttack'] ||
  2841. call.ident == callsIdent['crossClanWar_startBattle'] ||
  2842. call.ident == callsIdent['bossAttack'] ||
  2843. call.ident == callsIdent['battleGetReplay'] ||
  2844. call.ident == callsIdent['brawl_startBattle'] ||
  2845. call.ident == callsIdent['adventureSolo_turnStartBattle'] ||
  2846. call.ident == callsIdent['invasion_bossStart'] ||
  2847. call.ident == callsIdent['titanArenaStartBattle'] ||
  2848. call.ident == callsIdent['towerStartBattle'] ||
  2849. call.ident == callsIdent['epicBrawl_startBattle'] ||
  2850. call.ident == callsIdent['adventure_turnStartBattle']) {
  2851. let battle = call.result.response.battle || call.result.response.replay;
  2852. if (call.ident == callsIdent['brawl_startBattle'] ||
  2853. call.ident == callsIdent['bossAttack'] ||
  2854. call.ident == callsIdent['towerStartBattle'] ||
  2855. call.ident == callsIdent['invasion_bossStart']) {
  2856. battle = call.result.response;
  2857. }
  2858. lastBattleInfo = battle;
  2859. if (call.ident == callsIdent['battleGetReplay'] && call.result.response.replay.type === "clan_raid") {
  2860. if (call?.result?.response?.replay?.result?.damage) {
  2861. const damages = Object.values(call.result.response.replay.result.damage);
  2862. const bossDamage = damages.reduce((a, v) => a + v, 0);
  2863. setProgress(I18N('BOSS_DAMAGE') + bossDamage.toLocaleString(), false, hideProgress);
  2864. continue;
  2865. }
  2866. }
  2867. if (!isChecked('preCalcBattle')) {
  2868. continue;
  2869. }
  2870. const preCalcBattle = structuredClone(battle);
  2871. setProgress(I18N('BEING_RECALC'));
  2872. let battleDuration = 120;
  2873. try {
  2874. const typeBattle = getBattleType(preCalcBattle.type);
  2875. battleDuration = +lib.data.battleConfig[typeBattle.split('_')[1]].config.battleDuration;
  2876. } catch (e) { }
  2877. //console.log(battle.type);
  2878. function getBattleInfo(battle, isRandSeed) {
  2879. return new Promise(function (resolve) {
  2880. if (isRandSeed) {
  2881. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  2882. }
  2883. BattleCalc(battle, getBattleType(battle.type), e => resolve(e));
  2884. });
  2885. }
  2886. let actions = [getBattleInfo(preCalcBattle, false)];
  2887. let countTestBattle = getInput('countTestBattle');
  2888. if (call.ident == callsIdent['invasion_bossStart'] && preCalcBattle.seed === 8008) {
  2889. countTestBattle = 0;
  2890. }
  2891. if (call.ident == callsIdent['battleGetReplay']) {
  2892. preCalcBattle.progress = [{ attackers: { input: ['auto', 0, 0, 'auto', 0, 0] } }];
  2893. }
  2894. for (let i = 0; i < countTestBattle; i++) {
  2895. actions.push(getBattleInfo(preCalcBattle, true));
  2896. }
  2897. Promise.all(actions)
  2898. .then(e => {
  2899. e = e.map(n => ({win: n.result.win, time: n.battleTime}));
  2900. let firstBattle = e.shift();
  2901. const timer = Math.floor(battleDuration - firstBattle.time);
  2902. const min = ('00' + Math.floor(timer / 60)).slice(-2);
  2903. const sec = ('00' + Math.floor(timer - min * 60)).slice(-2);
  2904. let msg = `${I18N('THIS_TIME')} ${firstBattle.win ? I18N('VICTORY') : I18N('DEFEAT')}`;
  2905. if (e.length) {
  2906. const countWin = e.reduce((w, s) => w + s.win, 0);
  2907. msg += ` ${I18N('CHANCE_TO_WIN')}: ${Math.floor((countWin / e.length) * 100)}% (${e.length})`;
  2908. }
  2909. msg += `, ${min}:${sec}`
  2910. setProgress(msg, false, hideProgress)
  2911. });
  2912. }
  2913. /**
  2914. * Start of the Asgard boss fight
  2915. * Начало боя с боссом Асгарда
  2916. */
  2917. if (call.ident == callsIdent['clanRaid_startBossBattle']) {
  2918. lastBossBattle = call.result.response.battle;
  2919. lastBossBattle.endTime = Date.now() + 160 * 1000;
  2920. if (isChecked('preCalcBattle')) {
  2921. const result = await Calc(lastBossBattle).then(e => e.progress[0].defenders.heroes[1].extra);
  2922. const bossDamage = result.damageTaken + result.damageTakenNextLevel;
  2923. setProgress(I18N('BOSS_DAMAGE') + bossDamage.toLocaleString(), false, hideProgress);
  2924. }
  2925. }
  2926. /**
  2927. * Cancel tutorial
  2928. * Отмена туториала
  2929. */
  2930. if (isCanceledTutorial && call.ident == callsIdent['tutorialGetInfo']) {
  2931. let chains = call.result.response.chains;
  2932. for (let n in chains) {
  2933. chains[n] = 9999;
  2934. }
  2935. isChange = true;
  2936. }
  2937. /**
  2938. * Opening keys and spheres of titan artifacts
  2939. * Открытие ключей и сфер артефактов титанов
  2940. */
  2941. if (artifactChestOpen &&
  2942. (call.ident == callsIdent[artifactChestOpenCallName] ||
  2943. (callsIdent[artifactChestOpenCallName] && callsIdent[artifactChestOpenCallName].includes(call.ident)))) {
  2944. let reward = call.result.response[artifactChestOpenCallName == 'artifactChestOpen' ? 'chestReward' : 'reward'];
  2945.  
  2946. reward.forEach(e => {
  2947. for (let f in e) {
  2948. if (!allReward[f]) {
  2949. allReward[f] = {};
  2950. }
  2951. for (let o in e[f]) {
  2952. if (!allReward[f][o]) {
  2953. allReward[f][o] = e[f][o];
  2954. countTypeReward++;
  2955. } else {
  2956. allReward[f][o] += e[f][o];
  2957. }
  2958. }
  2959. }
  2960. });
  2961.  
  2962. if (!call.ident.includes(artifactChestOpenCallName)) {
  2963. mainReward = call.result.response;
  2964. }
  2965. }
  2966.  
  2967. if (countTypeReward > 20) {
  2968. correctShowOpenArtifact = 3;
  2969. } else {
  2970. correctShowOpenArtifact = 0;
  2971. }
  2972. /**
  2973. * Sum the result of opening Pet Eggs
  2974. * Суммирование результата открытия яиц питомцев
  2975. */
  2976. if (isChecked('countControl') && call.ident == callsIdent['pet_chestOpen']) {
  2977. const rewards = call.result.response.rewards;
  2978. if (rewards.length > 10) {
  2979. /**
  2980. * Removing pet cards
  2981. * Убираем карточки петов
  2982. */
  2983. for (const reward of rewards) {
  2984. if (reward.petCard) {
  2985. delete reward.petCard;
  2986. }
  2987. }
  2988. }
  2989. rewards.forEach(e => {
  2990. for (let f in e) {
  2991. if (!allReward[f]) {
  2992. allReward[f] = {};
  2993. }
  2994. for (let o in e[f]) {
  2995. if (!allReward[f][o]) {
  2996. allReward[f][o] = e[f][o];
  2997. } else {
  2998. allReward[f][o] += e[f][o];
  2999. }
  3000. }
  3001. }
  3002. });
  3003. call.result.response.rewards = [allReward];
  3004. isChange = true;
  3005. }
  3006. /**
  3007. * Removing titan cards
  3008. * Убираем карточки титанов
  3009. */
  3010. if (call.ident == callsIdent['titanUseSummonCircle']) {
  3011. if (call.result.response.rewards.length > 10) {
  3012. for (const reward of call.result.response.rewards) {
  3013. if (reward.titanCard) {
  3014. delete reward.titanCard;
  3015. }
  3016. }
  3017. isChange = true;
  3018. }
  3019. }
  3020. /**
  3021. * Auto-repeat opening matryoshkas
  3022. * АвтоПовтор открытия матрешек
  3023. */
  3024. if (isChecked('countControl') && call.ident == callsIdent['consumableUseLootBox']) {
  3025. let [countLootBox, lootBox] = Object.entries(call.result.response).pop();
  3026. countLootBox = +countLootBox;
  3027. let newCount = 0;
  3028. if (lootBox?.consumable && lootBox.consumable[lastRussianDollId]) {
  3029. newCount += lootBox.consumable[lastRussianDollId];
  3030. delete lootBox.consumable[lastRussianDollId];
  3031. }
  3032. if (
  3033. newCount &&
  3034. (await popup.confirm(`${I18N('BTN_OPEN')} ${newCount} ${I18N('OPEN_DOLLS')}?`, [
  3035. { msg: I18N('BTN_OPEN'), result: true },
  3036. { msg: I18N('BTN_NO'), result: false, isClose: true },
  3037. ]))
  3038. ) {
  3039. const [count, recursionResult] = await openRussianDolls(lastRussianDollId, newCount);
  3040. countLootBox += +count;
  3041. mergeItemsObj(lootBox, recursionResult);
  3042. isChange = true;
  3043. }
  3044.  
  3045. if (this.massOpen) {
  3046. if (
  3047. await popup.confirm(I18N('OPEN_ALL_EQUIP_BOXES'), [
  3048. { msg: I18N('BTN_OPEN'), result: true },
  3049. { msg: I18N('BTN_NO'), result: false, isClose: true },
  3050. ])
  3051. ) {
  3052. const consumable = await Send({ calls: [{ name: 'inventoryGet', args: {}, ident: 'inventoryGet' }] }).then((e) =>
  3053. Object.entries(e.results[0].result.response.consumable)
  3054. );
  3055. const calls = [];
  3056. const deleteItems = {};
  3057. for (const [libId, amount] of consumable) {
  3058. if (libId != this.massOpen && libId >= 362 && libId <= 389) {
  3059. calls.push({
  3060. name: 'consumableUseLootBox',
  3061. args: { libId, amount },
  3062. ident: 'consumableUseLootBox_' + libId,
  3063. });
  3064. deleteItems[libId] = -amount;
  3065. }
  3066. }
  3067. const responses = await Send({ calls }).then((e) => e.results.map((r) => r.result.response).flat());
  3068.  
  3069. for (const loot of responses) {
  3070. const [count, result] = Object.entries(loot).pop();
  3071. countLootBox += +count;
  3072.  
  3073. mergeItemsObj(lootBox, result);
  3074. }
  3075. isChange = true;
  3076.  
  3077. this.onReadySuccess = () => {
  3078. cheats.updateInventory({ consumable: deleteItems });
  3079. cheats.refreshInventory();
  3080. };
  3081. }
  3082. }
  3083.  
  3084. if (isChange) {
  3085. call.result.response = {
  3086. [countLootBox]: lootBox,
  3087. };
  3088. }
  3089. }
  3090. /**
  3091. * Dungeon recalculation (fix endless cards)
  3092. * Прерасчет подземки (исправление бесконечных карт)
  3093. */
  3094. if (call.ident == callsIdent['dungeonStartBattle']) {
  3095. lastDungeonBattleData = call.result.response;
  3096. lastDungeonBattleStart = Date.now();
  3097. }
  3098. /**
  3099. * Getting the number of prediction cards
  3100. * Получение количества карт предсказаний
  3101. */
  3102. if (call.ident == callsIdent['inventoryGet']) {
  3103. countPredictionCard = call.result.response.consumable[81] || 0;
  3104. }
  3105. /**
  3106. * Getting subscription status
  3107. * Получение состояния подписки
  3108. */
  3109. if (call.ident == callsIdent['subscriptionGetInfo']) {
  3110. const subscription = call.result.response.subscription;
  3111. if (subscription) {
  3112. subEndTime = subscription.endTime * 1000;
  3113. }
  3114. }
  3115. /**
  3116. * Getting prediction cards
  3117. * Получение карт предсказаний
  3118. */
  3119. if (call.ident == callsIdent['questFarm']) {
  3120. const consumable = call.result.response?.consumable;
  3121. if (consumable && consumable[81]) {
  3122. countPredictionCard += consumable[81];
  3123. console.log(`Cards: ${countPredictionCard}`);
  3124. }
  3125. }
  3126. /**
  3127. * Hiding extra servers
  3128. * Скрытие лишних серверов
  3129. */
  3130. if (call.ident == callsIdent['serverGetAll'] && isChecked('hideServers')) {
  3131. let servers = call.result.response.users.map(s => s.serverId)
  3132. call.result.response.servers = call.result.response.servers.filter(s => servers.includes(s.id));
  3133. isChange = true;
  3134. }
  3135. /**
  3136. * Displays player positions in the adventure
  3137. * Отображает позиции игроков в приключении
  3138. */
  3139. if (call.ident == callsIdent['adventure_getLobbyInfo']) {
  3140. const users = Object.values(call.result.response.users);
  3141. const mapIdent = call.result.response.mapIdent;
  3142. const adventureId = call.result.response.adventureId;
  3143. const maps = {
  3144. adv_strongford_3pl_hell: 9,
  3145. adv_valley_3pl_hell: 10,
  3146. adv_ghirwil_3pl_hell: 11,
  3147. adv_angels_3pl_hell: 12,
  3148. }
  3149. let msg = I18N('MAP') + (mapIdent in maps ? maps[mapIdent] : adventureId);
  3150. msg += '<br>' + I18N('PLAYER_POS');
  3151. for (const user of users) {
  3152. msg += `<br>${user.user.name} - ${user.currentNode}`;
  3153. }
  3154. setProgress(msg, false, hideProgress);
  3155. }
  3156. /**
  3157. * Automatic launch of a raid at the end of the adventure
  3158. * Автоматический запуск рейда при окончании приключения
  3159. */
  3160. if (call.ident == callsIdent['adventure_end']) {
  3161. autoRaidAdventure()
  3162. }
  3163. /** Удаление лавки редкостей */
  3164. if (call.ident == callsIdent['missionRaid']) {
  3165. if (call.result?.heroesMerchant) {
  3166. delete call.result.heroesMerchant;
  3167. isChange = true;
  3168. }
  3169. }
  3170. /** missionTimer */
  3171. if (call.ident == callsIdent['missionStart']) {
  3172. missionBattle = call.result.response;
  3173. }
  3174. /** Награды турнира стихий */
  3175. if (call.ident == callsIdent['hallOfFameGetTrophies']) {
  3176. const trophys = call.result.response;
  3177. const calls = [];
  3178. for (const week in trophys) {
  3179. const trophy = trophys[week];
  3180. if (!trophy.championRewardFarmed) {
  3181. calls.push({
  3182. name: 'hallOfFameFarmTrophyReward',
  3183. args: { trophyId: week, rewardType: 'champion' },
  3184. ident: 'body_champion_' + week,
  3185. });
  3186. }
  3187. if (Object.keys(trophy.clanReward).length && !trophy.clanRewardFarmed) {
  3188. calls.push({
  3189. name: 'hallOfFameFarmTrophyReward',
  3190. args: { trophyId: week, rewardType: 'clan' },
  3191. ident: 'body_clan_' + week,
  3192. });
  3193. }
  3194. }
  3195. if (calls.length) {
  3196. Send({ calls })
  3197. .then((e) => e.results.map((e) => e.result.response))
  3198. .then(async results => {
  3199. let coin18 = 0,
  3200. coin19 = 0,
  3201. gold = 0,
  3202. starmoney = 0;
  3203. for (const r of results) {
  3204. coin18 += r?.coin ? +r.coin[18] : 0;
  3205. coin19 += r?.coin ? +r.coin[19] : 0;
  3206. gold += r?.gold ? +r.gold : 0;
  3207. starmoney += r?.starmoney ? +r.starmoney : 0;
  3208. }
  3209.  
  3210. let msg = I18N('ELEMENT_TOURNAMENT_REWARD') + '<br>';
  3211. if (coin18) {
  3212. msg += cheats.translate('LIB_COIN_NAME_18') + `: ${coin18}<br>`;
  3213. }
  3214. if (coin19) {
  3215. msg += cheats.translate('LIB_COIN_NAME_19') + `: ${coin19}<br>`;
  3216. }
  3217. if (gold) {
  3218. msg += cheats.translate('LIB_PSEUDO_COIN') + `: ${gold}<br>`;
  3219. }
  3220. if (starmoney) {
  3221. msg += cheats.translate('LIB_PSEUDO_STARMONEY') + `: ${starmoney}<br>`;
  3222. }
  3223.  
  3224. await popup.confirm(msg, [{ msg: I18N('BTN_OK'), result: 0 }]);
  3225. });
  3226. }
  3227. }
  3228. if (call.ident == callsIdent['clanDomination_getInfo']) {
  3229. clanDominationGetInfo = call.result.response;
  3230. }
  3231. if (call.ident == callsIdent['clanRaid_endBossBattle']) {
  3232. console.log(call.result.response);
  3233. const damage = Object.values(call.result.response.damage).reduce((a, e) => a + e);
  3234. if (call.result.response.result.afterInvalid) {
  3235. addProgress('<br>' + I18N('SERVER_NOT_ACCEPT'));
  3236. }
  3237. addProgress('<br>Server > ' + I18N('BOSS_DAMAGE') + damage.toLocaleString());
  3238. }
  3239. if (call.ident == callsIdent['invasion_getInfo']) {
  3240. /*
  3241. const r = call.result.response;
  3242. if (r?.actions?.length) {
  3243. const { invasionInfo, invasionDataPacks } = HWHData;
  3244. const boss = r.actions.find((e) => e.payload.id === invasionInfo.id);
  3245. if (boss) {
  3246. invasionInfo.buff = r.buffAmount;
  3247. invasionInfo.bossLvl = boss.payload.level;
  3248. if (isChecked('tryFixIt_v2')) {
  3249. const pack = invasionDataPacks[invasionInfo.bossLvl];
  3250. if (pack) {
  3251. setProgress(
  3252. I18N('INVASION_BOSS_BUFF', {
  3253. bossLvl: invasionInfo.bossLvl,
  3254. needBuff: pack.buff,
  3255. haveBuff: invasionInfo.buff,
  3256. }),
  3257. false
  3258. );
  3259. }
  3260. }
  3261. }
  3262. }
  3263. */
  3264. }
  3265. if (call.ident == callsIdent['workshopBuff_create']) {
  3266. const r = call.result.response;
  3267. if (r.id == 1) {
  3268. const { invasionInfo, invasionDataPacks } = HWHData;
  3269. invasionInfo.buff = r.amount;
  3270. if (isChecked('tryFixIt_v2')) {
  3271. const pack = invasionDataPacks[invasionInfo.bossLvl];
  3272. if (pack) {
  3273. setProgress(
  3274. I18N('INVASION_BOSS_BUFF', {
  3275. bossLvl: invasionInfo.bossLvl,
  3276. needBuff: pack.buff,
  3277. haveBuff: invasionInfo.buff,
  3278. }),
  3279. false
  3280. );
  3281. }
  3282. }
  3283. }
  3284. }
  3285. if (call.ident == callsIdent['mailFarm']) {
  3286. const letters = Object.values(call.result.response);
  3287. for (const letter of letters) {
  3288. if (letter.consumable?.[81]) {
  3289. console.log('Карты предсказаний', letter.consumable[81]);
  3290. countPredictionCard += letter.consumable[81];
  3291. }
  3292. if (letter.refillable?.[45]) {
  3293. console.log('Сферы портала', letter.refillable[45]);
  3294. setPortals(+letter.refillable[45], true);
  3295. }
  3296. }
  3297. }
  3298. if (call.ident == callsIdent['quest_questsFarm']) {
  3299. const rewards = call.result.response;
  3300. for (const reward of rewards) {
  3301. if (reward.consumable?.[81]) {
  3302. console.log('Карты предсказаний', reward.consumable[81]);
  3303. countPredictionCard += letter.consumable[81];
  3304. }
  3305. if (reward.refillable?.[45]) {
  3306. console.log('Сферы портала', reward.refillable[45]);
  3307. setPortals(+reward.refillable[45], true);
  3308. }
  3309. }
  3310. }
  3311. if (call.ident == callsIdent['adventure_start']) {
  3312. setPortals(-1, true);
  3313. }
  3314. if (call.ident == callsIdent['clanWarEndBattle']) {
  3315. setWarTries(-1, true);
  3316. }
  3317. if (call.ident == callsIdent['saleShowcase_rewardInfo']) {
  3318. if (new Date(call.result.response.nextRefill * 1000) < Date.now()) {
  3319. const offerId = this?.['saleShowcase_rewardInfo']?.offerId;
  3320. if (offerId) {
  3321. try {
  3322. void Caller.send({ name: 'saleShowcase_farmReward', args: { offerId } });
  3323. } catch (e) {
  3324. console.error(e);
  3325. }
  3326. }
  3327. }
  3328. }
  3329. /*
  3330. if (call.ident == callsIdent['chatGetAll'] && call.args.chatType == 'clanDomination' && !callsIdent['clanDomination_mapState']) {
  3331. this.onReadySuccess = async function () {
  3332. const result = await Send({
  3333. calls: [
  3334. {
  3335. name: 'clanDomination_mapState',
  3336. args: {},
  3337. ident: 'clanDomination_mapState',
  3338. },
  3339. ],
  3340. }).then((e) => e.results[0].result.response);
  3341. let townPositions = result.townPositions;
  3342. let positions = {};
  3343. for (let pos in townPositions) {
  3344. let townPosition = townPositions[pos];
  3345. positions[townPosition.position] = townPosition;
  3346. }
  3347. Object.assign(clanDominationGetInfo, {
  3348. townPositions: positions,
  3349. });
  3350. let userPositions = result.userPositions;
  3351. for (let pos in clanDominationGetInfo.townPositions) {
  3352. let townPosition = clanDominationGetInfo.townPositions[pos];
  3353. if (townPosition.status) {
  3354. userPositions[townPosition.userId] = +pos;
  3355. }
  3356. }
  3357. cheats.updateMap(result);
  3358. };
  3359. }
  3360. if (call.ident == callsIdent['clanDomination_mapState']) {
  3361. const townPositions = call.result.response.townPositions;
  3362. const userPositions = call.result.response.userPositions;
  3363. for (let pos in townPositions) {
  3364. let townPos = townPositions[pos];
  3365. if (townPos.status) {
  3366. userPositions[townPos.userId] = townPos.position;
  3367. }
  3368. }
  3369. isChange = true;
  3370. }
  3371. */
  3372. }
  3373.  
  3374. if (mainReward && artifactChestOpen) {
  3375. console.log(allReward);
  3376. mainReward[artifactChestOpenCallName == 'artifactChestOpen' ? 'chestReward' : 'reward'] = [allReward];
  3377. artifactChestOpen = false;
  3378. artifactChestOpenCallName = '';
  3379. isChange = true;
  3380. }
  3381. } catch(err) {
  3382. console.log("Request(response, " + this.uniqid + "):\n", "Error:\n", response, err);
  3383. }
  3384.  
  3385. if (isChange) {
  3386. Object.defineProperty(this, 'responseText', {
  3387. writable: true
  3388. });
  3389. this.responseText = JSON.stringify(respond);
  3390. }
  3391. }
  3392.  
  3393. /**
  3394. * Request an answer to a question
  3395. *
  3396. * Запрос ответа на вопрос
  3397. */
  3398. async function getAnswer(question) {
  3399. // c29tZSBzdHJhbmdlIHN5bWJvbHM=
  3400. const quizAPI = new ZingerYWebsiteAPI('getAnswer.php', arguments, { question });
  3401. return new Promise((resolve, reject) => {
  3402. quizAPI.request().then((data) => {
  3403. if (data.result) {
  3404. resolve(data.result);
  3405. } else {
  3406. resolve(false);
  3407. }
  3408. }).catch((error) => {
  3409. console.error(error);
  3410. resolve(false);
  3411. });
  3412. })
  3413. }
  3414.  
  3415. /**
  3416. * Submitting a question and answer to a database
  3417. *
  3418. * Отправка вопроса и ответа в базу данных
  3419. */
  3420. function sendAnswerInfo(answerInfo) {
  3421. // c29tZSBub25zZW5zZQ==
  3422. const quizAPI = new ZingerYWebsiteAPI('setAnswer.php', arguments, { answerInfo });
  3423. quizAPI.request().then((data) => {
  3424. if (data.result) {
  3425. console.log(I18N('SENT_QUESTION'));
  3426. }
  3427. });
  3428. }
  3429.  
  3430. /**
  3431. * Returns the battle type by preset type
  3432. *
  3433. * Возвращает тип боя по типу пресета
  3434. */
  3435. function getBattleType(strBattleType) {
  3436. if (!strBattleType) {
  3437. return null;
  3438. }
  3439. switch (strBattleType) {
  3440. case 'titan_pvp':
  3441. return 'get_titanPvp';
  3442. case 'titan_pvp_manual':
  3443. case 'titan_clan_pvp':
  3444. case 'clan_pvp_titan':
  3445. case 'clan_global_pvp_titan':
  3446. case 'brawl_titan':
  3447. case 'challenge_titan':
  3448. case 'titan_mission':
  3449. return 'get_titanPvpManual';
  3450. case 'clan_raid': // Asgard Boss // Босс асгарда
  3451. case 'adventure': // Adventures // Приключения
  3452. case 'clan_global_pvp':
  3453. case 'epic_brawl':
  3454. case 'clan_pvp':
  3455. return 'get_clanPvp';
  3456. case 'dungeon_titan':
  3457. case 'titan_tower':
  3458. return 'get_titan';
  3459. case 'tower':
  3460. case 'clan_dungeon':
  3461. return 'get_tower';
  3462. case 'pve':
  3463. case 'mission':
  3464. return 'get_pve';
  3465. case 'mission_boss':
  3466. return 'get_missionBoss';
  3467. case 'challenge':
  3468. case 'pvp_manual':
  3469. return 'get_pvpManual';
  3470. case 'grand':
  3471. case 'arena':
  3472. case 'pvp':
  3473. case 'clan_domination':
  3474. return 'get_pvp';
  3475. case 'core':
  3476. return 'get_core';
  3477. default: {
  3478. if (strBattleType.includes('invasion')) {
  3479. return 'get_invasion';
  3480. }
  3481. if (strBattleType.includes('boss')) {
  3482. return 'get_boss';
  3483. }
  3484. if (strBattleType.includes('titan_arena')) {
  3485. return 'get_titanPvpManual';
  3486. }
  3487. return 'get_clanPvp';
  3488. }
  3489. }
  3490. }
  3491. /**
  3492. * Returns the class name of the passed object
  3493. *
  3494. * Возвращает название класса переданного объекта
  3495. */
  3496. function getClass(obj) {
  3497. return {}.toString.call(obj).slice(8, -1);
  3498. }
  3499. /**
  3500. * Calculates the request signature
  3501. *
  3502. * Расчитывает сигнатуру запроса
  3503. */
  3504. this.getSignature = function(headers, data) {
  3505. const sign = {
  3506. signature: '',
  3507. length: 0,
  3508. add: function (text) {
  3509. this.signature += text;
  3510. if (this.length < this.signature.length) {
  3511. this.length = 3 * (this.signature.length + 1) >> 1;
  3512. }
  3513. },
  3514. }
  3515. sign.add(headers["X-Request-Id"]);
  3516. sign.add(':');
  3517. sign.add(headers["X-Auth-Token"]);
  3518. sign.add(':');
  3519. sign.add(headers["X-Auth-Session-Id"]);
  3520. sign.add(':');
  3521. sign.add(data);
  3522. sign.add(':');
  3523. sign.add('LIBRARY-VERSION=1');
  3524. sign.add('UNIQUE-SESSION-ID=' + headers["X-Env-Unique-Session-Id"]);
  3525.  
  3526. return md5(sign.signature);
  3527. }
  3528.  
  3529. class HotkeyManager {
  3530. constructor() {
  3531. if (HotkeyManager.instance) {
  3532. return HotkeyManager.instance;
  3533. }
  3534. this.hotkeys = [];
  3535. document.addEventListener('keydown', this.handleKeyDown.bind(this));
  3536. HotkeyManager.instance = this;
  3537. }
  3538.  
  3539. handleKeyDown(event) {
  3540. const key = event.key.toLowerCase();
  3541. const mods = {
  3542. ctrl: event.ctrlKey,
  3543. alt: event.altKey,
  3544. shift: event.shiftKey,
  3545. };
  3546.  
  3547. this.hotkeys.forEach((hotkey) => {
  3548. if (hotkey.key === key && hotkey.ctrl === mods.ctrl && hotkey.alt === mods.alt && hotkey.shift === mods.shift) {
  3549. hotkey.callback(hotkey);
  3550. }
  3551. });
  3552. }
  3553.  
  3554. add(key, opt = {}, callback) {
  3555. this.hotkeys.push({
  3556. key: key.toLowerCase(),
  3557. callback,
  3558. ctrl: opt.ctrl || false,
  3559. alt: opt.alt || false,
  3560. shift: opt.shift || false,
  3561. });
  3562. }
  3563.  
  3564. remove(key, opt = {}) {
  3565. this.hotkeys = this.hotkeys.filter((hotkey) => {
  3566. return !(
  3567. hotkey.key === key.toLowerCase() &&
  3568. hotkey.ctrl === (opt.ctrl || false) &&
  3569. hotkey.alt === (opt.alt || false) &&
  3570. hotkey.shift === (opt.shift || false)
  3571. );
  3572. });
  3573. }
  3574.  
  3575. static getInst() {
  3576. if (!HotkeyManager.instance) {
  3577. new HotkeyManager();
  3578. }
  3579. return HotkeyManager.instance;
  3580. }
  3581. }
  3582.  
  3583. class MouseClicker {
  3584. constructor(element) {
  3585. if (MouseClicker.instance) {
  3586. return MouseClicker.instance;
  3587. }
  3588. this.element = element;
  3589. this.mouse = {
  3590. bubbles: true,
  3591. cancelable: true,
  3592. clientX: 0,
  3593. clientY: 0,
  3594. };
  3595. this.element.addEventListener('mousemove', this.handleMouseMove.bind(this));
  3596. this.clickInfo = {};
  3597. this.nextTimeoutId = 1;
  3598. MouseClicker.instance = this;
  3599. }
  3600.  
  3601. handleMouseMove(event) {
  3602. this.mouse.clientX = event.clientX;
  3603. this.mouse.clientY = event.clientY;
  3604. }
  3605.  
  3606. click(options) {
  3607. options = options || this.mouse;
  3608. this.element.dispatchEvent(new MouseEvent('mousedown', options));
  3609. this.element.dispatchEvent(new MouseEvent('mouseup', options));
  3610. }
  3611.  
  3612. start(interval = 1000, clickCount = Infinity) {
  3613. const currentMouse = { ...this.mouse };
  3614. const timeoutId = this.nextTimeoutId++;
  3615. let count = 0;
  3616.  
  3617. const clickTimeout = () => {
  3618. this.click(currentMouse);
  3619. count++;
  3620. if (count < clickCount) {
  3621. this.clickInfo[timeoutId].timeout = setTimeout(clickTimeout, interval);
  3622. } else {
  3623. delete this.clickInfo[timeoutId];
  3624. }
  3625. };
  3626.  
  3627. this.clickInfo[timeoutId] = {
  3628. timeout: setTimeout(clickTimeout, interval),
  3629. count: clickCount,
  3630. };
  3631. return timeoutId;
  3632. }
  3633.  
  3634. stop(timeoutId) {
  3635. if (this.clickInfo[timeoutId]) {
  3636. clearTimeout(this.clickInfo[timeoutId].timeout);
  3637. delete this.clickInfo[timeoutId];
  3638. }
  3639. }
  3640.  
  3641. stopAll() {
  3642. for (const timeoutId in this.clickInfo) {
  3643. clearTimeout(this.clickInfo[timeoutId].timeout);
  3644. }
  3645. this.clickInfo = {};
  3646. }
  3647.  
  3648. static getInst(element) {
  3649. if (!MouseClicker.instance) {
  3650. new MouseClicker(element);
  3651. }
  3652. return MouseClicker.instance;
  3653. }
  3654. }
  3655.  
  3656. let extintionsList = [];
  3657. /**
  3658. * Creates an interface
  3659. *
  3660. * Создает интерфейс
  3661. */
  3662. function createInterface() {
  3663. popup.init();
  3664. const { ScriptMenu } = HWHClasses;
  3665. const scriptMenu = ScriptMenu.getInst();
  3666. scriptMenu.init();
  3667. scriptMenu.addHeader(GM_info.script.name, justInfo);
  3668. const versionHeader = scriptMenu.addHeader('v' + GM_info.script.version);
  3669. if (extintionsList.length) {
  3670. versionHeader.title = '';
  3671. versionHeader.style.color = 'red';
  3672. for (const extintion of extintionsList) {
  3673. const { name, ver, author } = extintion;
  3674. versionHeader.title += name + ', v' + ver + ' by ' + author + '\n';
  3675. }
  3676. }
  3677. // AutoClicker
  3678. const hkm = new HotkeyManager();
  3679. const fc = document.getElementById('flash-content') || document.getElementById('game');
  3680. const mc = new MouseClicker(fc);
  3681. function toggleClicker(self, timeout) {
  3682. if (self.onClick) {
  3683. console.log('Останавливаем клики');
  3684. mc.stop(self.onClick);
  3685. self.onClick = false;
  3686. } else {
  3687. console.log('Стартуем клики');
  3688. self.onClick = mc.start(timeout);
  3689. }
  3690. }
  3691. hkm.add('C', { ctrl: true, alt: true }, (self) => {
  3692. console.log('"Ctrl + Alt + C"');
  3693. toggleClicker(self, 20);
  3694. });
  3695. hkm.add('V', { ctrl: true, alt: true }, (self) => {
  3696. console.log('"Ctrl + Alt + V"');
  3697. toggleClicker(self, 100);
  3698. });
  3699. }
  3700.  
  3701. function addExtentionName(name, ver, author) {
  3702. extintionsList.push({
  3703. name,
  3704. ver,
  3705. author,
  3706. });
  3707. }
  3708.  
  3709. function addControls() {
  3710. createInterface();
  3711. const { ScriptMenu } = HWHClasses;
  3712. const scriptMenu = ScriptMenu.getInst();
  3713. const checkboxDetails = scriptMenu.addDetails(I18N('SETTINGS'), 'settings');
  3714. const { checkboxes } = HWHData;
  3715. for (let name in checkboxes) {
  3716. if (checkboxes[name].hide) {
  3717. continue;
  3718. }
  3719. checkboxes[name].cbox = scriptMenu.addCheckbox(checkboxes[name].label, checkboxes[name].title, checkboxDetails);
  3720. /**
  3721. * Getting the state of checkboxes from storage
  3722. * Получаем состояние чекбоксов из storage
  3723. */
  3724. let val = storage.get(name, null);
  3725. if (val != null) {
  3726. checkboxes[name].cbox.checked = val;
  3727. } else {
  3728. storage.set(name, checkboxes[name].default);
  3729. checkboxes[name].cbox.checked = checkboxes[name].default;
  3730. }
  3731. /**
  3732. * Tracing the change event of the checkbox for writing to storage
  3733. * Отсеживание события изменения чекбокса для записи в storage
  3734. */
  3735. checkboxes[name].cbox.dataset['name'] = name;
  3736. checkboxes[name].cbox.addEventListener('change', async function (event) {
  3737. const nameCheckbox = this.dataset['name'];
  3738. /*
  3739. if (this.checked && nameCheckbox == 'cancelBattle') {
  3740. this.checked = false;
  3741. if (await popup.confirm(I18N('MSG_BAN_ATTENTION'), [
  3742. { msg: I18N('BTN_NO_I_AM_AGAINST'), result: true },
  3743. { msg: I18N('BTN_YES_I_AGREE'), result: false },
  3744. ])) {
  3745. return;
  3746. }
  3747. this.checked = true;
  3748. }
  3749. */
  3750. storage.set(nameCheckbox, this.checked);
  3751. })
  3752. }
  3753.  
  3754. const inputDetails = scriptMenu.addDetails(I18N('VALUES'), 'values');
  3755. const { inputs } = HWHData;
  3756. for (let name in inputs) {
  3757. inputs[name].input = scriptMenu.addInputText(inputs[name].title, false, inputDetails);
  3758. /**
  3759. * Get inputText state from storage
  3760. * Получаем состояние inputText из storage
  3761. */
  3762. let val = storage.get(name, null);
  3763. if (val != null) {
  3764. inputs[name].input.value = val;
  3765. } else {
  3766. storage.set(name, inputs[name].default);
  3767. inputs[name].input.value = inputs[name].default;
  3768. }
  3769. /**
  3770. * Tracing a field change event for a record in storage
  3771. * Отсеживание события изменения поля для записи в storage
  3772. */
  3773. inputs[name].input.dataset['name'] = name;
  3774. inputs[name].input.addEventListener('input', function () {
  3775. const inputName = this.dataset['name'];
  3776. let value = +this.value;
  3777. if (!value || Number.isNaN(value)) {
  3778. value = storage.get(inputName, inputs[inputName].default);
  3779. inputs[name].input.value = value;
  3780. }
  3781. storage.set(inputName, value);
  3782. })
  3783. }
  3784. }
  3785.  
  3786. /**
  3787. * Sending a request
  3788. *
  3789. * Отправка запроса
  3790. */
  3791. function send(json, callback, pr) {
  3792. if (typeof json == 'string') {
  3793. json = JSON.parse(json);
  3794. }
  3795. for (const call of json.calls) {
  3796. if (!call?.context?.actionTs) {
  3797. call.context = {
  3798. actionTs: Math.floor(performance.now())
  3799. }
  3800. }
  3801. }
  3802. json = JSON.stringify(json);
  3803. /**
  3804. * We get the headlines of the previous intercepted request
  3805. * Получаем заголовки предыдущего перехваченого запроса
  3806. */
  3807. let headers = lastHeaders;
  3808. /**
  3809. * We increase the header of the query Certifier by 1
  3810. * Увеличиваем заголовок идетификатора запроса на 1
  3811. */
  3812. headers["X-Request-Id"]++;
  3813. /**
  3814. * We calculate the title with the signature
  3815. * Расчитываем заголовок с сигнатурой
  3816. */
  3817. headers["X-Auth-Signature"] = getSignature(headers, json);
  3818. /**
  3819. * Create a new ajax request
  3820. * Создаем новый AJAX запрос
  3821. */
  3822. let xhr = new XMLHttpRequest;
  3823. /**
  3824. * Indicate the previously saved URL for API queries
  3825. * Указываем ранее сохраненный URL для API запросов
  3826. */
  3827. xhr.open('POST', apiUrl, true);
  3828. /**
  3829. * Add the function to the event change event
  3830. * Добавляем функцию к событию смены статуса запроса
  3831. */
  3832. xhr.onreadystatechange = function() {
  3833. /**
  3834. * If the result of the request is obtained, we call the flask function
  3835. * Если результат запроса получен вызываем колбек функцию
  3836. */
  3837. if(xhr.readyState == 4) {
  3838. callback(xhr.response, pr);
  3839. }
  3840. };
  3841. /**
  3842. * Indicate the type of request
  3843. * Указываем тип запроса
  3844. */
  3845. xhr.responseType = 'json';
  3846. /**
  3847. * We set the request headers
  3848. * Задаем заголовки запроса
  3849. */
  3850. for(let nameHeader in headers) {
  3851. let head = headers[nameHeader];
  3852. xhr.setRequestHeader(nameHeader, head);
  3853. }
  3854. /**
  3855. * Sending a request
  3856. * Отправляем запрос
  3857. */
  3858. xhr.send(json);
  3859. }
  3860.  
  3861. let hideTimeoutProgress = 0;
  3862. /**
  3863. * Hide progress
  3864. *
  3865. * Скрыть прогресс
  3866. */
  3867. function hideProgress(timeout) {
  3868. const { ScriptMenu } = HWHClasses;
  3869. const scriptMenu = ScriptMenu.getInst();
  3870. timeout = timeout || 0;
  3871. clearTimeout(hideTimeoutProgress);
  3872. hideTimeoutProgress = setTimeout(function () {
  3873. scriptMenu.setStatus('');
  3874. }, timeout);
  3875. }
  3876. /**
  3877. * Progress display
  3878. *
  3879. * Отображение прогресса
  3880. */
  3881. function setProgress(text, hide, onclick) {
  3882. const { ScriptMenu } = HWHClasses;
  3883. const scriptMenu = ScriptMenu.getInst();
  3884. scriptMenu.setStatus(text, onclick);
  3885. hide = hide || false;
  3886. if (hide) {
  3887. hideProgress(3000);
  3888. }
  3889. }
  3890.  
  3891. /**
  3892. * Progress added
  3893. *
  3894. * Дополнение прогресса
  3895. */
  3896. function addProgress(text) {
  3897. const { ScriptMenu } = HWHClasses;
  3898. const scriptMenu = ScriptMenu.getInst();
  3899. scriptMenu.addStatus(text);
  3900. }
  3901.  
  3902. /**
  3903. * Returns the timer value depending on the subscription
  3904. *
  3905. * Возвращает значение таймера в зависимости от подписки
  3906. */
  3907. function getTimer(time, div) {
  3908. let speedDiv = 5;
  3909. if (subEndTime < Date.now()) {
  3910. speedDiv = div || 1.5;
  3911. }
  3912. return Math.max(Math.ceil(time / speedDiv + 1.5), 4);
  3913. }
  3914.  
  3915. function startSlave() {
  3916. const { slaveFixBattle } = HWHClasses;
  3917. const sFix = new slaveFixBattle();
  3918. sFix.wsStart();
  3919. }
  3920.  
  3921. this.testFuntions = {
  3922. hideProgress,
  3923. setProgress,
  3924. addProgress,
  3925. masterFix: false,
  3926. startSlave,
  3927. };
  3928.  
  3929. this.HWHFuncs = {
  3930. send,
  3931. I18N,
  3932. isChecked,
  3933. getInput,
  3934. copyText,
  3935. confShow,
  3936. hideProgress,
  3937. setProgress,
  3938. addProgress,
  3939. getTimer,
  3940. addExtentionName,
  3941. getUserInfo,
  3942. setIsCancalBattle,
  3943. random,
  3944. };
  3945.  
  3946. this.HWHClasses = {
  3947. checkChangeSend,
  3948. checkChangeResponse,
  3949. };
  3950.  
  3951. this.HWHData = {
  3952. i18nLangData,
  3953. checkboxes,
  3954. inputs,
  3955. buttons,
  3956. invasionInfo,
  3957. invasionDataPacks,
  3958. };
  3959.  
  3960. /**
  3961. * Calculates HASH MD5 from string
  3962. *
  3963. * Расчитывает HASH MD5 из строки
  3964. *
  3965. * [js-md5]{@link https://github.com/emn178/js-md5}
  3966. *
  3967. * @namespace md5
  3968. * @version 0.7.3
  3969. * @author Chen, Yi-Cyuan [emn178@gmail.com]
  3970. * @copyright Chen, Yi-Cyuan 2014-2017
  3971. * @license MIT
  3972. */
  3973. !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 _}))}();
  3974.  
  3975. class Caller {
  3976. static globalHooks = {
  3977. onError: null,
  3978. };
  3979.  
  3980. constructor(calls = null) {
  3981. this.calls = [];
  3982. this.results = {};
  3983. this.sideResults = {};
  3984. if (calls) {
  3985. this.add(calls);
  3986. }
  3987. }
  3988.  
  3989. static setGlobalHook(event, callback) {
  3990. if (this.globalHooks[event] !== undefined) {
  3991. this.globalHooks[event] = callback;
  3992. } else {
  3993. throw new Error(`Unknown event: ${event}`);
  3994. }
  3995. }
  3996.  
  3997. addCall(call) {
  3998. const { name = call, args = {} } = typeof call === 'object' ? call : { name: call };
  3999. this.calls.push({ name, args });
  4000. return this;
  4001. }
  4002.  
  4003. add(name) {
  4004. if (Array.isArray(name)) {
  4005. name.forEach((call) => this.addCall(call));
  4006. } else {
  4007. this.addCall(name);
  4008. }
  4009. return this;
  4010. }
  4011.  
  4012. handleError(error) {
  4013. const errorName = error.name;
  4014. const errorDescription = error.description;
  4015.  
  4016. if (Caller.globalHooks.onError) {
  4017. const shouldThrow = Caller.globalHooks.onError(error);
  4018. if (shouldThrow === false) {
  4019. return;
  4020. }
  4021. }
  4022.  
  4023. if (error.call) {
  4024. const callInfo = error.call;
  4025. throw new Error(`${errorName} in ${callInfo.name}: ${errorDescription}\n` + `Args: ${JSON.stringify(callInfo.args)}\n`);
  4026. } else if (errorName === 'common\\rpc\\exception\\InvalidRequest') {
  4027. throw new Error(`Invalid request: ${errorDescription}`);
  4028. } else {
  4029. throw new Error(`Unknown error: ${errorName} - ${errorDescription}`);
  4030. }
  4031. }
  4032.  
  4033. async send() {
  4034. if (!this.calls.length) {
  4035. throw new Error('No calls to send.');
  4036. }
  4037.  
  4038. const identToNameMap = {};
  4039. const callsWithIdent = this.calls.map((call, index) => {
  4040. const ident = this.calls.length === 1 ? 'body' : `group_${index}_body`;
  4041. identToNameMap[ident] = call.name;
  4042. return { ...call, ident };
  4043. });
  4044.  
  4045. try {
  4046. const response = await Send({ calls: callsWithIdent });
  4047.  
  4048. if (response.error) {
  4049. this.handleError(response.error);
  4050. }
  4051.  
  4052. if (!response.results) {
  4053. throw new Error('Invalid response format: missing "results" field');
  4054. }
  4055.  
  4056. response.results.forEach((result) => {
  4057. const name = identToNameMap[result.ident];
  4058. if (!this.results[name]) {
  4059. this.results[name] = [];
  4060. this.sideResults[name] = [];
  4061. }
  4062. this.results[name].push(result.result.response);
  4063. const sideResults = {};
  4064. for (const key of Object.keys(result.result)) {
  4065. if (key === 'response') continue;
  4066. sideResults[key] = result.result[key];
  4067. }
  4068. this.sideResults[name].push(sideResults);
  4069. });
  4070. } catch (error) {
  4071. throw error;
  4072. }
  4073. return this;
  4074. }
  4075.  
  4076. result(name, forceArray = false) {
  4077. const results = name ? this.results[name] || [] : Object.values(this.results).flat();
  4078. return forceArray || results.length !== 1 ? results : results[0];
  4079. }
  4080.  
  4081. sideResult(name, forceArray = false) {
  4082. const results = name ? this.sideResults[name] || [] : Object.values(this.sideResults).flat();
  4083. return forceArray || results.length !== 1 ? results : results[0];
  4084. }
  4085.  
  4086. async execute(name) {
  4087. try {
  4088. await this.send();
  4089. return this.result(name);
  4090. } catch (error) {
  4091. throw error;
  4092. }
  4093. }
  4094.  
  4095. clear() {
  4096. this.calls = [];
  4097. this.results = {};
  4098. return this;
  4099. }
  4100.  
  4101. isEmpty() {
  4102. return this.calls.length === 0 && Object.keys(this.results).length === 0;
  4103. }
  4104.  
  4105. static async send(calls) {
  4106. return new Caller(calls).execute();
  4107. }
  4108. }
  4109.  
  4110. this.Caller = Caller;
  4111.  
  4112. /*
  4113. // Примеры использования
  4114. (async () => {
  4115. // Короткий вызов
  4116. await new Caller('inventoryGet').execute();
  4117. // Простой вызов
  4118. let result = await new Caller().add('inventoryGet').execute();
  4119. console.log('Inventory Get Result:', result);
  4120.  
  4121. // Сложный вызов
  4122. let caller = new Caller();
  4123. await caller
  4124. .add([
  4125. {
  4126. name: 'inventoryGet',
  4127. args: {},
  4128. },
  4129. {
  4130. name: 'heroGetAll',
  4131. args: {},
  4132. },
  4133. ])
  4134. .send();
  4135. console.log('Inventory Get Result:', caller.result('inventoryGet'));
  4136. console.log('Hero Get All Result:', caller.result('heroGetAll'));
  4137.  
  4138. // Очистка всех данных
  4139. caller.clear();
  4140. })();
  4141. */
  4142.  
  4143. /**
  4144. * Script for beautiful dialog boxes
  4145. *
  4146. * Скрипт для красивых диалоговых окошек
  4147. */
  4148. const popup = new (function () {
  4149. this.popUp,
  4150. this.downer,
  4151. this.middle,
  4152. this.msgText,
  4153. this.buttons = [];
  4154. this.checkboxes = [];
  4155. this.dialogPromice = null;
  4156. this.isInit = false;
  4157.  
  4158. this.init = function () {
  4159. if (this.isInit) {
  4160. return;
  4161. }
  4162. addStyle();
  4163. addBlocks();
  4164. addEventListeners();
  4165. this.isInit = true;
  4166. }
  4167.  
  4168. const addEventListeners = () => {
  4169. document.addEventListener('keyup', (e) => {
  4170. if (e.key == 'Escape') {
  4171. if (this.dialogPromice) {
  4172. const { func, result } = this.dialogPromice;
  4173. this.dialogPromice = null;
  4174. popup.hide();
  4175. func(result);
  4176. }
  4177. }
  4178. });
  4179. }
  4180.  
  4181. const addStyle = () => {
  4182. let style = document.createElement('style');
  4183. style.innerText = `
  4184. .PopUp_ {
  4185. position: fixed;
  4186. left: 50%;
  4187. top: 50%;
  4188. transform: translate(-50%, -50%);
  4189. min-width: 300px;
  4190. max-width: 80%;
  4191. max-height: 80%;
  4192. background-color: #190e08e6;
  4193. z-index: 10001;
  4194. border: 3px #ce9767 solid;
  4195. border-radius: 10px;
  4196. display: flex;
  4197. flex-direction: column;
  4198. justify-content: space-around;
  4199. padding: 15px 9px;
  4200. box-sizing: border-box;
  4201. }
  4202.  
  4203. .PopUp_back {
  4204. position: absolute;
  4205. background-color: #00000066;
  4206. width: 100%;
  4207. height: 100%;
  4208. z-index: 10000;
  4209. top: 0;
  4210. left: 0;
  4211. }
  4212.  
  4213. .PopUp_close {
  4214. width: 40px;
  4215. height: 40px;
  4216. position: absolute;
  4217. right: -18px;
  4218. top: -18px;
  4219. border: 3px solid #c18550;
  4220. border-radius: 20px;
  4221. background: radial-gradient(circle, rgba(190,30,35,1) 0%, rgba(0,0,0,1) 100%);
  4222. background-position-y: 3px;
  4223. box-shadow: -1px 1px 3px black;
  4224. cursor: pointer;
  4225. box-sizing: border-box;
  4226. }
  4227.  
  4228. .PopUp_close:hover {
  4229. filter: brightness(1.2);
  4230. }
  4231.  
  4232. .PopUp_crossClose {
  4233. width: 100%;
  4234. height: 100%;
  4235. background-size: 65%;
  4236. background-position: center;
  4237. background-repeat: no-repeat;
  4238. 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")
  4239. }
  4240.  
  4241. .PopUp_blocks {
  4242. width: 100%;
  4243. height: 50%;
  4244. display: flex;
  4245. justify-content: space-evenly;
  4246. align-items: center;
  4247. flex-wrap: wrap;
  4248. justify-content: center;
  4249. }
  4250.  
  4251. .PopUp_blocks:last-child {
  4252. margin-top: 25px;
  4253. }
  4254.  
  4255. .PopUp_buttons {
  4256. display: flex;
  4257. margin: 7px 10px;
  4258. flex-direction: column;
  4259. }
  4260.  
  4261. .PopUp_button {
  4262. background-color: #52A81C;
  4263. border-radius: 5px;
  4264. box-shadow: inset 0px -4px 10px, inset 0px 3px 2px #99fe20, 0px 0px 4px, 0px -3px 1px #d7b275, 0px 0px 0px 3px #ce9767;
  4265. cursor: pointer;
  4266. padding: 4px 12px 6px;
  4267. }
  4268.  
  4269. .PopUp_input {
  4270. text-align: center;
  4271. font-size: 16px;
  4272. height: 27px;
  4273. border: 1px solid #cf9250;
  4274. border-radius: 9px 9px 0px 0px;
  4275. background: transparent;
  4276. color: #fce1ac;
  4277. padding: 1px 10px;
  4278. box-sizing: border-box;
  4279. box-shadow: 0px 0px 4px, 0px 0px 0px 3px #ce9767;
  4280. }
  4281.  
  4282. .PopUp_checkboxes {
  4283. display: flex;
  4284. flex-direction: column;
  4285. margin: 15px 15px -5px 15px;
  4286. align-items: flex-start;
  4287. }
  4288.  
  4289. .PopUp_ContCheckbox {
  4290. margin: 2px 0px;
  4291. }
  4292.  
  4293. .PopUp_checkbox {
  4294. position: absolute;
  4295. z-index: -1;
  4296. opacity: 0;
  4297. }
  4298. .PopUp_checkbox+label {
  4299. display: inline-flex;
  4300. align-items: center;
  4301. user-select: none;
  4302.  
  4303. font-size: 15px;
  4304. font-family: sans-serif;
  4305. font-weight: 600;
  4306. font-stretch: condensed;
  4307. letter-spacing: 1px;
  4308. color: #fce1ac;
  4309. text-shadow: 0px 0px 1px;
  4310. }
  4311. .PopUp_checkbox+label::before {
  4312. content: '';
  4313. display: inline-block;
  4314. width: 20px;
  4315. height: 20px;
  4316. border: 1px solid #cf9250;
  4317. border-radius: 7px;
  4318. margin-right: 7px;
  4319. }
  4320. .PopUp_checkbox:checked+label::before {
  4321. 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");
  4322. }
  4323.  
  4324. .PopUp_input::placeholder {
  4325. color: #fce1ac75;
  4326. }
  4327.  
  4328. .PopUp_input:focus {
  4329. outline: 0;
  4330. }
  4331.  
  4332. .PopUp_input + .PopUp_button {
  4333. border-radius: 0px 0px 5px 5px;
  4334. padding: 2px 18px 5px;
  4335. }
  4336.  
  4337. .PopUp_button:hover {
  4338. filter: brightness(1.2);
  4339. }
  4340.  
  4341. .PopUp_button:active {
  4342. box-shadow: inset 0px 5px 10px, inset 0px 1px 2px #99fe20, 0px 0px 4px, 0px -3px 1px #d7b275, 0px 0px 0px 3px #ce9767;
  4343. }
  4344.  
  4345. .PopUp_text {
  4346. font-size: 22px;
  4347. font-family: sans-serif;
  4348. font-weight: 600;
  4349. font-stretch: condensed;
  4350. letter-spacing: 1px;
  4351. text-align: center;
  4352. }
  4353.  
  4354. .PopUp_buttonText {
  4355. color: #E4FF4C;
  4356. text-shadow: 0px 1px 2px black;
  4357. }
  4358.  
  4359. .PopUp_msgText {
  4360. color: #FDE5B6;
  4361. text-shadow: 0px 0px 2px;
  4362. }
  4363.  
  4364. .PopUp_hideBlock {
  4365. display: none;
  4366. }
  4367. `;
  4368. document.head.appendChild(style);
  4369. }
  4370.  
  4371. const addBlocks = () => {
  4372. this.back = document.createElement('div');
  4373. this.back.classList.add('PopUp_back');
  4374. this.back.classList.add('PopUp_hideBlock');
  4375. document.body.append(this.back);
  4376.  
  4377. this.popUp = document.createElement('div');
  4378. this.popUp.classList.add('PopUp_');
  4379. this.back.append(this.popUp);
  4380.  
  4381. let upper = document.createElement('div')
  4382. upper.classList.add('PopUp_blocks');
  4383. this.popUp.append(upper);
  4384.  
  4385. this.middle = document.createElement('div')
  4386. this.middle.classList.add('PopUp_blocks');
  4387. this.middle.classList.add('PopUp_checkboxes');
  4388. this.popUp.append(this.middle);
  4389.  
  4390. this.downer = document.createElement('div')
  4391. this.downer.classList.add('PopUp_blocks');
  4392. this.popUp.append(this.downer);
  4393.  
  4394. this.msgText = document.createElement('div');
  4395. this.msgText.classList.add('PopUp_text', 'PopUp_msgText');
  4396. upper.append(this.msgText);
  4397. }
  4398.  
  4399. this.showBack = function () {
  4400. this.back.classList.remove('PopUp_hideBlock');
  4401. }
  4402.  
  4403. this.hideBack = function () {
  4404. this.back.classList.add('PopUp_hideBlock');
  4405. }
  4406.  
  4407. this.show = function () {
  4408. if (this.checkboxes.length) {
  4409. this.middle.classList.remove('PopUp_hideBlock');
  4410. }
  4411. this.showBack();
  4412. this.popUp.classList.remove('PopUp_hideBlock');
  4413. }
  4414.  
  4415. this.hide = function () {
  4416. this.hideBack();
  4417. this.popUp.classList.add('PopUp_hideBlock');
  4418. }
  4419.  
  4420. this.addAnyButton = (option) => {
  4421. const contButton = document.createElement('div');
  4422. contButton.classList.add('PopUp_buttons');
  4423. this.downer.append(contButton);
  4424.  
  4425. let inputField = {
  4426. value: option.result || option.default
  4427. }
  4428. if (option.isInput) {
  4429. inputField = document.createElement('input');
  4430. inputField.type = 'text';
  4431. if (option.placeholder) {
  4432. inputField.placeholder = option.placeholder;
  4433. }
  4434. if (option.default) {
  4435. inputField.value = option.default;
  4436. }
  4437. inputField.classList.add('PopUp_input');
  4438. contButton.append(inputField);
  4439. }
  4440.  
  4441. const button = document.createElement('div');
  4442. button.classList.add('PopUp_button');
  4443. button.title = option.title || '';
  4444. contButton.append(button);
  4445.  
  4446. const buttonText = document.createElement('div');
  4447. buttonText.classList.add('PopUp_text', 'PopUp_buttonText');
  4448. buttonText.innerHTML = option.msg;
  4449. button.append(buttonText);
  4450.  
  4451. return { button, contButton, inputField };
  4452. }
  4453.  
  4454. this.addCloseButton = () => {
  4455. let button = document.createElement('div')
  4456. button.classList.add('PopUp_close');
  4457. this.popUp.append(button);
  4458.  
  4459. let crossClose = document.createElement('div')
  4460. crossClose.classList.add('PopUp_crossClose');
  4461. button.append(crossClose);
  4462.  
  4463. return { button, contButton: button };
  4464. }
  4465.  
  4466. this.addButton = (option, buttonClick) => {
  4467.  
  4468. const { button, contButton, inputField } = option.isClose ? this.addCloseButton() : this.addAnyButton(option);
  4469. if (option.isClose) {
  4470. this.dialogPromice = { func: buttonClick, result: option.result };
  4471. }
  4472. button.addEventListener('click', () => {
  4473. let result = '';
  4474. if (option.isInput) {
  4475. result = inputField.value;
  4476. }
  4477. if (option.isClose || option.isCancel) {
  4478. this.dialogPromice = null;
  4479. }
  4480. buttonClick(result);
  4481. });
  4482.  
  4483. this.buttons.push(contButton);
  4484. }
  4485.  
  4486. this.clearButtons = () => {
  4487. while (this.buttons.length) {
  4488. this.buttons.pop().remove();
  4489. }
  4490. }
  4491.  
  4492. this.addCheckBox = (checkBox) => {
  4493. const contCheckbox = document.createElement('div');
  4494. contCheckbox.classList.add('PopUp_ContCheckbox');
  4495. this.middle.append(contCheckbox);
  4496.  
  4497. const checkbox = document.createElement('input');
  4498. checkbox.type = 'checkbox';
  4499. checkbox.id = 'PopUpCheckbox' + this.checkboxes.length;
  4500. checkbox.dataset.name = checkBox.name;
  4501. checkbox.checked = checkBox.checked;
  4502. checkbox.label = checkBox.label;
  4503. checkbox.title = checkBox.title || '';
  4504. checkbox.classList.add('PopUp_checkbox');
  4505. contCheckbox.appendChild(checkbox)
  4506.  
  4507. const checkboxLabel = document.createElement('label');
  4508. checkboxLabel.innerText = checkBox.label;
  4509. checkboxLabel.title = checkBox.title || '';
  4510. checkboxLabel.setAttribute('for', checkbox.id);
  4511. contCheckbox.appendChild(checkboxLabel);
  4512.  
  4513. this.checkboxes.push(checkbox);
  4514. }
  4515.  
  4516. this.clearCheckBox = () => {
  4517. this.middle.classList.add('PopUp_hideBlock');
  4518. while (this.checkboxes.length) {
  4519. this.checkboxes.pop().parentNode.remove();
  4520. }
  4521. }
  4522.  
  4523. this.setMsgText = (text) => {
  4524. this.msgText.innerHTML = text;
  4525. }
  4526.  
  4527. this.getCheckBoxes = () => {
  4528. const checkBoxes = [];
  4529.  
  4530. for (const checkBox of this.checkboxes) {
  4531. checkBoxes.push({
  4532. name: checkBox.dataset.name,
  4533. label: checkBox.label,
  4534. checked: checkBox.checked
  4535. });
  4536. }
  4537.  
  4538. return checkBoxes;
  4539. }
  4540.  
  4541. this.confirm = async (msg, buttOpt, checkBoxes = []) => {
  4542. if (!this.isInit) {
  4543. this.init();
  4544. }
  4545. this.clearButtons();
  4546. this.clearCheckBox();
  4547. return new Promise((complete, failed) => {
  4548. this.setMsgText(msg);
  4549. if (!buttOpt) {
  4550. buttOpt = [{ msg: 'Ok', result: true, isInput: false }];
  4551. }
  4552. for (const checkBox of checkBoxes) {
  4553. this.addCheckBox(checkBox);
  4554. }
  4555. for (let butt of buttOpt) {
  4556. this.addButton(butt, (result) => {
  4557. result = result || butt.result;
  4558. complete(result);
  4559. popup.hide();
  4560. });
  4561. if (butt.isCancel) {
  4562. this.dialogPromice = { func: complete, result: butt.result };
  4563. }
  4564. }
  4565. this.show();
  4566. });
  4567. }
  4568. });
  4569.  
  4570. this.HWHFuncs.popup = popup;
  4571.  
  4572. /**
  4573. * Миксин EventEmitter
  4574. * @param {Class} BaseClass Базовый класс (по умолчанию Object)
  4575. * @returns {Class} Класс с методами EventEmitter
  4576. */
  4577. const EventEmitterMixin = (BaseClass = Object) =>
  4578. class EventEmitter extends BaseClass {
  4579. constructor(...args) {
  4580. super(...args);
  4581. this._events = new Map();
  4582. }
  4583.  
  4584. /**
  4585. * Подписаться на событие
  4586. * @param {string} event Имя события
  4587. * @param {function} listener Функция-обработчик
  4588. * @returns {this} Возвращает экземпляр для чейнинга
  4589. */
  4590. on(event, listener) {
  4591. if (typeof listener !== 'function') {
  4592. throw new TypeError('Listener must be a function');
  4593. }
  4594.  
  4595. if (!this._events.has(event)) {
  4596. this._events.set(event, new Set());
  4597. }
  4598. this._events.get(event).add(listener);
  4599. return this;
  4600. }
  4601.  
  4602. /**
  4603. * Отписаться от события
  4604. * @param {string} event Имя события
  4605. * @param {function} listener Функция-обработчик
  4606. * @returns {this} Возвращает экземпляр для чейнинга
  4607. */
  4608. off(event, listener) {
  4609. if (this._events.has(event)) {
  4610. const listeners = this._events.get(event);
  4611. listeners.delete(listener);
  4612. if (listeners.size === 0) {
  4613. this._events.delete(event);
  4614. }
  4615. }
  4616. return this;
  4617. }
  4618.  
  4619. /**
  4620. * Вызвать событие
  4621. * @param {string} event Имя события
  4622. * @param {...any} args Аргументы для обработчиков
  4623. * @returns {boolean} Было ли событие обработано
  4624. */
  4625. emit(event, ...args) {
  4626. if (!this._events.has(event)) return false;
  4627. const listeners = new Set(this._events.get(event));
  4628. listeners.forEach((listener) => {
  4629. try {
  4630. listener.apply(this, args);
  4631. } catch (e) {
  4632. console.error(`Error in event handler for "${event}":`, e);
  4633. }
  4634. });
  4635.  
  4636. return true;
  4637. }
  4638.  
  4639. /**
  4640. * Подписаться на событие один раз
  4641. * @param {string} event Имя события
  4642. * @param {function} listener Функция-обработчик
  4643. * @returns {this} Возвращает экземпляр для чейнинга
  4644. */
  4645. once(event, listener) {
  4646. const onceWrapper = (...args) => {
  4647. this.off(event, onceWrapper);
  4648. listener.apply(this, args);
  4649. };
  4650. return this.on(event, onceWrapper);
  4651. }
  4652.  
  4653. /**
  4654. * Удалить все обработчики для события
  4655. * @param {string} [event] Имя события (если не указано - очистить все)
  4656. * @returns {this} Возвращает экземпляр для чейнинга
  4657. */
  4658. removeAllListeners(event) {
  4659. if (event) {
  4660. this._events.delete(event);
  4661. } else {
  4662. this._events.clear();
  4663. }
  4664. return this;
  4665. }
  4666.  
  4667. /**
  4668. * Получить количество обработчиков для события
  4669. * @param {string} event Имя события
  4670. * @returns {number} Количество обработчиков
  4671. */
  4672. listenerCount(event) {
  4673. return this._events.has(event) ? this._events.get(event).size : 0;
  4674. }
  4675. };
  4676.  
  4677. this.HWHFuncs.EventEmitterMixin = EventEmitterMixin;
  4678.  
  4679. /**
  4680. * Script control panel
  4681. *
  4682. * Панель управления скриптом
  4683. */
  4684. class ScriptMenu extends EventEmitterMixin() {
  4685. constructor() {
  4686. if (ScriptMenu.instance) {
  4687. return ScriptMenu.instance;
  4688. }
  4689. super();
  4690. this.mainMenu = null;
  4691. this.buttons = [];
  4692. this.checkboxes = [];
  4693. this.option = {
  4694. showMenu: true,
  4695. showDetails: {},
  4696. };
  4697. ScriptMenu.instance = this;
  4698. return this;
  4699. }
  4700.  
  4701. static getInst() {
  4702. if (!ScriptMenu.instance) {
  4703. new ScriptMenu();
  4704. }
  4705. return ScriptMenu.instance;
  4706. }
  4707.  
  4708. init(option = {}) {
  4709. this.emit('beforeInit', option);
  4710. this.option = Object.assign(this.option, option);
  4711. const saveOption = this.loadSaveOption();
  4712. this.option = Object.assign(this.option, saveOption);
  4713. this.addStyle();
  4714. this.addBlocks();
  4715. this.emit('afterInit', option);
  4716. }
  4717.  
  4718. addStyle() {
  4719. const style = document.createElement('style');
  4720. style.innerText = `
  4721. .scriptMenu_status {
  4722. position: absolute;
  4723. z-index: 10001;
  4724. top: -1px;
  4725. left: 30%;
  4726. cursor: pointer;
  4727. border-radius: 0px 0px 10px 10px;
  4728. background: #190e08e6;
  4729. border: 1px #ce9767 solid;
  4730. font-size: 18px;
  4731. font-family: sans-serif;
  4732. font-weight: 600;
  4733. font-stretch: condensed;
  4734. letter-spacing: 1px;
  4735. color: #fce1ac;
  4736. text-shadow: 0px 0px 1px;
  4737. transition: 0.5s;
  4738. padding: 2px 10px 3px;
  4739. }
  4740. .scriptMenu_statusHide {
  4741. top: -35px;
  4742. height: 30px;
  4743. overflow: hidden;
  4744. }
  4745. .scriptMenu_label {
  4746. position: absolute;
  4747. top: 30%;
  4748. left: -4px;
  4749. z-index: 9999;
  4750. cursor: pointer;
  4751. width: 30px;
  4752. height: 30px;
  4753. background: radial-gradient(circle, #47a41b 0%, #1a2f04 100%);
  4754. border: 1px solid #1a2f04;
  4755. border-radius: 5px;
  4756. box-shadow:
  4757. inset 0px 2px 4px #83ce26,
  4758. inset 0px -4px 6px #1a2f04,
  4759. 0px 0px 2px black,
  4760. 0px 0px 0px 2px #ce9767;
  4761. }
  4762. .scriptMenu_label:hover {
  4763. filter: brightness(1.2);
  4764. }
  4765. .scriptMenu_arrowLabel {
  4766. width: 100%;
  4767. height: 100%;
  4768. background-size: 75%;
  4769. background-position: center;
  4770. background-repeat: no-repeat;
  4771. 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");
  4772. box-shadow: 0px 1px 2px #000;
  4773. border-radius: 5px;
  4774. filter: drop-shadow(0px 1px 2px #000D);
  4775. }
  4776. .scriptMenu_main {
  4777. position: absolute;
  4778. max-width: 285px;
  4779. z-index: 9999;
  4780. top: 50%;
  4781. transform: translateY(-40%);
  4782. background: #190e08e6;
  4783. border: 1px #ce9767 solid;
  4784. border-radius: 0px 10px 10px 0px;
  4785. border-left: none;
  4786. box-sizing: border-box;
  4787. font-size: 15px;
  4788. font-family: sans-serif;
  4789. font-weight: 600;
  4790. font-stretch: condensed;
  4791. letter-spacing: 1px;
  4792. color: #fce1ac;
  4793. text-shadow: 0px 0px 1px;
  4794. transition: 1s;
  4795. }
  4796. .scriptMenu_conteiner {
  4797. max-height: 80vh;
  4798. overflow: scroll;
  4799. scrollbar-width: none; /* Для Firefox */
  4800. -ms-overflow-style: none; /* Для Internet Explorer и Edge */
  4801. display: flex;
  4802. flex-direction: column;
  4803. flex-wrap: nowrap;
  4804. padding: 5px 10px 5px 5px;
  4805. }
  4806. .scriptMenu_conteiner::-webkit-scrollbar {
  4807. display: none; /* Для Chrome, Safari и Opera */
  4808. }
  4809. .scriptMenu_showMenu {
  4810. display: none;
  4811. }
  4812. .scriptMenu_showMenu:checked~.scriptMenu_main {
  4813. left: 0px;
  4814. }
  4815. .scriptMenu_showMenu:not(:checked)~.scriptMenu_main {
  4816. left: -300px;
  4817. }
  4818. .scriptMenu_divInput {
  4819. margin: 2px;
  4820. }
  4821. .scriptMenu_divInputText {
  4822. margin: 2px;
  4823. align-self: center;
  4824. display: flex;
  4825. }
  4826. .scriptMenu_checkbox {
  4827. position: absolute;
  4828. z-index: -1;
  4829. opacity: 0;
  4830. }
  4831. .scriptMenu_checkbox+label {
  4832. display: inline-flex;
  4833. align-items: center;
  4834. user-select: none;
  4835. }
  4836. .scriptMenu_checkbox+label::before {
  4837. content: '';
  4838. display: inline-block;
  4839. width: 20px;
  4840. height: 20px;
  4841. border: 1px solid #cf9250;
  4842. border-radius: 7px;
  4843. margin-right: 7px;
  4844. }
  4845. .scriptMenu_checkbox:checked+label::before {
  4846. 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");
  4847. }
  4848. .scriptMenu_close {
  4849. width: 40px;
  4850. height: 40px;
  4851. position: absolute;
  4852. right: -18px;
  4853. top: -18px;
  4854. border: 3px solid #c18550;
  4855. border-radius: 20px;
  4856. background: radial-gradient(circle, rgba(190,30,35,1) 0%, rgba(0,0,0,1) 100%);
  4857. background-position-y: 3px;
  4858. box-shadow: -1px 1px 3px black;
  4859. cursor: pointer;
  4860. box-sizing: border-box;
  4861. }
  4862. .scriptMenu_close:hover {
  4863. filter: brightness(1.2);
  4864. }
  4865. .scriptMenu_crossClose {
  4866. width: 100%;
  4867. height: 100%;
  4868. background-size: 65%;
  4869. background-position: center;
  4870. background-repeat: no-repeat;
  4871. 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")
  4872. }
  4873. .scriptMenu_button {
  4874. user-select: none;
  4875. cursor: pointer;
  4876. padding: 5px 14px 8px;
  4877. }
  4878. .scriptMenu_button:hover {
  4879. filter: brightness(1.2);
  4880. }
  4881. .scriptMenu_buttonText {
  4882. color: #fce5b7;
  4883. text-shadow: 0px 1px 2px black;
  4884. text-align: center;
  4885. }
  4886. .scriptMenu_header {
  4887. text-align: center;
  4888. align-self: center;
  4889. font-size: 15px;
  4890. margin: 0px 15px;
  4891. }
  4892. .scriptMenu_header a {
  4893. color: #fce5b7;
  4894. text-decoration: none;
  4895. }
  4896. .scriptMenu_InputText {
  4897. text-align: center;
  4898. width: 130px;
  4899. height: 24px;
  4900. border: 1px solid #cf9250;
  4901. border-radius: 9px;
  4902. background: transparent;
  4903. color: #fce1ac;
  4904. padding: 0px 10px;
  4905. box-sizing: border-box;
  4906. }
  4907. .scriptMenu_InputText:focus {
  4908. filter: brightness(1.2);
  4909. outline: 0;
  4910. }
  4911. .scriptMenu_InputText::placeholder {
  4912. color: #fce1ac75;
  4913. }
  4914. .scriptMenu_Summary {
  4915. cursor: pointer;
  4916. margin-left: 7px;
  4917. }
  4918. .scriptMenu_Details {
  4919. align-self: center;
  4920. }
  4921. .scriptMenu_buttonGroup {
  4922. display: flex;
  4923. justify-content: center;
  4924. user-select: none;
  4925. cursor: pointer;
  4926. padding: 0;
  4927. margin: 3px 0;
  4928. }
  4929. .scriptMenu_buttonGroup .scriptMenu_button {
  4930. width: 100%;
  4931. padding: 5px 8px 8px;
  4932. }
  4933. .scriptMenu_mainButton {
  4934. border-radius: 5px;
  4935. margin: 3px 0;
  4936. }
  4937. .scriptMenu_combineButtonLeft {
  4938. border-top-left-radius: 5px;
  4939. border-bottom-left-radius: 5px;
  4940. margin-right: 2px;
  4941. }
  4942. .scriptMenu_combineButtonCenter {
  4943. border-radius: 0px;
  4944. margin-right: 2px;
  4945. }
  4946. .scriptMenu_combineButtonRight {
  4947. border-top-right-radius: 5px;
  4948. border-bottom-right-radius: 5px;
  4949. }
  4950. .scriptMenu_beigeButton {
  4951. border: 1px solid #442901;
  4952. background: radial-gradient(circle, rgba(165,120,56,1) 80%, rgba(0,0,0,1) 110%);
  4953. box-shadow: inset 0px 2px 4px #e9b282, inset 0px -4px 6px #442901, inset 0px 1px 6px #442901, inset 0px 0px 6px, 0px 0px 2px black, 0px 0px 0px 1px #ce9767;
  4954. }
  4955. .scriptMenu_beigeButton:active {
  4956. box-shadow: inset 0px 4px 6px #442901, inset 0px 4px 6px #442901, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 1px #ce9767;
  4957. }
  4958. .scriptMenu_greenButton {
  4959. border: 1px solid #1a2f04;
  4960. background: radial-gradient(circle, #47a41b 0%, #1a2f04 150%);
  4961. box-shadow: inset 0px 2px 4px #83ce26, inset 0px -4px 6px #1a2f04, 0px 0px 2px black, 0px 0px 0px 1px #ce9767;
  4962. }
  4963. .scriptMenu_greenButton:active {
  4964. box-shadow: inset 0px 4px 6px #1a2f04, inset 0px 4px 6px #1a2f04, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 1px #ce9767;
  4965. }
  4966. .scriptMenu_redButton {
  4967. border: 1px solid #440101;
  4968. background: radial-gradient(circle, rgb(198, 34, 34) 80%, rgb(0, 0, 0) 110%);
  4969. box-shadow: inset 0px 2px 4px #e98282, inset 0px -4px 6px #440101, inset 0px 1px 6px #440101, inset 0px 0px 6px, 0px 0px 2px black, 0px 0px 0px 1px #ce9767;
  4970. }
  4971. .scriptMenu_redButton:active {
  4972. box-shadow: inset 0px 4px 6px #440101, inset 0px 4px 6px #440101, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 1px #ce9767;
  4973. }
  4974. .scriptMenu_attention {
  4975. position: relative;
  4976. }
  4977. .scriptMenu_attention .scriptMenu_dot {
  4978. display: flex;
  4979. justify-content: center;
  4980. align-items: center;
  4981. }
  4982. .scriptMenu_dot {
  4983. position: absolute;
  4984. top: -7px;
  4985. right: -7px;
  4986. width: 20px;
  4987. height: 20px;
  4988. border-radius: 50%;
  4989. border: 1px solid #c18550;
  4990. background: radial-gradient(circle, #f000 25%, black 100%);
  4991. box-shadow: 0px 0px 2px black;
  4992. background-position: 0px -1px;
  4993. font-size: 10px;
  4994. text-align: center;
  4995. color: white;
  4996. text-shadow: 1px 1px 1px black;
  4997. box-sizing: border-box;
  4998. display: none;
  4999. }
  5000. `;
  5001. document.head.appendChild(style);
  5002. }
  5003.  
  5004. addBlocks() {
  5005. const main = document.createElement('div');
  5006. document.body.appendChild(main);
  5007.  
  5008. this.status = document.createElement('div');
  5009. this.status.classList.add('scriptMenu_status');
  5010. this.setStatus('');
  5011. main.appendChild(this.status);
  5012.  
  5013. const label = document.createElement('label');
  5014. label.classList.add('scriptMenu_label');
  5015. label.setAttribute('for', 'checkbox_showMenu');
  5016. main.appendChild(label);
  5017.  
  5018. const arrowLabel = document.createElement('div');
  5019. arrowLabel.classList.add('scriptMenu_arrowLabel');
  5020. label.appendChild(arrowLabel);
  5021.  
  5022. const checkbox = document.createElement('input');
  5023. checkbox.type = 'checkbox';
  5024. checkbox.id = 'checkbox_showMenu';
  5025. checkbox.checked = this.option.showMenu;
  5026. checkbox.classList.add('scriptMenu_showMenu');
  5027. checkbox.addEventListener('change', () => {
  5028. this.option.showMenu = checkbox.checked;
  5029. this.saveSaveOption();
  5030. });
  5031. main.appendChild(checkbox);
  5032.  
  5033. const mainMenu = document.createElement('div');
  5034. mainMenu.classList.add('scriptMenu_main');
  5035. main.appendChild(mainMenu);
  5036.  
  5037. this.mainMenu = document.createElement('div');
  5038. this.mainMenu.classList.add('scriptMenu_conteiner');
  5039. mainMenu.appendChild(this.mainMenu);
  5040.  
  5041. const closeButton = document.createElement('label');
  5042. closeButton.classList.add('scriptMenu_close');
  5043. closeButton.setAttribute('for', 'checkbox_showMenu');
  5044. this.mainMenu.appendChild(closeButton);
  5045.  
  5046. const crossClose = document.createElement('div');
  5047. crossClose.classList.add('scriptMenu_crossClose');
  5048. closeButton.appendChild(crossClose);
  5049. }
  5050.  
  5051. getButtonColor(color) {
  5052. const buttonColors = {
  5053. green: 'scriptMenu_greenButton',
  5054. red: 'scriptMenu_redButton',
  5055. beige: 'scriptMenu_beigeButton',
  5056. };
  5057. return buttonColors[color] || buttonColors['beige'];
  5058. }
  5059.  
  5060. setStatus(text, onclick) {
  5061. if (this._currentStatusClickHandler) {
  5062. this.status.removeEventListener('click', this._currentStatusClickHandler);
  5063. this._currentStatusClickHandler = null;
  5064. }
  5065.  
  5066. if (!text) {
  5067. this.status.classList.add('scriptMenu_statusHide');
  5068. this.status.innerHTML = '';
  5069. } else {
  5070. this.status.classList.remove('scriptMenu_statusHide');
  5071. this.status.innerHTML = text;
  5072. }
  5073.  
  5074. if (typeof onclick === 'function') {
  5075. this.status.addEventListener('click', onclick, { once: true });
  5076. this._currentStatusClickHandler = onclick;
  5077. }
  5078. }
  5079.  
  5080. addStatus(text) {
  5081. if (!this.status.innerHTML) {
  5082. this.status.classList.remove('scriptMenu_statusHide');
  5083. }
  5084. this.status.innerHTML += text;
  5085. }
  5086.  
  5087. addHeader(text, onClick, main = this.mainMenu) {
  5088. this.emit('beforeAddHeader', text, onClick, main);
  5089. const header = document.createElement('div');
  5090. header.classList.add('scriptMenu_header');
  5091. header.innerHTML = text;
  5092. if (typeof onClick === 'function') {
  5093. header.addEventListener('click', onClick);
  5094. }
  5095. main.appendChild(header);
  5096. this.emit('afterAddHeader', text, onClick, main);
  5097. return header;
  5098. }
  5099.  
  5100. addButton(btn, main = this.mainMenu) {
  5101. this.emit('beforeAddButton', btn, main);
  5102. const { name, onClick, title, color, dot, classes = [], isCombine } = btn;
  5103. const button = document.createElement('div');
  5104. if (!isCombine) {
  5105. classes.push('scriptMenu_mainButton');
  5106. }
  5107. button.classList.add('scriptMenu_button', this.getButtonColor(color), ...classes);
  5108. button.title = title;
  5109. button.addEventListener('click', onClick);
  5110. main.appendChild(button);
  5111.  
  5112. const buttonText = document.createElement('div');
  5113. buttonText.classList.add('scriptMenu_buttonText');
  5114. buttonText.innerText = name;
  5115. button.appendChild(buttonText);
  5116.  
  5117. if (dot) {
  5118. const dotAtention = document.createElement('div');
  5119. dotAtention.classList.add('scriptMenu_dot');
  5120. dotAtention.title = dot;
  5121. button.appendChild(dotAtention);
  5122. }
  5123.  
  5124. this.buttons.push(button);
  5125. this.emit('afterAddButton', button, btn);
  5126. return button;
  5127. }
  5128.  
  5129. addCombinedButton(buttonList, main = this.mainMenu) {
  5130. this.emit('beforeAddCombinedButton', buttonList, main);
  5131. const buttonGroup = document.createElement('div');
  5132. buttonGroup.classList.add('scriptMenu_buttonGroup');
  5133. let count = 0;
  5134.  
  5135. for (const btn of buttonList) {
  5136. btn.isCombine = true;
  5137. btn.classes ??= [];
  5138. if (count === 0) {
  5139. btn.classes.push('scriptMenu_combineButtonLeft');
  5140. } else if (count === buttonList.length - 1) {
  5141. btn.classes.push('scriptMenu_combineButtonRight');
  5142. } else {
  5143. btn.classes.push('scriptMenu_combineButtonCenter');
  5144. }
  5145. this.addButton(btn, buttonGroup);
  5146. count++;
  5147. }
  5148.  
  5149. const dotAtention = document.createElement('div');
  5150. dotAtention.classList.add('scriptMenu_dot');
  5151. buttonGroup.appendChild(dotAtention);
  5152.  
  5153. main.appendChild(buttonGroup);
  5154. this.emit('afterAddCombinedButton', buttonGroup, buttonList);
  5155. return buttonGroup;
  5156. }
  5157.  
  5158. addCheckbox(label, title, main = this.mainMenu) {
  5159. this.emit('beforeAddCheckbox', label, title, main);
  5160. const divCheckbox = document.createElement('div');
  5161. divCheckbox.classList.add('scriptMenu_divInput');
  5162. divCheckbox.title = title;
  5163. main.appendChild(divCheckbox);
  5164.  
  5165. const checkbox = document.createElement('input');
  5166. checkbox.type = 'checkbox';
  5167. checkbox.id = 'scriptMenuCheckbox' + this.checkboxes.length;
  5168. checkbox.classList.add('scriptMenu_checkbox');
  5169. divCheckbox.appendChild(checkbox);
  5170.  
  5171. const checkboxLabel = document.createElement('label');
  5172. checkboxLabel.innerText = label;
  5173. checkboxLabel.setAttribute('for', checkbox.id);
  5174. divCheckbox.appendChild(checkboxLabel);
  5175.  
  5176. this.checkboxes.push(checkbox);
  5177. this.emit('afterAddCheckbox', label, title, main);
  5178. return checkbox;
  5179. }
  5180.  
  5181. addInputText(title, placeholder, main = this.mainMenu) {
  5182. this.emit('beforeAddCheckbox', title, placeholder, main);
  5183. const divInputText = document.createElement('div');
  5184. divInputText.classList.add('scriptMenu_divInputText');
  5185. divInputText.title = title;
  5186. main.appendChild(divInputText);
  5187.  
  5188. const newInputText = document.createElement('input');
  5189. newInputText.type = 'text';
  5190. if (placeholder) {
  5191. newInputText.placeholder = placeholder;
  5192. }
  5193. newInputText.classList.add('scriptMenu_InputText');
  5194. divInputText.appendChild(newInputText);
  5195. this.emit('afterAddCheckbox', title, placeholder, main);
  5196. return newInputText;
  5197. }
  5198.  
  5199. addDetails(summaryText, name = null) {
  5200. this.emit('beforeAddDetails', summaryText, name);
  5201. const details = document.createElement('details');
  5202. details.classList.add('scriptMenu_Details');
  5203. this.mainMenu.appendChild(details);
  5204.  
  5205. const summary = document.createElement('summary');
  5206. summary.classList.add('scriptMenu_Summary');
  5207. summary.innerText = summaryText;
  5208. if (name) {
  5209. details.open = this.option.showDetails[name] ?? false;
  5210. details.dataset.name = name;
  5211. details.addEventListener('toggle', () => {
  5212. this.option.showDetails[details.dataset.name] = details.open;
  5213. this.saveSaveOption();
  5214. });
  5215. }
  5216.  
  5217. details.appendChild(summary);
  5218. this.emit('afterAddDetails', summaryText, name);
  5219. return details;
  5220. }
  5221.  
  5222. saveSaveOption() {
  5223. try {
  5224. localStorage.setItem('scriptMenu_saveOption', JSON.stringify(this.option));
  5225. } catch (e) {
  5226. console.log('¯\\_(ツ)_/¯');
  5227. }
  5228. }
  5229.  
  5230. loadSaveOption() {
  5231. let saveOption = null;
  5232. try {
  5233. saveOption = localStorage.getItem('scriptMenu_saveOption');
  5234. } catch (e) {
  5235. console.log('¯\\_(ツ)_/¯');
  5236. }
  5237.  
  5238. if (!saveOption) {
  5239. return {};
  5240. }
  5241.  
  5242. try {
  5243. saveOption = JSON.parse(saveOption);
  5244. } catch (e) {
  5245. return {};
  5246. }
  5247.  
  5248. return saveOption;
  5249. }
  5250. }
  5251.  
  5252. this.HWHClasses.ScriptMenu = ScriptMenu;
  5253.  
  5254. //const scriptMenu = ScriptMenu.getInst();
  5255.  
  5256. /**
  5257. * Пример использования
  5258. const scriptMenu = ScriptMenu.getInst();
  5259. scriptMenu.init();
  5260. scriptMenu.addHeader('v1.508');
  5261. scriptMenu.addCheckbox('testHack', 'Тестовый взлом игры!');
  5262. scriptMenu.addButton({
  5263. text: 'Запуск!',
  5264. onClick: () => console.log('click'),
  5265. title: 'подсказака',
  5266. });
  5267. scriptMenu.addInputText('input подсказака');
  5268. scriptMenu.on('beforeInit', (option) => {
  5269. console.log('beforeInit', option);
  5270. })
  5271. scriptMenu.on('beforeAddHeader', (text, onClick, main) => {
  5272. console.log('beforeAddHeader', text, onClick, main);
  5273. });
  5274. scriptMenu.on('beforeAddButton', (btn, main) => {
  5275. console.log('beforeAddButton', btn, main);
  5276. });
  5277. scriptMenu.on('beforeAddCombinedButton', (buttonList, main) => {
  5278. console.log('beforeAddCombinedButton', buttonList, main);
  5279. });
  5280. scriptMenu.on('beforeAddCheckbox', (label, title, main) => {
  5281. console.log('beforeAddCheckbox', label, title, main);
  5282. });
  5283. scriptMenu.on('beforeAddDetails', (summaryText, name) => {
  5284. console.log('beforeAddDetails', summaryText, name);
  5285. });
  5286. */
  5287.  
  5288. /**
  5289. * Game Library
  5290. *
  5291. * Игровая библиотека
  5292. */
  5293. class Library {
  5294. defaultLibUrl = 'https://heroesru-a.akamaihd.net/vk/v1101/lib/lib.json';
  5295.  
  5296. constructor() {
  5297. if (!Library.instance) {
  5298. Library.instance = this;
  5299. }
  5300.  
  5301. return Library.instance;
  5302. }
  5303.  
  5304. async load() {
  5305. try {
  5306. await this.getUrlLib();
  5307. console.log(this.defaultLibUrl);
  5308. this.data = await fetch(this.defaultLibUrl).then(e => e.json())
  5309. } catch (error) {
  5310. console.error('Не удалось загрузить библиотеку', error)
  5311. }
  5312. }
  5313.  
  5314. async getUrlLib() {
  5315. try {
  5316. const db = new Database('hw_cache', 'cache');
  5317. await db.open();
  5318. const cacheLibFullUrl = await db.get('lib/lib.json.gz', false);
  5319. this.defaultLibUrl = cacheLibFullUrl.fullUrl.split('.gz').shift();
  5320. } catch(e) {}
  5321. }
  5322.  
  5323. getData(id) {
  5324. return this.data[id];
  5325. }
  5326.  
  5327. setData(data) {
  5328. this.data = data;
  5329. }
  5330. }
  5331.  
  5332. this.lib = new Library();
  5333. /**
  5334. * Database
  5335. *
  5336. * База данных
  5337. */
  5338. class Database {
  5339. constructor(dbName, storeName) {
  5340. this.dbName = dbName;
  5341. this.storeName = storeName;
  5342. this.db = null;
  5343. }
  5344.  
  5345. async open() {
  5346. return new Promise((resolve, reject) => {
  5347. const request = indexedDB.open(this.dbName);
  5348.  
  5349. request.onerror = () => {
  5350. reject(new Error(`Failed to open database ${this.dbName}`));
  5351. };
  5352.  
  5353. request.onsuccess = () => {
  5354. this.db = request.result;
  5355. resolve();
  5356. };
  5357.  
  5358. request.onupgradeneeded = (event) => {
  5359. const db = event.target.result;
  5360. if (!db.objectStoreNames.contains(this.storeName)) {
  5361. db.createObjectStore(this.storeName);
  5362. }
  5363. };
  5364. });
  5365. }
  5366.  
  5367. async set(key, value) {
  5368. return new Promise((resolve, reject) => {
  5369. const transaction = this.db.transaction([this.storeName], 'readwrite');
  5370. const store = transaction.objectStore(this.storeName);
  5371. const request = store.put(value, key);
  5372.  
  5373. request.onerror = () => {
  5374. reject(new Error(`Failed to save value with key ${key}`));
  5375. };
  5376.  
  5377. request.onsuccess = () => {
  5378. resolve();
  5379. };
  5380. });
  5381. }
  5382.  
  5383. async get(key, def) {
  5384. return new Promise((resolve, reject) => {
  5385. const transaction = this.db.transaction([this.storeName], 'readonly');
  5386. const store = transaction.objectStore(this.storeName);
  5387. const request = store.get(key);
  5388.  
  5389. request.onerror = () => {
  5390. resolve(def);
  5391. };
  5392.  
  5393. request.onsuccess = () => {
  5394. resolve(request.result);
  5395. };
  5396. });
  5397. }
  5398.  
  5399. async delete(key) {
  5400. return new Promise((resolve, reject) => {
  5401. const transaction = this.db.transaction([this.storeName], 'readwrite');
  5402. const store = transaction.objectStore(this.storeName);
  5403. const request = store.delete(key);
  5404.  
  5405. request.onerror = () => {
  5406. reject(new Error(`Failed to delete value with key ${key}`));
  5407. };
  5408.  
  5409. request.onsuccess = () => {
  5410. resolve();
  5411. };
  5412. });
  5413. }
  5414. }
  5415.  
  5416. /**
  5417. * Returns the stored value
  5418. *
  5419. * Возвращает сохраненное значение
  5420. */
  5421. function getSaveVal(saveName, def) {
  5422. const result = storage.get(saveName, def);
  5423. return result;
  5424. }
  5425. this.HWHFuncs.getSaveVal = getSaveVal;
  5426.  
  5427. /**
  5428. * Stores value
  5429. *
  5430. * Сохраняет значение
  5431. */
  5432. function setSaveVal(saveName, value) {
  5433. storage.set(saveName, value);
  5434. }
  5435. this.HWHFuncs.setSaveVal = setSaveVal;
  5436.  
  5437. /**
  5438. * Database initialization
  5439. *
  5440. * Инициализация базы данных
  5441. */
  5442. const db = new Database(GM_info.script.name, 'settings');
  5443.  
  5444. /**
  5445. * Data store
  5446. *
  5447. * Хранилище данных
  5448. */
  5449. const storage = {
  5450. userId: 0,
  5451. /**
  5452. * Default values
  5453. *
  5454. * Значения по умолчанию
  5455. */
  5456. values: {},
  5457. name: GM_info.script.name,
  5458. init: function () {
  5459. const { checkboxes, inputs } = HWHData;
  5460. this.values = [
  5461. ...Object.entries(checkboxes).map((e) => ({ [e[0]]: e[1].default })),
  5462. ...Object.entries(inputs).map((e) => ({ [e[0]]: e[1].default })),
  5463. ].reduce((acc, obj) => ({ ...acc, ...obj }), {});
  5464. },
  5465. get: function (key, def) {
  5466. if (key in this.values) {
  5467. return this.values[key];
  5468. }
  5469. return def;
  5470. },
  5471. set: function (key, value) {
  5472. this.values[key] = value;
  5473. db.set(this.userId, this.values).catch((e) => null);
  5474. localStorage[this.name + ':' + key] = value;
  5475. },
  5476. delete: function (key) {
  5477. delete this.values[key];
  5478. db.set(this.userId, this.values);
  5479. delete localStorage[this.name + ':' + key];
  5480. },
  5481. };
  5482.  
  5483. /**
  5484. * Returns all keys from localStorage that start with prefix (for migration)
  5485. *
  5486. * Возвращает все ключи из localStorage которые начинаются с prefix (для миграции)
  5487. */
  5488. function getAllValuesStartingWith(prefix) {
  5489. const values = [];
  5490. for (let i = 0; i < localStorage.length; i++) {
  5491. const key = localStorage.key(i);
  5492. if (key.startsWith(prefix)) {
  5493. const val = localStorage.getItem(key);
  5494. const keyValue = key.split(':')[1];
  5495. values.push({ key: keyValue, val });
  5496. }
  5497. }
  5498. return values;
  5499. }
  5500.  
  5501. /**
  5502. * Opens or migrates to a database
  5503. *
  5504. * Открывает или мигрирует в базу данных
  5505. */
  5506. async function openOrMigrateDatabase(userId) {
  5507. storage.init();
  5508. storage.userId = userId;
  5509. try {
  5510. await db.open();
  5511. } catch(e) {
  5512. return;
  5513. }
  5514. let settings = await db.get(userId, false);
  5515.  
  5516. if (settings) {
  5517. storage.values = settings;
  5518. return;
  5519. }
  5520.  
  5521. const values = getAllValuesStartingWith(GM_info.script.name);
  5522. for (const value of values) {
  5523. let val = null;
  5524. try {
  5525. val = JSON.parse(value.val);
  5526. } catch {
  5527. break;
  5528. }
  5529. storage.values[value.key] = val;
  5530. }
  5531. await db.set(userId, storage.values);
  5532. }
  5533.  
  5534. class ZingerYWebsiteAPI {
  5535. /**
  5536. * Class for interaction with the API of the zingery.ru website
  5537. * Intended only for use with the HeroWarsHelper script:
  5538. * https://greasyfork.org/ru/scripts/450693-herowarshelper
  5539. * Copyright ZingerY
  5540. */
  5541. url = 'https://zingery.ru/heroes/';
  5542. // YWJzb2x1dGVseSB1c2VsZXNzIGxpbmU=
  5543. constructor(urn, env, data = {}) {
  5544. this.urn = urn;
  5545. this.fd = {
  5546. now: Date.now(),
  5547. fp: this.constructor.toString().replaceAll(/\s/g, ''),
  5548. env: env.callee.toString().replaceAll(/\s/g, ''),
  5549. info: (({ name, version, author }) => [name, version, author])(GM_info.script),
  5550. ...data,
  5551. };
  5552. }
  5553.  
  5554. sign() {
  5555. return md5([...this.fd.info, ~(this.fd.now % 1e3), this.fd.fp].join('_'));
  5556. }
  5557.  
  5558. encode(data) {
  5559. return btoa(encodeURIComponent(JSON.stringify(data)));
  5560. }
  5561.  
  5562. decode(data) {
  5563. return JSON.parse(decodeURIComponent(atob(data)));
  5564. }
  5565.  
  5566. headers() {
  5567. return {
  5568. 'X-Request-Signature': this.sign(),
  5569. 'X-Script-Name': GM_info.script.name,
  5570. 'X-Script-Version': GM_info.script.version,
  5571. 'X-Script-Author': GM_info.script.author,
  5572. 'X-Script-ZingerY': 42,
  5573. };
  5574. }
  5575.  
  5576. async request() {
  5577. try {
  5578. const response = await fetch(this.url + this.urn, {
  5579. method: 'POST',
  5580. headers: this.headers(),
  5581. body: this.encode(this.fd),
  5582. });
  5583. const text = await response.text();
  5584. return this.decode(text);
  5585. } catch (e) {
  5586. console.error(e);
  5587. return [];
  5588. }
  5589. }
  5590. /**
  5591. * Класс для взаимодействия с API сайта zingery.ru
  5592. * Предназначен только для использования со скриптом HeroWarsHelper:
  5593. * https://greasyfork.org/ru/scripts/450693-herowarshelper
  5594. * Copyright ZingerY
  5595. */
  5596. }
  5597.  
  5598. /**
  5599. * Sending expeditions
  5600. *
  5601. * Отправка экспедиций
  5602. */
  5603. function checkExpedition() {
  5604. const { Expedition } = HWHClasses;
  5605. return new Promise((resolve, reject) => {
  5606. const expedition = new Expedition(resolve, reject);
  5607. expedition.start();
  5608. });
  5609. }
  5610.  
  5611. class Expedition {
  5612. checkExpedInfo = {
  5613. calls: [
  5614. {
  5615. name: 'expeditionGet',
  5616. args: {},
  5617. ident: 'expeditionGet',
  5618. },
  5619. {
  5620. name: 'heroGetAll',
  5621. args: {},
  5622. ident: 'heroGetAll',
  5623. },
  5624. ],
  5625. };
  5626.  
  5627. constructor(resolve, reject) {
  5628. this.resolve = resolve;
  5629. this.reject = reject;
  5630. }
  5631.  
  5632. async start() {
  5633. const data = await Send(JSON.stringify(this.checkExpedInfo));
  5634.  
  5635. const expedInfo = data.results[0].result.response;
  5636. const dataHeroes = data.results[1].result.response;
  5637. const dataExped = { useHeroes: [], exped: [] };
  5638. const calls = [];
  5639.  
  5640. /**
  5641. * Adding expeditions to collect
  5642. * Добавляем экспедиции для сбора
  5643. */
  5644. let countGet = 0;
  5645. for (var n in expedInfo) {
  5646. const exped = expedInfo[n];
  5647. const dateNow = Date.now() / 1000;
  5648. if (exped.status == 2 && exped.endTime != 0 && dateNow > exped.endTime) {
  5649. countGet++;
  5650. calls.push({
  5651. name: 'expeditionFarm',
  5652. args: { expeditionId: exped.id },
  5653. ident: 'expeditionFarm_' + exped.id,
  5654. });
  5655. } else {
  5656. dataExped.useHeroes = dataExped.useHeroes.concat(exped.heroes);
  5657. }
  5658. if (exped.status == 1) {
  5659. dataExped.exped.push({ id: exped.id, power: exped.power });
  5660. }
  5661. }
  5662. dataExped.exped = dataExped.exped.sort((a, b) => b.power - a.power);
  5663.  
  5664. /**
  5665. * Putting together a list of heroes
  5666. * Собираем список героев
  5667. */
  5668. const heroesArr = [];
  5669. for (let n in dataHeroes) {
  5670. const hero = dataHeroes[n];
  5671. if (hero.power > 0 && !dataExped.useHeroes.includes(hero.id)) {
  5672. let heroPower = hero.power;
  5673. // Лара Крофт * 3
  5674. if (hero.id == 63 && hero.color >= 16) {
  5675. heroPower *= 3;
  5676. }
  5677. heroesArr.push({ id: hero.id, power: heroPower });
  5678. }
  5679. }
  5680.  
  5681. /**
  5682. * Adding expeditions to send
  5683. * Добавляем экспедиции для отправки
  5684. */
  5685. let countSend = 0;
  5686. heroesArr.sort((a, b) => a.power - b.power);
  5687. for (const exped of dataExped.exped) {
  5688. let heroesIds = this.selectionHeroes(heroesArr, exped.power);
  5689. if (heroesIds && heroesIds.length > 4) {
  5690. for (let q in heroesArr) {
  5691. if (heroesIds.includes(heroesArr[q].id)) {
  5692. delete heroesArr[q];
  5693. }
  5694. }
  5695. countSend++;
  5696. calls.push({
  5697. name: 'expeditionSendHeroes',
  5698. args: {
  5699. expeditionId: exped.id,
  5700. heroes: heroesIds,
  5701. },
  5702. ident: 'expeditionSendHeroes_' + exped.id,
  5703. });
  5704. }
  5705. }
  5706.  
  5707. if (calls.length) {
  5708. await Send({ calls });
  5709. this.end(I18N('EXPEDITIONS_SENT', {countGet, countSend}));
  5710. return;
  5711. }
  5712.  
  5713. this.end(I18N('EXPEDITIONS_NOTHING'));
  5714. }
  5715.  
  5716. /**
  5717. * Selection of heroes for expeditions
  5718. *
  5719. * Подбор героев для экспедиций
  5720. */
  5721. selectionHeroes(heroes, power) {
  5722. const resultHeroers = [];
  5723. const heroesIds = [];
  5724. for (let q = 0; q < 5; q++) {
  5725. for (let i in heroes) {
  5726. let hero = heroes[i];
  5727. if (heroesIds.includes(hero.id)) {
  5728. continue;
  5729. }
  5730.  
  5731. const summ = resultHeroers.reduce((acc, hero) => acc + hero.power, 0);
  5732. const need = Math.round((power - summ) / (5 - resultHeroers.length));
  5733. if (hero.power > need) {
  5734. resultHeroers.push(hero);
  5735. heroesIds.push(hero.id);
  5736. break;
  5737. }
  5738. }
  5739. }
  5740.  
  5741. const summ = resultHeroers.reduce((acc, hero) => acc + hero.power, 0);
  5742. if (summ < power) {
  5743. return false;
  5744. }
  5745. return heroesIds;
  5746. }
  5747.  
  5748. /**
  5749. * Ends expedition script
  5750. *
  5751. * Завершает скрипт экспедиции
  5752. */
  5753. end(msg) {
  5754. setProgress(msg, true);
  5755. this.resolve();
  5756. }
  5757. }
  5758.  
  5759. this.HWHClasses.Expedition = Expedition;
  5760.  
  5761. /**
  5762. * Walkthrough of the dungeon
  5763. *
  5764. * Прохождение подземелья
  5765. */
  5766. function testDungeon() {
  5767. const { executeDungeon } = HWHClasses;
  5768. return new Promise((resolve, reject) => {
  5769. const dung = new executeDungeon(resolve, reject);
  5770. const titanit = getInput('countTitanit');
  5771. dung.start(titanit);
  5772. });
  5773. }
  5774.  
  5775. /**
  5776. * Walkthrough of the dungeon
  5777. *
  5778. * Прохождение подземелья
  5779. */
  5780. function executeDungeon(resolve, reject) {
  5781. dungeonActivity = 0;
  5782. let maxDungeonActivity = 150;
  5783.  
  5784. titanGetAll = [];
  5785.  
  5786. teams = {
  5787. heroes: [],
  5788. earth: [],
  5789. fire: [],
  5790. neutral: [],
  5791. water: [],
  5792. }
  5793.  
  5794. titanStats = [];
  5795.  
  5796. titansStates = {};
  5797.  
  5798. let talentMsg = '';
  5799. let talentMsgReward = '';
  5800.  
  5801. callsExecuteDungeon = {
  5802. calls: [{
  5803. name: "dungeonGetInfo",
  5804. args: {},
  5805. ident: "dungeonGetInfo"
  5806. }, {
  5807. name: "teamGetAll",
  5808. args: {},
  5809. ident: "teamGetAll"
  5810. }, {
  5811. name: "teamGetFavor",
  5812. args: {},
  5813. ident: "teamGetFavor"
  5814. }, {
  5815. name: "clanGetInfo",
  5816. args: {},
  5817. ident: "clanGetInfo"
  5818. }, {
  5819. name: "titanGetAll",
  5820. args: {},
  5821. ident: "titanGetAll"
  5822. }, {
  5823. name: "inventoryGet",
  5824. args: {},
  5825. ident: "inventoryGet"
  5826. }]
  5827. }
  5828.  
  5829. this.start = function(titanit) {
  5830. maxDungeonActivity = titanit || getInput('countTitanit');
  5831. send(JSON.stringify(callsExecuteDungeon), startDungeon);
  5832. }
  5833.  
  5834. /**
  5835. * Getting data on the dungeon
  5836. *
  5837. * Получаем данные по подземелью
  5838. */
  5839. function startDungeon(e) {
  5840. res = e.results;
  5841. dungeonGetInfo = res[0].result.response;
  5842. if (!dungeonGetInfo) {
  5843. endDungeon('noDungeon', res);
  5844. return;
  5845. }
  5846. teamGetAll = res[1].result.response;
  5847. teamGetFavor = res[2].result.response;
  5848. dungeonActivity = res[3].result.response.stat.todayDungeonActivity;
  5849. titanGetAll = Object.values(res[4].result.response);
  5850. countPredictionCard = res[5].result.response.consumable[81];
  5851.  
  5852. teams.hero = {
  5853. favor: teamGetFavor.dungeon_hero,
  5854. heroes: teamGetAll.dungeon_hero.filter(id => id < 6000),
  5855. teamNum: 0,
  5856. }
  5857. heroPet = teamGetAll.dungeon_hero.filter(id => id >= 6000).pop();
  5858. if (heroPet) {
  5859. teams.hero.pet = heroPet;
  5860. }
  5861.  
  5862. teams.neutral = {
  5863. favor: {},
  5864. heroes: getTitanTeam(titanGetAll, 'neutral'),
  5865. teamNum: 0,
  5866. };
  5867. teams.water = {
  5868. favor: {},
  5869. heroes: getTitanTeam(titanGetAll, 'water'),
  5870. teamNum: 0,
  5871. };
  5872. teams.fire = {
  5873. favor: {},
  5874. heroes: getTitanTeam(titanGetAll, 'fire'),
  5875. teamNum: 0,
  5876. };
  5877. teams.earth = {
  5878. favor: {},
  5879. heroes: getTitanTeam(titanGetAll, 'earth'),
  5880. teamNum: 0,
  5881. };
  5882.  
  5883.  
  5884. checkFloor(dungeonGetInfo);
  5885. }
  5886.  
  5887. function getTitanTeam(titans, type) {
  5888. switch (type) {
  5889. case 'neutral':
  5890. return titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5891. case 'water':
  5892. return titans.filter(e => e.id.toString().slice(2, 3) == '0').map(e => e.id);
  5893. case 'fire':
  5894. return titans.filter(e => e.id.toString().slice(2, 3) == '1').map(e => e.id);
  5895. case 'earth':
  5896. return titans.filter(e => e.id.toString().slice(2, 3) == '2').map(e => e.id);
  5897. }
  5898. }
  5899.  
  5900. function getNeutralTeam() {
  5901. const titans = titanGetAll.filter(e => !titansStates[e.id]?.isDead)
  5902. return titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5903. }
  5904.  
  5905. function fixTitanTeam(titans) {
  5906. titans.heroes = titans.heroes.filter(e => !titansStates[e]?.isDead);
  5907. return titans;
  5908. }
  5909.  
  5910. /**
  5911. * Checking the floor
  5912. *
  5913. * Проверяем этаж
  5914. */
  5915. async function checkFloor(dungeonInfo) {
  5916. if (!('floor' in dungeonInfo) || dungeonInfo.floor?.state == 2) {
  5917. saveProgress();
  5918. return;
  5919. }
  5920. checkTalent(dungeonInfo);
  5921. // console.log(dungeonInfo, dungeonActivity);
  5922. maxDungeonActivity = +getInput('countTitanit');
  5923. setProgress(`${I18N('DUNGEON')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity} ${talentMsg}`);
  5924. if (dungeonActivity >= maxDungeonActivity) {
  5925. endDungeon('endDungeon', 'maxActive ' + dungeonActivity + '/' + maxDungeonActivity);
  5926. return;
  5927. }
  5928. titansStates = dungeonInfo.states.titans;
  5929. titanStats = titanObjToArray(titansStates);
  5930. const floorChoices = dungeonInfo.floor.userData;
  5931. const floorType = dungeonInfo.floorType;
  5932. //const primeElement = dungeonInfo.elements.prime;
  5933. if (floorType == "battle") {
  5934. const calls = [];
  5935. for (let teamNum in floorChoices) {
  5936. attackerType = floorChoices[teamNum].attackerType;
  5937. const args = fixTitanTeam(teams[attackerType]);
  5938. if (attackerType == 'neutral') {
  5939. args.heroes = getNeutralTeam();
  5940. }
  5941. if (!args.heroes.length) {
  5942. continue;
  5943. }
  5944. args.teamNum = teamNum;
  5945. calls.push({
  5946. name: "dungeonStartBattle",
  5947. args,
  5948. ident: "body_" + teamNum
  5949. })
  5950. }
  5951. if (!calls.length) {
  5952. endDungeon('endDungeon', 'All Dead');
  5953. return;
  5954. }
  5955. const battleDatas = await Send(JSON.stringify({ calls }))
  5956. .then(e => e.results.map(n => n.result.response))
  5957. const battleResults = [];
  5958. for (n in battleDatas) {
  5959. battleData = battleDatas[n]
  5960. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  5961. battleResults.push(await Calc(battleData).then(result => {
  5962. result.teamNum = n;
  5963. result.attackerType = floorChoices[n].attackerType;
  5964. return result;
  5965. }));
  5966. }
  5967. processingPromises(battleResults)
  5968. }
  5969. }
  5970.  
  5971. async function checkTalent(dungeonInfo) {
  5972. const talent = dungeonInfo.talent;
  5973. if (!talent) {
  5974. return;
  5975. }
  5976. const dungeonFloor = +dungeonInfo.floorNumber;
  5977. const talentFloor = +talent.floorRandValue;
  5978. let doorsAmount = 3 - talent.conditions.doorsAmount;
  5979.  
  5980. if (dungeonFloor === talentFloor && (!doorsAmount || !talent.conditions?.farmedDoors[dungeonFloor])) {
  5981. const reward = await Send({
  5982. calls: [
  5983. { name: 'heroTalent_getReward', args: { talentType: 'tmntDungeonTalent', reroll: false }, ident: 'group_0_body' },
  5984. { name: 'heroTalent_farmReward', args: { talentType: 'tmntDungeonTalent' }, ident: 'group_1_body' },
  5985. ],
  5986. }).then((e) => e.results[0].result.response);
  5987. const type = Object.keys(reward).pop();
  5988. const itemId = Object.keys(reward[type]).pop();
  5989. const count = reward[type][itemId];
  5990. const itemName = cheats.translate(`LIB_${type.toUpperCase()}_NAME_${itemId}`);
  5991. talentMsgReward += `<br> ${count} ${itemName}`;
  5992. doorsAmount++;
  5993. }
  5994. talentMsg = `<br>TMNT Talent: ${doorsAmount}/3 ${talentMsgReward}<br>`;
  5995. }
  5996.  
  5997. function processingPromises(results) {
  5998. let selectBattle = results[0];
  5999. if (results.length < 2) {
  6000. // console.log(selectBattle);
  6001. if (!selectBattle.result.win) {
  6002. endDungeon('dungeonEndBattle\n', selectBattle);
  6003. return;
  6004. }
  6005. endBattle(selectBattle);
  6006. return;
  6007. }
  6008.  
  6009. selectBattle = false;
  6010. let bestState = -1000;
  6011. for (const result of results) {
  6012. const recovery = getState(result);
  6013. if (recovery > bestState) {
  6014. bestState = recovery;
  6015. selectBattle = result
  6016. }
  6017. }
  6018. // console.log(selectBattle.teamNum, results);
  6019. if (!selectBattle || bestState <= -1000) {
  6020. endDungeon('dungeonEndBattle\n', results);
  6021. return;
  6022. }
  6023.  
  6024. startBattle(selectBattle.teamNum, selectBattle.attackerType)
  6025. .then(endBattle);
  6026. }
  6027.  
  6028. /**
  6029. * Let's start the fight
  6030. *
  6031. * Начинаем бой
  6032. */
  6033. function startBattle(teamNum, attackerType) {
  6034. return new Promise(function (resolve, reject) {
  6035. args = fixTitanTeam(teams[attackerType]);
  6036. args.teamNum = teamNum;
  6037. if (attackerType == 'neutral') {
  6038. const titans = titanGetAll.filter(e => !titansStates[e.id]?.isDead)
  6039. args.heroes = titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  6040. }
  6041. startBattleCall = {
  6042. calls: [{
  6043. name: "dungeonStartBattle",
  6044. args,
  6045. ident: "body"
  6046. }]
  6047. }
  6048. send(JSON.stringify(startBattleCall), resultBattle, {
  6049. resolve,
  6050. teamNum,
  6051. attackerType
  6052. });
  6053. });
  6054. }
  6055. /**
  6056. * Returns the result of the battle in a promise
  6057. *
  6058. * Возращает резульат боя в промис
  6059. */
  6060. function resultBattle(resultBattles, args) {
  6061. battleData = resultBattles.results[0].result.response;
  6062. battleType = "get_tower";
  6063. if (battleData.type == "dungeon_titan") {
  6064. battleType = "get_titan";
  6065. }
  6066. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  6067. BattleCalc(battleData, battleType, function (result) {
  6068. result.teamNum = args.teamNum;
  6069. result.attackerType = args.attackerType;
  6070. args.resolve(result);
  6071. });
  6072. }
  6073. /**
  6074. * Finishing the fight
  6075. *
  6076. * Заканчиваем бой
  6077. */
  6078. async function endBattle(battleInfo) {
  6079. if (battleInfo.result.win) {
  6080. const args = {
  6081. result: battleInfo.result,
  6082. progress: battleInfo.progress,
  6083. }
  6084. if (countPredictionCard > 0) {
  6085. args.isRaid = true;
  6086. } else {
  6087. const timer = getTimer(battleInfo.battleTime);
  6088. console.log(timer);
  6089. await countdownTimer(timer, `${I18N('DUNGEON')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity} ${talentMsg}`);
  6090. }
  6091. const calls = [{
  6092. name: "dungeonEndBattle",
  6093. args,
  6094. ident: "body"
  6095. }];
  6096. lastDungeonBattleData = null;
  6097. send(JSON.stringify({ calls }), resultEndBattle);
  6098. } else {
  6099. endDungeon('dungeonEndBattle win: false\n', battleInfo);
  6100. }
  6101. }
  6102.  
  6103. /**
  6104. * Getting and processing battle results
  6105. *
  6106. * Получаем и обрабатываем результаты боя
  6107. */
  6108. function resultEndBattle(e) {
  6109. if ('error' in e) {
  6110. popup.confirm(I18N('ERROR_MSG', {
  6111. name: e.error.name,
  6112. description: e.error.description,
  6113. }));
  6114. endDungeon('errorRequest', e);
  6115. return;
  6116. }
  6117. battleResult = e.results[0].result.response;
  6118. if ('error' in battleResult) {
  6119. endDungeon('errorBattleResult', battleResult);
  6120. return;
  6121. }
  6122. dungeonGetInfo = battleResult.dungeon ?? battleResult;
  6123. dungeonActivity += battleResult.reward.dungeonActivity ?? 0;
  6124. checkFloor(dungeonGetInfo);
  6125. }
  6126.  
  6127. /**
  6128. * Returns the coefficient of condition of the
  6129. * difference in titanium before and after the battle
  6130. *
  6131. * Возвращает коэффициент состояния титанов после боя
  6132. */
  6133. function getState(result) {
  6134. if (!result.result.win) {
  6135. return -1000;
  6136. }
  6137.  
  6138. let beforeSumFactor = 0;
  6139. const beforeTitans = result.battleData.attackers;
  6140. for (let titanId in beforeTitans) {
  6141. const titan = beforeTitans[titanId];
  6142. const state = titan.state;
  6143. let factor = 1;
  6144. if (state) {
  6145. const hp = state.hp / titan.hp;
  6146. const energy = state.energy / 1e3;
  6147. factor = hp + energy / 20
  6148. }
  6149. beforeSumFactor += factor;
  6150. }
  6151.  
  6152. let afterSumFactor = 0;
  6153. const afterTitans = result.progress[0].attackers.heroes;
  6154. for (let titanId in afterTitans) {
  6155. const titan = afterTitans[titanId];
  6156. const hp = titan.hp / beforeTitans[titanId].hp;
  6157. const energy = titan.energy / 1e3;
  6158. const factor = hp + energy / 20;
  6159. afterSumFactor += factor;
  6160. }
  6161. return afterSumFactor - beforeSumFactor;
  6162. }
  6163.  
  6164. /**
  6165. * Converts an object with IDs to an array with IDs
  6166. *
  6167. * Преобразует объект с идетификаторами в массив с идетификаторами
  6168. */
  6169. function titanObjToArray(obj) {
  6170. let titans = [];
  6171. for (let id in obj) {
  6172. obj[id].id = id;
  6173. titans.push(obj[id]);
  6174. }
  6175. return titans;
  6176. }
  6177.  
  6178. function saveProgress() {
  6179. let saveProgressCall = {
  6180. calls: [{
  6181. name: "dungeonSaveProgress",
  6182. args: {},
  6183. ident: "body"
  6184. }]
  6185. }
  6186. send(JSON.stringify(saveProgressCall), resultEndBattle);
  6187. }
  6188.  
  6189. function endDungeon(reason, info) {
  6190. console.warn(reason, info);
  6191. setProgress(`${I18N('DUNGEON')} ${I18N('COMPLETED')}`, true);
  6192. resolve();
  6193. }
  6194. }
  6195.  
  6196. this.HWHClasses.executeDungeon = executeDungeon;
  6197.  
  6198. /**
  6199. * Passing the tower
  6200. *
  6201. * Прохождение башни
  6202. */
  6203. function testTower() {
  6204. const { executeTower } = HWHClasses;
  6205. return new Promise((resolve, reject) => {
  6206. tower = new executeTower(resolve, reject);
  6207. tower.start();
  6208. });
  6209. }
  6210.  
  6211. /**
  6212. * Passing the tower
  6213. *
  6214. * Прохождение башни
  6215. */
  6216. function executeTower(resolve, reject) {
  6217. lastTowerInfo = {};
  6218.  
  6219. scullCoin = 0;
  6220.  
  6221. heroGetAll = [];
  6222.  
  6223. heroesStates = {};
  6224.  
  6225. argsBattle = {
  6226. heroes: [],
  6227. favor: {},
  6228. };
  6229.  
  6230. callsExecuteTower = {
  6231. calls: [{
  6232. name: "towerGetInfo",
  6233. args: {},
  6234. ident: "towerGetInfo"
  6235. }, {
  6236. name: "teamGetAll",
  6237. args: {},
  6238. ident: "teamGetAll"
  6239. }, {
  6240. name: "teamGetFavor",
  6241. args: {},
  6242. ident: "teamGetFavor"
  6243. }, {
  6244. name: "inventoryGet",
  6245. args: {},
  6246. ident: "inventoryGet"
  6247. }, {
  6248. name: "heroGetAll",
  6249. args: {},
  6250. ident: "heroGetAll"
  6251. }]
  6252. }
  6253.  
  6254. buffIds = [
  6255. {id: 0, cost: 0, isBuy: false}, // plug // заглушка
  6256. {id: 1, cost: 1, isBuy: true}, // 3% attack // 3% атака
  6257. {id: 2, cost: 6, isBuy: true}, // 2% attack // 2% атака
  6258. {id: 3, cost: 16, isBuy: true}, // 4% attack // 4% атака
  6259. {id: 4, cost: 40, isBuy: true}, // 8% attack // 8% атака
  6260. {id: 5, cost: 1, isBuy: true}, // 10% armor // 10% броня
  6261. {id: 6, cost: 6, isBuy: true}, // 5% armor // 5% броня
  6262. {id: 7, cost: 16, isBuy: true}, // 10% armor // 10% броня
  6263. {id: 8, cost: 40, isBuy: true}, // 20% armor // 20% броня
  6264. { id: 9, cost: 1, isBuy: true }, // 10% protection from magic // 10% защита от магии
  6265. { id: 10, cost: 6, isBuy: true }, // 5% protection from magic // 5% защита от магии
  6266. { id: 11, cost: 16, isBuy: true }, // 10% protection from magic // 10% защита от магии
  6267. { id: 12, cost: 40, isBuy: true }, // 20% protection from magic // 20% защита от магии
  6268. { id: 13, cost: 1, isBuy: false }, // 40% health hero // 40% здоровья герою
  6269. { id: 14, cost: 6, isBuy: false }, // 40% health hero // 40% здоровья герою
  6270. { id: 15, cost: 16, isBuy: false }, // 80% health hero // 80% здоровья герою
  6271. { id: 16, cost: 40, isBuy: false }, // 40% health to all heroes // 40% здоровья всем героям
  6272. { id: 17, cost: 1, isBuy: false }, // 40% energy to the hero // 40% энергии герою
  6273. { id: 18, cost: 3, isBuy: false }, // 40% energy to the hero // 40% энергии герою
  6274. { id: 19, cost: 8, isBuy: false }, // 80% energy to the hero // 80% энергии герою
  6275. { id: 20, cost: 20, isBuy: false }, // 40% energy to all heroes // 40% энергии всем героям
  6276. { id: 21, cost: 40, isBuy: false }, // Hero Resurrection // Воскрешение героя
  6277. ]
  6278.  
  6279. this.start = function () {
  6280. send(JSON.stringify(callsExecuteTower), startTower);
  6281. }
  6282.  
  6283. /**
  6284. * Getting data on the Tower
  6285. *
  6286. * Получаем данные по башне
  6287. */
  6288. function startTower(e) {
  6289. res = e.results;
  6290. towerGetInfo = res[0].result.response;
  6291. if (!towerGetInfo) {
  6292. endTower('noTower', res);
  6293. return;
  6294. }
  6295. teamGetAll = res[1].result.response;
  6296. teamGetFavor = res[2].result.response;
  6297. inventoryGet = res[3].result.response;
  6298. heroGetAll = Object.values(res[4].result.response);
  6299.  
  6300. scullCoin = inventoryGet.coin[7] ?? 0;
  6301.  
  6302. argsBattle.favor = teamGetFavor.tower;
  6303. argsBattle.heroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  6304. pet = teamGetAll.tower.filter(id => id >= 6000).pop();
  6305. if (pet) {
  6306. argsBattle.pet = pet;
  6307. }
  6308.  
  6309. checkFloor(towerGetInfo);
  6310. }
  6311.  
  6312. function fixHeroesTeam(argsBattle) {
  6313. let fixHeroes = argsBattle.heroes.filter(e => !heroesStates[e]?.isDead);
  6314. if (fixHeroes.length < 5) {
  6315. heroGetAll = heroGetAll.filter(e => !heroesStates[e.id]?.isDead);
  6316. fixHeroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  6317. Object.keys(argsBattle.favor).forEach(e => {
  6318. if (!fixHeroes.includes(+e)) {
  6319. delete argsBattle.favor[e];
  6320. }
  6321. })
  6322. }
  6323. argsBattle.heroes = fixHeroes;
  6324. return argsBattle;
  6325. }
  6326.  
  6327. /**
  6328. * Check the floor
  6329. *
  6330. * Проверяем этаж
  6331. */
  6332. function checkFloor(towerInfo) {
  6333. lastTowerInfo = towerInfo;
  6334. maySkipFloor = +towerInfo.maySkipFloor;
  6335. floorNumber = +towerInfo.floorNumber;
  6336. heroesStates = towerInfo.states.heroes;
  6337. floorInfo = towerInfo.floor;
  6338.  
  6339. /**
  6340. * Is there at least one chest open on the floor
  6341. * Открыт ли на этаже хоть один сундук
  6342. */
  6343. isOpenChest = false;
  6344. if (towerInfo.floorType == "chest") {
  6345. isOpenChest = towerInfo.floor.chests.reduce((n, e) => n + e.opened, 0);
  6346. }
  6347.  
  6348. setProgress(`${I18N('TOWER')}: ${I18N('FLOOR')} ${floorNumber}`);
  6349. if (floorNumber > 49) {
  6350. if (isOpenChest) {
  6351. endTower('alreadyOpenChest 50 floor', floorNumber);
  6352. return;
  6353. }
  6354. }
  6355. /**
  6356. * If the chest is open and you can skip floors, then move on
  6357. * Если сундук открыт и можно скипать этажи, то переходим дальше
  6358. */
  6359. if (towerInfo.mayFullSkip && +towerInfo.teamLevel == 130) {
  6360. if (floorNumber == 1) {
  6361. fullSkipTower();
  6362. return;
  6363. }
  6364. if (isOpenChest) {
  6365. nextOpenChest(floorNumber);
  6366. } else {
  6367. nextChestOpen(floorNumber);
  6368. }
  6369. return;
  6370. }
  6371.  
  6372. // console.log(towerInfo, scullCoin);
  6373. switch (towerInfo.floorType) {
  6374. case "battle":
  6375. if (floorNumber <= maySkipFloor) {
  6376. skipFloor();
  6377. return;
  6378. }
  6379. if (floorInfo.state == 2) {
  6380. nextFloor();
  6381. return;
  6382. }
  6383. startBattle().then(endBattle);
  6384. return;
  6385. case "buff":
  6386. checkBuff(towerInfo);
  6387. return;
  6388. case "chest":
  6389. openChest(floorNumber);
  6390. return;
  6391. default:
  6392. console.log('!', towerInfo.floorType, towerInfo);
  6393. break;
  6394. }
  6395. }
  6396.  
  6397. /**
  6398. * Let's start the fight
  6399. *
  6400. * Начинаем бой
  6401. */
  6402. function startBattle() {
  6403. return new Promise(function (resolve, reject) {
  6404. towerStartBattle = {
  6405. calls: [{
  6406. name: "towerStartBattle",
  6407. args: fixHeroesTeam(argsBattle),
  6408. ident: "body"
  6409. }]
  6410. }
  6411. send(JSON.stringify(towerStartBattle), resultBattle, resolve);
  6412. });
  6413. }
  6414. /**
  6415. * Returns the result of the battle in a promise
  6416. *
  6417. * Возращает резульат боя в промис
  6418. */
  6419. function resultBattle(resultBattles, resolve) {
  6420. battleData = resultBattles.results[0].result.response;
  6421. battleType = "get_tower";
  6422. BattleCalc(battleData, battleType, function (result) {
  6423. resolve(result);
  6424. });
  6425. }
  6426. /**
  6427. * Finishing the fight
  6428. *
  6429. * Заканчиваем бой
  6430. */
  6431. function endBattle(battleInfo) {
  6432. if (battleInfo.result.stars >= 3) {
  6433. endBattleCall = {
  6434. calls: [{
  6435. name: "towerEndBattle",
  6436. args: {
  6437. result: battleInfo.result,
  6438. progress: battleInfo.progress,
  6439. },
  6440. ident: "body"
  6441. }]
  6442. }
  6443. send(JSON.stringify(endBattleCall), resultEndBattle);
  6444. } else {
  6445. endTower('towerEndBattle win: false\n', battleInfo);
  6446. }
  6447. }
  6448.  
  6449. /**
  6450. * Getting and processing battle results
  6451. *
  6452. * Получаем и обрабатываем результаты боя
  6453. */
  6454. function resultEndBattle(e) {
  6455. battleResult = e.results[0].result.response;
  6456. if ('error' in battleResult) {
  6457. endTower('errorBattleResult', battleResult);
  6458. return;
  6459. }
  6460. if ('reward' in battleResult) {
  6461. scullCoin += battleResult.reward?.coin[7] ?? 0;
  6462. }
  6463. nextFloor();
  6464. }
  6465.  
  6466. function nextFloor() {
  6467. nextFloorCall = {
  6468. calls: [{
  6469. name: "towerNextFloor",
  6470. args: {},
  6471. ident: "body"
  6472. }]
  6473. }
  6474. send(JSON.stringify(nextFloorCall), checkDataFloor);
  6475. }
  6476.  
  6477. function openChest(floorNumber) {
  6478. floorNumber = floorNumber || 0;
  6479. openChestCall = {
  6480. calls: [{
  6481. name: "towerOpenChest",
  6482. args: {
  6483. num: 2
  6484. },
  6485. ident: "body"
  6486. }]
  6487. }
  6488. send(JSON.stringify(openChestCall), floorNumber < 50 ? nextFloor : lastChest);
  6489. }
  6490.  
  6491. function lastChest() {
  6492. endTower('openChest 50 floor', floorNumber);
  6493. }
  6494.  
  6495. function skipFloor() {
  6496. skipFloorCall = {
  6497. calls: [{
  6498. name: "towerSkipFloor",
  6499. args: {},
  6500. ident: "body"
  6501. }]
  6502. }
  6503. send(JSON.stringify(skipFloorCall), checkDataFloor);
  6504. }
  6505.  
  6506. function checkBuff(towerInfo) {
  6507. buffArr = towerInfo.floor;
  6508. promises = [];
  6509. for (let buff of buffArr) {
  6510. buffInfo = buffIds[buff.id];
  6511. if (buffInfo.isBuy && buffInfo.cost <= scullCoin) {
  6512. scullCoin -= buffInfo.cost;
  6513. promises.push(buyBuff(buff.id));
  6514. }
  6515. }
  6516. Promise.all(promises).then(nextFloor);
  6517. }
  6518.  
  6519. function buyBuff(buffId) {
  6520. return new Promise(function (resolve, reject) {
  6521. buyBuffCall = {
  6522. calls: [{
  6523. name: "towerBuyBuff",
  6524. args: {
  6525. buffId
  6526. },
  6527. ident: "body"
  6528. }]
  6529. }
  6530. send(JSON.stringify(buyBuffCall), resolve);
  6531. });
  6532. }
  6533.  
  6534. function checkDataFloor(result) {
  6535. towerInfo = result.results[0].result.response;
  6536. if ('reward' in towerInfo && towerInfo.reward?.coin) {
  6537. scullCoin += towerInfo.reward?.coin[7] ?? 0;
  6538. }
  6539. if ('tower' in towerInfo) {
  6540. towerInfo = towerInfo.tower;
  6541. }
  6542. if ('skullReward' in towerInfo) {
  6543. scullCoin += towerInfo.skullReward?.coin[7] ?? 0;
  6544. }
  6545. checkFloor(towerInfo);
  6546. }
  6547. /**
  6548. * Getting tower rewards
  6549. *
  6550. * Получаем награды башни
  6551. */
  6552. function farmTowerRewards(reason) {
  6553. let { pointRewards, points } = lastTowerInfo;
  6554. let pointsAll = Object.getOwnPropertyNames(pointRewards);
  6555. let farmPoints = pointsAll.filter(e => +e <= +points && !pointRewards[e]);
  6556. if (!farmPoints.length) {
  6557. return;
  6558. }
  6559. let farmTowerRewardsCall = {
  6560. calls: [{
  6561. name: "tower_farmPointRewards",
  6562. args: {
  6563. points: farmPoints
  6564. },
  6565. ident: "tower_farmPointRewards"
  6566. }]
  6567. }
  6568.  
  6569. if (scullCoin > 0) {
  6570. farmTowerRewardsCall.calls.push({
  6571. name: "tower_farmSkullReward",
  6572. args: {},
  6573. ident: "tower_farmSkullReward"
  6574. });
  6575. }
  6576.  
  6577. send(JSON.stringify(farmTowerRewardsCall), () => { });
  6578. }
  6579.  
  6580. function fullSkipTower() {
  6581. /**
  6582. * Next chest
  6583. *
  6584. * Следующий сундук
  6585. */
  6586. function nextChest(n) {
  6587. return {
  6588. name: "towerNextChest",
  6589. args: {},
  6590. ident: "group_" + n + "_body"
  6591. }
  6592. }
  6593. /**
  6594. * Open chest
  6595. *
  6596. * Открыть сундук
  6597. */
  6598. function openChest(n) {
  6599. return {
  6600. name: "towerOpenChest",
  6601. args: {
  6602. "num": 2
  6603. },
  6604. ident: "group_" + n + "_body"
  6605. }
  6606. }
  6607.  
  6608. const fullSkipTowerCall = {
  6609. calls: []
  6610. }
  6611.  
  6612. let n = 0;
  6613. for (let i = 0; i < 15; i++) {
  6614. // 15 сундуков
  6615. fullSkipTowerCall.calls.push(nextChest(++n));
  6616. fullSkipTowerCall.calls.push(openChest(++n));
  6617. // +5 сундуков, 250 изюма // towerOpenChest
  6618. // if (i < 5) {
  6619. // fullSkipTowerCall.calls.push(openChest(++n, 2));
  6620. // }
  6621. }
  6622.  
  6623. fullSkipTowerCall.calls.push({
  6624. name: 'towerGetInfo',
  6625. args: {},
  6626. ident: 'group_' + ++n + '_body',
  6627. });
  6628.  
  6629. send(JSON.stringify(fullSkipTowerCall), data => {
  6630. for (const r of data.results) {
  6631. const towerInfo = r?.result?.response;
  6632. if (towerInfo && 'skullReward' in towerInfo) {
  6633. scullCoin += towerInfo.skullReward?.coin[7] ?? 0;
  6634. }
  6635. }
  6636. data.results[0] = data.results[data.results.length - 1];
  6637. checkDataFloor(data);
  6638. });
  6639. }
  6640.  
  6641. function nextChestOpen(floorNumber) {
  6642. const calls = [{
  6643. name: "towerOpenChest",
  6644. args: {
  6645. num: 2
  6646. },
  6647. ident: "towerOpenChest"
  6648. }];
  6649.  
  6650. Send(JSON.stringify({ calls })).then(e => {
  6651. nextOpenChest(floorNumber);
  6652. });
  6653. }
  6654.  
  6655. function nextOpenChest(floorNumber) {
  6656. if (floorNumber > 49) {
  6657. endTower('openChest 50 floor', floorNumber);
  6658. return;
  6659. }
  6660.  
  6661. let nextOpenChestCall = {
  6662. calls: [{
  6663. name: "towerNextChest",
  6664. args: {},
  6665. ident: "towerNextChest"
  6666. }, {
  6667. name: "towerOpenChest",
  6668. args: {
  6669. num: 2
  6670. },
  6671. ident: "towerOpenChest"
  6672. }]
  6673. }
  6674. send(JSON.stringify(nextOpenChestCall), checkDataFloor);
  6675. }
  6676.  
  6677. function endTower(reason, info) {
  6678. console.log(reason, info);
  6679. if (reason != 'noTower') {
  6680. farmTowerRewards(reason);
  6681. }
  6682. setProgress(`${I18N('TOWER')} ${I18N('COMPLETED')}!`, true);
  6683. resolve();
  6684. }
  6685. }
  6686.  
  6687. this.HWHClasses.executeTower = executeTower;
  6688.  
  6689. /**
  6690. * Passage of the arena of the titans
  6691. *
  6692. * Прохождение арены титанов
  6693. */
  6694. function testTitanArena() {
  6695. const { executeTitanArena } = HWHClasses;
  6696. return new Promise((resolve, reject) => {
  6697. titAren = new executeTitanArena(resolve, reject);
  6698. titAren.start();
  6699. });
  6700. }
  6701.  
  6702. /**
  6703. * Passage of the arena of the titans
  6704. *
  6705. * Прохождение арены титанов
  6706. */
  6707. function executeTitanArena(resolve, reject) {
  6708. let titan_arena = [];
  6709. let finishListBattle = [];
  6710. /**
  6711. * ID of the current batch
  6712. *
  6713. * Идетификатор текущей пачки
  6714. */
  6715. let currentRival = 0;
  6716. /**
  6717. * Number of attempts to finish off the pack
  6718. *
  6719. * Количество попыток добития пачки
  6720. */
  6721. let attempts = 0;
  6722. /**
  6723. * Was there an attempt to finish off the current shooting range
  6724. *
  6725. * Была ли попытка добития текущего тира
  6726. */
  6727. let isCheckCurrentTier = false;
  6728. /**
  6729. * Current shooting range
  6730. *
  6731. * Текущий тир
  6732. */
  6733. let currTier = 0;
  6734. /**
  6735. * Number of battles on the current dash
  6736. *
  6737. * Количество битв на текущем тире
  6738. */
  6739. let countRivalsTier = 0;
  6740.  
  6741. let callsStart = {
  6742. calls: [{
  6743. name: "titanArenaGetStatus",
  6744. args: {},
  6745. ident: "titanArenaGetStatus"
  6746. }, {
  6747. name: "teamGetAll",
  6748. args: {},
  6749. ident: "teamGetAll"
  6750. }]
  6751. }
  6752.  
  6753. this.start = function () {
  6754. send(JSON.stringify(callsStart), startTitanArena);
  6755. }
  6756.  
  6757. function startTitanArena(data) {
  6758. let titanArena = data.results[0].result.response;
  6759. if (titanArena.status == 'disabled') {
  6760. endTitanArena('disabled', titanArena);
  6761. return;
  6762. }
  6763.  
  6764. let teamGetAll = data.results[1].result.response;
  6765. titan_arena = teamGetAll.titan_arena;
  6766.  
  6767. checkTier(titanArena)
  6768. }
  6769.  
  6770. function checkTier(titanArena) {
  6771. if (titanArena.status == "peace_time") {
  6772. endTitanArena('Peace_time', titanArena);
  6773. return;
  6774. }
  6775. currTier = titanArena.tier;
  6776. if (currTier) {
  6777. setProgress(`${I18N('TITAN_ARENA')}: ${I18N('LEVEL')} ${currTier}`);
  6778. }
  6779.  
  6780. if (titanArena.status == "completed_tier") {
  6781. titanArenaCompleteTier();
  6782. return;
  6783. }
  6784. /**
  6785. * Checking for the possibility of a raid
  6786. * Проверка на возможность рейда
  6787. */
  6788. if (titanArena.canRaid) {
  6789. titanArenaStartRaid();
  6790. return;
  6791. }
  6792. /**
  6793. * Check was an attempt to achieve the current shooting range
  6794. * Проверка была ли попытка добития текущего тира
  6795. */
  6796. if (!isCheckCurrentTier) {
  6797. checkRivals(titanArena.rivals);
  6798. return;
  6799. }
  6800.  
  6801. endTitanArena('Done or not canRaid', titanArena);
  6802. }
  6803. /**
  6804. * Submit dash information for verification
  6805. *
  6806. * Отправка информации о тире на проверку
  6807. */
  6808. function checkResultInfo(data) {
  6809. let titanArena = data.results[0].result.response;
  6810. checkTier(titanArena);
  6811. }
  6812. /**
  6813. * Finish the current tier
  6814. *
  6815. * Завершить текущий тир
  6816. */
  6817. function titanArenaCompleteTier() {
  6818. isCheckCurrentTier = false;
  6819. let calls = [{
  6820. name: "titanArenaCompleteTier",
  6821. args: {},
  6822. ident: "body"
  6823. }];
  6824. send(JSON.stringify({calls}), checkResultInfo);
  6825. }
  6826. /**
  6827. * Gathering points to be completed
  6828. *
  6829. * Собираем точки которые нужно добить
  6830. */
  6831. function checkRivals(rivals) {
  6832. finishListBattle = [];
  6833. for (let n in rivals) {
  6834. if (rivals[n].attackScore < 250) {
  6835. finishListBattle.push(n);
  6836. }
  6837. }
  6838. console.log('checkRivals', finishListBattle);
  6839. countRivalsTier = finishListBattle.length;
  6840. roundRivals();
  6841. }
  6842. /**
  6843. * Selecting the next point to finish off
  6844. *
  6845. * Выбор следующей точки для добития
  6846. */
  6847. function roundRivals() {
  6848. let countRivals = finishListBattle.length;
  6849. if (!countRivals) {
  6850. /**
  6851. * Whole range checked
  6852. *
  6853. * Весь тир проверен
  6854. */
  6855. isCheckCurrentTier = true;
  6856. titanArenaGetStatus();
  6857. return;
  6858. }
  6859. // setProgress('TitanArena: Уровень ' + currTier + ' Бои: ' + (countRivalsTier - countRivals + 1) + '/' + countRivalsTier);
  6860. currentRival = finishListBattle.pop();
  6861. attempts = +currentRival;
  6862. // console.log('roundRivals', currentRival);
  6863. titanArenaStartBattle(currentRival);
  6864. }
  6865. /**
  6866. * The start of a solo battle
  6867. *
  6868. * Начало одиночной битвы
  6869. */
  6870. function titanArenaStartBattle(rivalId) {
  6871. let calls = [{
  6872. name: "titanArenaStartBattle",
  6873. args: {
  6874. rivalId: rivalId,
  6875. titans: titan_arena
  6876. },
  6877. ident: "body"
  6878. }];
  6879. send(JSON.stringify({calls}), calcResult);
  6880. }
  6881. /**
  6882. * Calculation of the results of the battle
  6883. *
  6884. * Расчет результатов боя
  6885. */
  6886. function calcResult(data) {
  6887. let battlesInfo = data.results[0].result.response.battle;
  6888. /**
  6889. * If attempts are equal to the current battle number we make
  6890. * Если попытки равны номеру текущего боя делаем прерасчет
  6891. */
  6892. if (attempts == currentRival) {
  6893. preCalcBattle(battlesInfo);
  6894. return;
  6895. }
  6896. /**
  6897. * If there are still attempts, we calculate a new battle
  6898. * Если попытки еще есть делаем расчет нового боя
  6899. */
  6900. if (attempts > 0) {
  6901. attempts--;
  6902. calcBattleResult(battlesInfo)
  6903. .then(resultCalcBattle);
  6904. return;
  6905. }
  6906. /**
  6907. * Otherwise, go to the next opponent
  6908. * Иначе переходим к следующему сопернику
  6909. */
  6910. roundRivals();
  6911. }
  6912. /**
  6913. * Processing the results of the battle calculation
  6914. *
  6915. * Обработка результатов расчета битвы
  6916. */
  6917. async function resultCalcBattle(resultBattle) {
  6918. // console.log('resultCalcBattle', currentRival, attempts, resultBattle.result.win);
  6919. /**
  6920. * If the current calculation of victory is not a chance or the attempt ended with the finish the battle
  6921. * Если текущий расчет победа или шансов нет или попытки кончились завершаем бой
  6922. */
  6923. if (resultBattle.result.win || !attempts) {
  6924. let { progress, result } = resultBattle;
  6925. if (!resultBattle.result.win && isChecked('tryFixIt_v2')) {
  6926. const bFix = new BestOrWinFixBattle(resultBattle.battleData);
  6927. const resultFix = await bFix.start(Date.now() + 6e4, 300);
  6928. progress = resultFix.progress;
  6929. result = resultFix.result;
  6930. }
  6931. titanArenaEndBattle({
  6932. progress,
  6933. result,
  6934. rivalId: resultBattle.battleData.typeId,
  6935. });
  6936. return;
  6937. }
  6938. /**
  6939. * If not victory and there are attempts we start a new battle
  6940. * Если не победа и есть попытки начинаем новый бой
  6941. */
  6942. titanArenaStartBattle(resultBattle.battleData.typeId);
  6943. }
  6944. /**
  6945. * Returns the promise of calculating the results of the battle
  6946. *
  6947. * Возращает промис расчета результатов битвы
  6948. */
  6949. function getBattleInfo(battle, isRandSeed) {
  6950. return new Promise(function (resolve) {
  6951. battle = structuredClone(battle);
  6952. if (isRandSeed) {
  6953. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  6954. }
  6955. // console.log(battle.seed);
  6956. BattleCalc(battle, "get_titanClanPvp", e => resolve(e));
  6957. });
  6958. }
  6959. /**
  6960. * Recalculate battles
  6961. *
  6962. * Прерасчтет битвы
  6963. */
  6964. function preCalcBattle(battle) {
  6965. let actions = [getBattleInfo(battle, false)];
  6966. const countTestBattle = getInput('countTestBattle');
  6967. for (let i = 0; i < countTestBattle; i++) {
  6968. actions.push(getBattleInfo(battle, true));
  6969. }
  6970. Promise.all(actions)
  6971. .then(resultPreCalcBattle);
  6972. }
  6973. /**
  6974. * Processing the results of the battle recalculation
  6975. *
  6976. * Обработка результатов прерасчета битвы
  6977. */
  6978. function resultPreCalcBattle(e) {
  6979. let wins = e.map(n => n.result.win);
  6980. let firstBattle = e.shift();
  6981. let countWin = wins.reduce((w, s) => w + s);
  6982. const countTestBattle = getInput('countTestBattle');
  6983. console.log('resultPreCalcBattle', `${countWin}/${countTestBattle}`)
  6984. if (countWin > 0) {
  6985. attempts = getInput('countAutoBattle');
  6986. } else {
  6987. attempts = 0;
  6988. }
  6989. resultCalcBattle(firstBattle);
  6990. }
  6991.  
  6992. /**
  6993. * Complete an arena battle
  6994. *
  6995. * Завершить битву на арене
  6996. */
  6997. function titanArenaEndBattle(args) {
  6998. let calls = [{
  6999. name: "titanArenaEndBattle",
  7000. args,
  7001. ident: "body"
  7002. }];
  7003. send(JSON.stringify({calls}), resultTitanArenaEndBattle);
  7004. }
  7005.  
  7006. function resultTitanArenaEndBattle(e) {
  7007. let attackScore = e.results[0].result.response.attackScore;
  7008. let numReval = countRivalsTier - finishListBattle.length;
  7009. setProgress(`${I18N('TITAN_ARENA')}: ${I18N('LEVEL')} ${currTier} </br>${I18N('BATTLES')}: ${numReval}/${countRivalsTier} - ${attackScore}`);
  7010. // console.log('resultTitanArenaEndBattle', e)
  7011. console.log('resultTitanArenaEndBattle', numReval + '/' + countRivalsTier, attempts)
  7012. roundRivals();
  7013. }
  7014. /**
  7015. * Arena State
  7016. *
  7017. * Состояние арены
  7018. */
  7019. function titanArenaGetStatus() {
  7020. let calls = [{
  7021. name: "titanArenaGetStatus",
  7022. args: {},
  7023. ident: "body"
  7024. }];
  7025. send(JSON.stringify({calls}), checkResultInfo);
  7026. }
  7027. /**
  7028. * Arena Raid Request
  7029. *
  7030. * Запрос рейда арены
  7031. */
  7032. function titanArenaStartRaid() {
  7033. let calls = [{
  7034. name: "titanArenaStartRaid",
  7035. args: {
  7036. titans: titan_arena
  7037. },
  7038. ident: "body"
  7039. }];
  7040. send(JSON.stringify({calls}), calcResults);
  7041. }
  7042.  
  7043. function calcResults(data) {
  7044. let battlesInfo = data.results[0].result.response;
  7045. let {attackers, rivals} = battlesInfo;
  7046.  
  7047. let promises = [];
  7048. for (let n in rivals) {
  7049. rival = rivals[n];
  7050. promises.push(calcBattleResult({
  7051. attackers: attackers,
  7052. defenders: [rival.team],
  7053. seed: rival.seed,
  7054. typeId: n,
  7055. }));
  7056. }
  7057.  
  7058. Promise.all(promises)
  7059. .then(results => {
  7060. const endResults = {};
  7061. for (let info of results) {
  7062. let id = info.battleData.typeId;
  7063. endResults[id] = {
  7064. progress: info.progress,
  7065. result: info.result,
  7066. }
  7067. }
  7068. titanArenaEndRaid(endResults);
  7069. });
  7070. }
  7071.  
  7072. function calcBattleResult(battleData) {
  7073. return new Promise(function (resolve, reject) {
  7074. BattleCalc(battleData, "get_titanClanPvp", resolve);
  7075. });
  7076. }
  7077.  
  7078. /**
  7079. * Sending Raid Results
  7080. *
  7081. * Отправка результатов рейда
  7082. */
  7083. function titanArenaEndRaid(results) {
  7084. titanArenaEndRaidCall = {
  7085. calls: [{
  7086. name: "titanArenaEndRaid",
  7087. args: {
  7088. results
  7089. },
  7090. ident: "body"
  7091. }]
  7092. }
  7093. send(JSON.stringify(titanArenaEndRaidCall), checkRaidResults);
  7094. }
  7095.  
  7096. function checkRaidResults(data) {
  7097. results = data.results[0].result.response.results;
  7098. isSucsesRaid = true;
  7099. for (let i in results) {
  7100. isSucsesRaid &&= (results[i].attackScore >= 250);
  7101. }
  7102.  
  7103. if (isSucsesRaid) {
  7104. titanArenaCompleteTier();
  7105. } else {
  7106. titanArenaGetStatus();
  7107. }
  7108. }
  7109.  
  7110. function titanArenaFarmDailyReward() {
  7111. titanArenaFarmDailyRewardCall = {
  7112. calls: [{
  7113. name: "titanArenaFarmDailyReward",
  7114. args: {},
  7115. ident: "body"
  7116. }]
  7117. }
  7118. send(JSON.stringify(titanArenaFarmDailyRewardCall), () => {console.log('Done farm daily reward')});
  7119. }
  7120.  
  7121. function endTitanArena(reason, info) {
  7122. if (!['Peace_time', 'disabled'].includes(reason)) {
  7123. titanArenaFarmDailyReward();
  7124. }
  7125. console.log(reason, info);
  7126. setProgress(`${I18N('TITAN_ARENA')} ${I18N('COMPLETED')}!`, true);
  7127. resolve();
  7128. }
  7129. }
  7130.  
  7131. this.HWHClasses.executeTitanArena = executeTitanArena;
  7132.  
  7133. function hackGame() {
  7134. const self = this;
  7135. selfGame = null;
  7136. bindId = 1e9;
  7137. this.libGame = null;
  7138. this.doneLibLoad = () => {};
  7139.  
  7140. /**
  7141. * List of correspondence of used classes to their names
  7142. *
  7143. * Список соответствия используемых классов их названиям
  7144. */
  7145. ObjectsList = [
  7146. { name: 'BattlePresets', prop: 'game.battle.controller.thread.BattlePresets' },
  7147. { name: 'DataStorage', prop: 'game.data.storage.DataStorage' },
  7148. { name: 'BattleConfigStorage', prop: 'game.data.storage.battle.BattleConfigStorage' },
  7149. { name: 'BattleInstantPlay', prop: 'game.battle.controller.instant.BattleInstantPlay' },
  7150. { name: 'MultiBattleInstantReplay', prop: 'game.battle.controller.instant.MultiBattleInstantReplay' },
  7151. { name: 'MultiBattleResult', prop: 'game.battle.controller.MultiBattleResult' },
  7152.  
  7153. { name: 'PlayerMissionData', prop: 'game.model.user.mission.PlayerMissionData' },
  7154. { name: 'PlayerMissionBattle', prop: 'game.model.user.mission.PlayerMissionBattle' },
  7155. { name: 'GameModel', prop: 'game.model.GameModel' },
  7156. { name: 'CommandManager', prop: 'game.command.CommandManager' },
  7157. { name: 'MissionCommandList', prop: 'game.command.rpc.mission.MissionCommandList' },
  7158. { name: 'RPCCommandBase', prop: 'game.command.rpc.RPCCommandBase' },
  7159. { name: 'PlayerTowerData', prop: 'game.model.user.tower.PlayerTowerData' },
  7160. { name: 'TowerCommandList', prop: 'game.command.tower.TowerCommandList' },
  7161. { name: 'PlayerHeroTeamResolver', prop: 'game.model.user.hero.PlayerHeroTeamResolver' },
  7162. { name: 'BattlePausePopup', prop: 'game.view.popup.battle.BattlePausePopup' },
  7163. { name: 'BattlePopup', prop: 'game.view.popup.battle.BattlePopup' },
  7164. { name: 'DisplayObjectContainer', prop: 'starling.display.DisplayObjectContainer' },
  7165. { name: 'GuiClipContainer', prop: 'engine.core.clipgui.GuiClipContainer' },
  7166. { name: 'BattlePausePopupClip', prop: 'game.view.popup.battle.BattlePausePopupClip' },
  7167. { name: 'ClipLabel', prop: 'game.view.gui.components.ClipLabel' },
  7168. { name: 'ClipLabelBase', prop: 'game.view.gui.components.ClipLabelBase' },
  7169. { name: 'Translate', prop: 'com.progrestar.common.lang.Translate' },
  7170. { name: 'ClipButtonLabeledCentered', prop: 'game.view.gui.components.ClipButtonLabeledCentered' },
  7171. { name: 'BattlePausePopupMediator', prop: 'game.mediator.gui.popup.battle.BattlePausePopupMediator' },
  7172. { name: 'SettingToggleButton', prop: 'game.mechanics.settings.popup.view.SettingToggleButton' },
  7173. { name: 'PlayerDungeonData', prop: 'game.mechanics.dungeon.model.PlayerDungeonData' },
  7174. { name: 'NextDayUpdatedManager', prop: 'game.model.user.NextDayUpdatedManager' },
  7175. { name: 'BattleController', prop: 'game.battle.controller.BattleController' },
  7176. { name: 'BattleSettingsModel', prop: 'game.battle.controller.BattleSettingsModel' },
  7177. { name: 'BooleanProperty', prop: 'engine.core.utils.property.BooleanProperty' },
  7178. { name: 'RuleStorage', prop: 'game.data.storage.rule.RuleStorage' },
  7179. { name: 'BattleConfig', prop: 'battle.BattleConfig' },
  7180. { name: 'BattleGuiMediator', prop: 'game.battle.gui.BattleGuiMediator' },
  7181. { name: 'BooleanPropertyWriteable', prop: 'engine.core.utils.property.BooleanPropertyWriteable' },
  7182. { name: 'BattleLogEncoder', prop: 'battle.log.BattleLogEncoder' },
  7183. { name: 'BattleLogReader', prop: 'battle.log.BattleLogReader' },
  7184. { name: 'PlayerSubscriptionInfoValueObject', prop: 'game.model.user.subscription.PlayerSubscriptionInfoValueObject' },
  7185. { name: 'AdventureMapCamera', prop: 'game.mechanics.adventure.popup.map.AdventureMapCamera' },
  7186. ];
  7187.  
  7188. /**
  7189. * Contains the game classes needed to write and override game methods
  7190. *
  7191. * Содержит классы игры необходимые для написания и подмены методов игры
  7192. */
  7193. Game = {
  7194. /**
  7195. * Function 'e'
  7196. * Функция 'e'
  7197. */
  7198. bindFunc: function (a, b) {
  7199. if (null == b) return null;
  7200. null == b.__id__ && (b.__id__ = bindId++);
  7201. var c;
  7202. null == a.hx__closures__ ? (a.hx__closures__ = {}) : (c = a.hx__closures__[b.__id__]);
  7203. null == c && ((c = b.bind(a)), (a.hx__closures__[b.__id__] = c));
  7204. return c;
  7205. },
  7206. };
  7207.  
  7208. /**
  7209. * Connects to game objects via the object creation event
  7210. *
  7211. * Подключается к объектам игры через событие создания объекта
  7212. */
  7213. function connectGame() {
  7214. for (let obj of ObjectsList) {
  7215. /**
  7216. * https: //stackoverflow.com/questions/42611719/how-to-intercept-and-modify-a-specific-property-for-any-object
  7217. */
  7218. Object.defineProperty(Object.prototype, obj.prop, {
  7219. set: function (value) {
  7220. if (!selfGame) {
  7221. selfGame = this;
  7222. }
  7223. if (!Game[obj.name]) {
  7224. Game[obj.name] = value;
  7225. }
  7226. // console.log('set ' + obj.prop, this, value);
  7227. this[obj.prop + '_'] = value;
  7228. },
  7229. get: function () {
  7230. // console.log('get ' + obj.prop, this);
  7231. return this[obj.prop + '_'];
  7232. },
  7233. });
  7234. }
  7235. }
  7236.  
  7237. /**
  7238. * Game.BattlePresets
  7239. * @param {bool} a isReplay
  7240. * @param {bool} b autoToggleable
  7241. * @param {bool} c auto On Start
  7242. * @param {object} d config
  7243. * @param {bool} f showBothTeams
  7244. */
  7245. /**
  7246. * Returns the results of the battle to the callback function
  7247. * Возвращает в функцию callback результаты боя
  7248. * @param {*} battleData battle data данные боя
  7249. * @param {*} battleConfig combat configuration type options:
  7250. *
  7251. * тип конфигурации боя варианты:
  7252. *
  7253. * "get_invasion", "get_titanPvpManual", "get_titanPvp",
  7254. * "get_titanClanPvp","get_clanPvp","get_titan","get_boss",
  7255. * "get_tower","get_pve","get_pvpManual","get_pvp","get_core"
  7256. *
  7257. * You can specify the xYc function in the game.assets.storage.BattleAssetStorage class
  7258. *
  7259. * Можно уточнить в классе game.assets.storage.BattleAssetStorage функция xYc
  7260. * @param {*} callback функция в которую вернуться результаты боя
  7261. */
  7262. this.BattleCalc = function (battleData, battleConfig, callback) {
  7263. // battleConfig = battleConfig || getBattleType(battleData.type)
  7264. if (!Game.BattlePresets) throw Error('Use connectGame');
  7265. battlePresets = new Game.BattlePresets(
  7266. battleData.progress,
  7267. !1,
  7268. !0,
  7269. Game.DataStorage[getFn(Game.DataStorage, 24)][getF(Game.BattleConfigStorage, battleConfig)](),
  7270. !1
  7271. );
  7272. let battleInstantPlay;
  7273. if (battleData.progress?.length > 1) {
  7274. battleInstantPlay = new Game.MultiBattleInstantReplay(battleData, battlePresets);
  7275. } else {
  7276. battleInstantPlay = new Game.BattleInstantPlay(battleData, battlePresets);
  7277. }
  7278. battleInstantPlay[getProtoFn(Game.BattleInstantPlay, 9)].add((battleInstant) => {
  7279. const MBR_2 = getProtoFn(Game.MultiBattleResult, 2);
  7280. const battleResults = battleInstant[getF(Game.BattleInstantPlay, 'get_result')]();
  7281. const battleData = battleInstant[getF(Game.BattleInstantPlay, 'get_rawBattleInfo')]();
  7282. const battleLogs = [];
  7283. const timeLimit = battlePresets[getF(Game.BattlePresets, 'get_timeLimit')]();
  7284. let battleTime = 0;
  7285. let battleTimer = 0;
  7286. for (const battleResult of battleResults[MBR_2]) {
  7287. const battleLog = Game.BattleLogEncoder.read(new Game.BattleLogReader(battleResult));
  7288. battleLogs.push(battleLog);
  7289. const maxTime = Math.max(...battleLog.map((e) => (e.time < timeLimit && e.time !== 168.8 ? e.time : 0)));
  7290. battleTimer += getTimer(maxTime);
  7291. battleTime += maxTime;
  7292. }
  7293. callback({
  7294. battleLogs,
  7295. battleTime,
  7296. battleTimer,
  7297. battleData,
  7298. progress: battleResults[getF(Game.MultiBattleResult, 'get_progress')](),
  7299. result: battleResults[getF(Game.MultiBattleResult, 'get_result')](),
  7300. });
  7301. });
  7302. battleInstantPlay.start();
  7303. };
  7304.  
  7305. /**
  7306. * Returns a function with the specified name from the class
  7307. *
  7308. * Возвращает из класса функцию с указанным именем
  7309. * @param {Object} classF Class // класс
  7310. * @param {String} nameF function name // имя функции
  7311. * @param {String} pos name and alias order // порядок имени и псевдонима
  7312. * @returns
  7313. */
  7314. function getF(classF, nameF, pos) {
  7315. pos = pos || false;
  7316. let prop = Object.entries(classF.prototype.__properties__);
  7317. if (!pos) {
  7318. return prop.filter((e) => e[1] == nameF).pop()[0];
  7319. } else {
  7320. return prop.filter((e) => e[0] == nameF).pop()[1];
  7321. }
  7322. }
  7323.  
  7324. /**
  7325. * Returns a function with the specified name from the class
  7326. *
  7327. * Возвращает из класса функцию с указанным именем
  7328. * @param {Object} classF Class // класс
  7329. * @param {String} nameF function name // имя функции
  7330. * @returns
  7331. */
  7332. function getFnP(classF, nameF) {
  7333. let prop = Object.entries(classF.__properties__);
  7334. return prop.filter((e) => e[1] == nameF).pop()[0];
  7335. }
  7336.  
  7337. /**
  7338. * Returns the function name with the specified ordinal from the class
  7339. *
  7340. * Возвращает имя функции с указаным порядковым номером из класса
  7341. * @param {Object} classF Class // класс
  7342. * @param {Number} nF Order number of function // порядковый номер функции
  7343. * @returns
  7344. */
  7345. function getFn(classF, nF) {
  7346. let prop = Object.keys(classF);
  7347. return prop[nF];
  7348. }
  7349.  
  7350. /**
  7351. * Returns the name of the function with the specified serial number from the prototype of the class
  7352. *
  7353. * Возвращает имя функции с указаным порядковым номером из прототипа класса
  7354. * @param {Object} classF Class // класс
  7355. * @param {Number} nF Order number of function // порядковый номер функции
  7356. * @returns
  7357. */
  7358. function getProtoFn(classF, nF) {
  7359. let prop = Object.keys(classF.prototype);
  7360. return prop[nF];
  7361. }
  7362.  
  7363. function findInstanceOf(obj, targetClass) {
  7364. const prototypeKeys = Object.keys(Object.getPrototypeOf(obj));
  7365. const matchingKey = prototypeKeys.find((key) => obj[key] instanceof targetClass);
  7366. return matchingKey ? obj[matchingKey] : null;
  7367. }
  7368. /**
  7369. * Description of replaced functions
  7370. *
  7371. * Описание подменяемых функций
  7372. */
  7373. replaceFunction = {
  7374. company: function () {
  7375. let PMD_12 = getProtoFn(Game.PlayerMissionData, 12);
  7376. let oldSkipMisson = Game.PlayerMissionData.prototype[PMD_12];
  7377. Game.PlayerMissionData.prototype[PMD_12] = function (a, b, c) {
  7378. if (!isChecked('passBattle')) {
  7379. oldSkipMisson.call(this, a, b, c);
  7380. return;
  7381. }
  7382.  
  7383. try {
  7384. this[getProtoFn(Game.PlayerMissionData, 9)] = new Game.PlayerMissionBattle(a, b, c);
  7385.  
  7386. var a = new Game.BattlePresets(
  7387. !1,
  7388. !1,
  7389. !0,
  7390. Game.DataStorage[getFn(Game.DataStorage, 24)][getProtoFn(Game.BattleConfigStorage, 20)](),
  7391. !1
  7392. );
  7393. a = new Game.BattleInstantPlay(c, a);
  7394. a[getProtoFn(Game.BattleInstantPlay, 9)].add(Game.bindFunc(this, this.P$h));
  7395. a.start();
  7396. } catch (error) {
  7397. console.error('company', error);
  7398. oldSkipMisson.call(this, a, b, c);
  7399. }
  7400. };
  7401.  
  7402. Game.PlayerMissionData.prototype.P$h = function (a) {
  7403. let GM_2 = getFn(Game.GameModel, 2);
  7404. let GM_P2 = getProtoFn(Game.GameModel, 2);
  7405. let CM_21 = getProtoFn(Game.CommandManager, 21);
  7406. let MCL_2 = getProtoFn(Game.MissionCommandList, 2);
  7407. let MBR_15 = getF(Game.MultiBattleResult, 'get_result');
  7408. let RPCCB_17 = getProtoFn(Game.RPCCommandBase, 17);
  7409. let PMD_34 = getProtoFn(Game.PlayerMissionData, 34);
  7410. Game.GameModel[GM_2]()[GM_P2][CM_21][MCL_2](a[MBR_15]())[RPCCB_17](Game.bindFunc(this, this[PMD_34]));
  7411. };
  7412. },
  7413. /*
  7414. tower: function () {
  7415. let PTD_67 = getProtoFn(Game.PlayerTowerData, 67);
  7416. let oldSkipTower = Game.PlayerTowerData.prototype[PTD_67];
  7417. Game.PlayerTowerData.prototype[PTD_67] = function (a) {
  7418. if (!isChecked('passBattle')) {
  7419. oldSkipTower.call(this, a);
  7420. return;
  7421. }
  7422. try {
  7423. var p = new Game.BattlePresets(
  7424. !1,
  7425. !1,
  7426. !0,
  7427. Game.DataStorage[getFn(Game.DataStorage, 24)][getProtoFn(Game.BattleConfigStorage, 20)](),
  7428. !1
  7429. );
  7430. a = new Game.BattleInstantPlay(a, p);
  7431. a[getProtoFn(Game.BattleInstantPlay, 9)].add(Game.bindFunc(this, this.P$h));
  7432. a.start();
  7433. } catch (error) {
  7434. console.error('tower', error);
  7435. oldSkipMisson.call(this, a, b, c);
  7436. }
  7437. };
  7438.  
  7439. Game.PlayerTowerData.prototype.P$h = function (a) {
  7440. const GM_2 = getFnP(Game.GameModel, 'get_instance');
  7441. const GM_P2 = getProtoFn(Game.GameModel, 2);
  7442. const CM_29 = getProtoFn(Game.CommandManager, 29);
  7443. const TCL_5 = getProtoFn(Game.TowerCommandList, 5);
  7444. const MBR_15 = getF(Game.MultiBattleResult, 'get_result');
  7445. const RPCCB_15 = getProtoFn(Game.RPCCommandBase, 17);
  7446. const PTD_78 = getProtoFn(Game.PlayerTowerData, 78);
  7447. Game.GameModel[GM_2]()[GM_P2][CM_29][TCL_5](a[MBR_15]())[RPCCB_15](Game.bindFunc(this, this[PTD_78]));
  7448. };
  7449. },
  7450. */
  7451. // skipSelectHero: function() {
  7452. // if (!HOST) throw Error('Use connectGame');
  7453. // Game.PlayerHeroTeamResolver.prototype[getProtoFn(Game.PlayerHeroTeamResolver, 3)] = () => false;
  7454. // },
  7455. passBattle: function () {
  7456. let BPP_4 = getProtoFn(Game.BattlePausePopup, 4);
  7457. let oldPassBattle = Game.BattlePausePopup.prototype[BPP_4];
  7458. Game.BattlePausePopup.prototype[BPP_4] = function (a) {
  7459. if (!isChecked('passBattle')) {
  7460. oldPassBattle.call(this, a);
  7461. return;
  7462. }
  7463. try {
  7464. Game.BattlePopup.prototype[getProtoFn(Game.BattlePausePopup, 4)].call(this, a);
  7465. this[getProtoFn(Game.BattlePausePopup, 3)]();
  7466. this[getProtoFn(Game.DisplayObjectContainer, 3)](this.clip[getProtoFn(Game.GuiClipContainer, 2)]());
  7467. this.clip[getProtoFn(Game.BattlePausePopupClip, 1)][getProtoFn(Game.ClipLabelBase, 9)](
  7468. Game.Translate.translate('UI_POPUP_BATTLE_PAUSE')
  7469. );
  7470.  
  7471. this.clip[getProtoFn(Game.BattlePausePopupClip, 2)][getProtoFn(Game.ClipButtonLabeledCentered, 2)](
  7472. Game.Translate.translate('UI_POPUP_BATTLE_RETREAT'),
  7473. ((q = this[getProtoFn(Game.BattlePausePopup, 1)]), Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 17)]))
  7474. );
  7475. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 2)](
  7476. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 14)](),
  7477. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 13)]()
  7478. ? ((q = this[getProtoFn(Game.BattlePausePopup, 1)]), Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 18)]))
  7479. : ((q = this[getProtoFn(Game.BattlePausePopup, 1)]), Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 18)]))
  7480. );
  7481.  
  7482. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 0)][
  7483. getProtoFn(Game.ClipLabelBase, 24)
  7484. ]();
  7485. this.clip[getProtoFn(Game.BattlePausePopupClip, 3)][getProtoFn(Game.SettingToggleButton, 3)](
  7486. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 9)]()
  7487. );
  7488. this.clip[getProtoFn(Game.BattlePausePopupClip, 4)][getProtoFn(Game.SettingToggleButton, 3)](
  7489. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 10)]()
  7490. );
  7491. this.clip[getProtoFn(Game.BattlePausePopupClip, 6)][getProtoFn(Game.SettingToggleButton, 3)](
  7492. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 11)]()
  7493. );
  7494. } catch (error) {
  7495. console.error('passBattle', error);
  7496. oldPassBattle.call(this, a);
  7497. }
  7498. };
  7499.  
  7500. let retreatButtonLabel = getF(Game.BattlePausePopupMediator, 'get_retreatButtonLabel');
  7501. let oldFunc = Game.BattlePausePopupMediator.prototype[retreatButtonLabel];
  7502. Game.BattlePausePopupMediator.prototype[retreatButtonLabel] = function () {
  7503. if (isChecked('passBattle')) {
  7504. return I18N('BTN_PASS');
  7505. } else {
  7506. return oldFunc.call(this);
  7507. }
  7508. };
  7509. },
  7510. endlessCards: function () {
  7511. let PDD_21 = getProtoFn(Game.PlayerDungeonData, 21);
  7512. let oldEndlessCards = Game.PlayerDungeonData.prototype[PDD_21];
  7513. Game.PlayerDungeonData.prototype[PDD_21] = function () {
  7514. if (countPredictionCard <= 0) {
  7515. return true;
  7516. } else {
  7517. return oldEndlessCards.call(this);
  7518. }
  7519. };
  7520. },
  7521. speedBattle: function () {
  7522. const get_timeScale = getF(Game.BattleController, 'get_timeScale');
  7523. const oldSpeedBattle = Game.BattleController.prototype[get_timeScale];
  7524. Game.BattleController.prototype[get_timeScale] = function () {
  7525. const speedBattle = Number.parseFloat(getInput('speedBattle'));
  7526. if (!speedBattle) {
  7527. return oldSpeedBattle.call(this);
  7528. }
  7529. try {
  7530. const BC_12 = getProtoFn(Game.BattleController, 12);
  7531. const BSM_12 = getProtoFn(Game.BattleSettingsModel, 12);
  7532. const BP_get_value = getF(Game.BooleanProperty, 'get_value');
  7533. if (this[BC_12][BSM_12][BP_get_value]()) {
  7534. return 0;
  7535. }
  7536. const BSM_2 = getProtoFn(Game.BattleSettingsModel, 2);
  7537. const BC_49 = getProtoFn(Game.BattleController, 49);
  7538. const BSM_1 = getProtoFn(Game.BattleSettingsModel, 1);
  7539. const BC_14 = getProtoFn(Game.BattleController, 14);
  7540. const BC_3 = getFn(Game.BattleController, 3);
  7541. if (this[BC_12][BSM_2][BP_get_value]()) {
  7542. var a = speedBattle * this[BC_49]();
  7543. } else {
  7544. a = this[BC_12][BSM_1][BP_get_value]();
  7545. const maxSpeed = Math.max(...this[BC_14]);
  7546. const multiple = a == this[BC_14].indexOf(maxSpeed) ? (maxSpeed >= 4 ? speedBattle : this[BC_14][a]) : this[BC_14][a];
  7547. a = multiple * Game.BattleController[BC_3][BP_get_value]() * this[BC_49]();
  7548. }
  7549. const BSM_24 = getProtoFn(Game.BattleSettingsModel, 24);
  7550. a > this[BC_12][BSM_24][BP_get_value]() && (a = this[BC_12][BSM_24][BP_get_value]());
  7551. const DS_23 = getFn(Game.DataStorage, 23);
  7552. const get_battleSpeedMultiplier = getF(Game.RuleStorage, 'get_battleSpeedMultiplier', true);
  7553. var b = Game.DataStorage[DS_23][get_battleSpeedMultiplier]();
  7554. const R_1 = getFn(selfGame.Reflect, 1);
  7555. const BC_1 = getFn(Game.BattleController, 1);
  7556. const get_config = getF(Game.BattlePresets, 'get_config');
  7557. null != b &&
  7558. (a = selfGame.Reflect[R_1](b, this[BC_1][get_config]().ident)
  7559. ? a * selfGame.Reflect[R_1](b, this[BC_1][get_config]().ident)
  7560. : a * selfGame.Reflect[R_1](b, 'default'));
  7561. return a;
  7562. } catch (error) {
  7563. console.error('passBatspeedBattletle', error);
  7564. return oldSpeedBattle.call(this);
  7565. }
  7566. };
  7567. },
  7568.  
  7569. /**
  7570. * Acceleration button without Valkyries favor
  7571. *
  7572. * Кнопка ускорения без Покровительства Валькирий
  7573. */
  7574. battleFastKey: function () {
  7575. const BGM_44 = getProtoFn(Game.BattleGuiMediator, 44);
  7576. const oldBattleFastKey = Game.BattleGuiMediator.prototype[BGM_44];
  7577. Game.BattleGuiMediator.prototype[BGM_44] = function () {
  7578. let flag = true;
  7579. //console.log(flag)
  7580. if (!flag) {
  7581. return oldBattleFastKey.call(this);
  7582. }
  7583. try {
  7584. const BGM_9 = getProtoFn(Game.BattleGuiMediator, 9);
  7585. const BGM_10 = getProtoFn(Game.BattleGuiMediator, 10);
  7586. const BPW_0 = getProtoFn(Game.BooleanPropertyWriteable, 0);
  7587. this[BGM_9][BPW_0](true);
  7588. this[BGM_10][BPW_0](true);
  7589. } catch (error) {
  7590. console.error(error);
  7591. return oldBattleFastKey.call(this);
  7592. }
  7593. };
  7594. },
  7595. fastSeason: function () {
  7596. const GameNavigator = selfGame['game.screen.navigator.GameNavigator'];
  7597. const oldFuncName = getProtoFn(GameNavigator, 18);
  7598. const newFuncName = getProtoFn(GameNavigator, 16);
  7599. const oldFastSeason = GameNavigator.prototype[oldFuncName];
  7600. const newFastSeason = GameNavigator.prototype[newFuncName];
  7601. GameNavigator.prototype[oldFuncName] = function (a, b) {
  7602. if (isChecked('fastSeason')) {
  7603. return newFastSeason.apply(this, [a]);
  7604. } else {
  7605. return oldFastSeason.apply(this, [a, b]);
  7606. }
  7607. };
  7608. },
  7609. ShowChestReward: function () {
  7610. const TitanArtifactChest = selfGame['game.mechanics.titan_arena.mediator.chest.TitanArtifactChestRewardPopupMediator'];
  7611. const getOpenAmountTitan = getF(TitanArtifactChest, 'get_openAmount');
  7612. const oldGetOpenAmountTitan = TitanArtifactChest.prototype[getOpenAmountTitan];
  7613. TitanArtifactChest.prototype[getOpenAmountTitan] = function () {
  7614. if (correctShowOpenArtifact) {
  7615. correctShowOpenArtifact--;
  7616. return 100;
  7617. }
  7618. return oldGetOpenAmountTitan.call(this);
  7619. };
  7620.  
  7621. const ArtifactChest = selfGame['game.view.popup.artifactchest.rewardpopup.ArtifactChestRewardPopupMediator'];
  7622. const getOpenAmount = getF(ArtifactChest, 'get_openAmount');
  7623. const oldGetOpenAmount = ArtifactChest.prototype[getOpenAmount];
  7624. ArtifactChest.prototype[getOpenAmount] = function () {
  7625. if (correctShowOpenArtifact) {
  7626. correctShowOpenArtifact--;
  7627. return 100;
  7628. }
  7629. return oldGetOpenAmount.call(this);
  7630. };
  7631. },
  7632. fixCompany: function () {
  7633. const GameBattleView = selfGame['game.mediator.gui.popup.battle.GameBattleView'];
  7634. const BattleThread = selfGame['game.battle.controller.thread.BattleThread'];
  7635. const getOnViewDisposed = getF(BattleThread, 'get_onViewDisposed');
  7636. const getThread = getF(GameBattleView, 'get_thread');
  7637. const oldFunc = GameBattleView.prototype[getThread];
  7638. GameBattleView.prototype[getThread] = function () {
  7639. return (
  7640. oldFunc.call(this) || {
  7641. [getOnViewDisposed]: async () => {},
  7642. }
  7643. );
  7644. };
  7645. },
  7646. BuyTitanArtifact: function () {
  7647. const BIP_4 = getProtoFn(selfGame['game.view.popup.shop.buy.BuyItemPopup'], 4);
  7648. const BuyItemPopup = selfGame['game.view.popup.shop.buy.BuyItemPopup'];
  7649. const oldFunc = BuyItemPopup.prototype[BIP_4];
  7650. BuyItemPopup.prototype[BIP_4] = function () {
  7651. if (isChecked('countControl')) {
  7652. const BuyTitanArtifactItemPopup = selfGame['game.view.popup.shop.buy.BuyTitanArtifactItemPopup'];
  7653. const BTAP_0 = getProtoFn(BuyTitanArtifactItemPopup, 0);
  7654. if (this[BTAP_0]) {
  7655. const BuyTitanArtifactPopupMediator = selfGame['game.mediator.gui.popup.shop.buy.BuyTitanArtifactItemPopupMediator'];
  7656. const BTAM_1 = getProtoFn(BuyTitanArtifactPopupMediator, 1);
  7657. const BuyItemPopupMediator = selfGame['game.mediator.gui.popup.shop.buy.BuyItemPopupMediator'];
  7658. const BIPM_5 = getProtoFn(BuyItemPopupMediator, 5);
  7659. const BIPM_7 = getProtoFn(BuyItemPopupMediator, 7);
  7660. const BIPM_9 = getProtoFn(BuyItemPopupMediator, 9);
  7661.  
  7662. let need = Math.min(this[BTAP_0][BTAM_1](), this[BTAP_0][BIPM_7]);
  7663. need = need ? need : 60;
  7664. this[BTAP_0][BIPM_9] = need;
  7665. this[BTAP_0][BIPM_5] = 10;
  7666. }
  7667. }
  7668. oldFunc.call(this);
  7669. };
  7670. },
  7671. ClanQuestsFastFarm: function () {
  7672. const VipRuleValueObject = selfGame['game.data.storage.rule.VipRuleValueObject'];
  7673. const getClanQuestsFastFarm = getF(VipRuleValueObject, 'get_clanQuestsFastFarm', 1);
  7674. VipRuleValueObject.prototype[getClanQuestsFastFarm] = function () {
  7675. return 0;
  7676. };
  7677. },
  7678. adventureCamera: function () {
  7679. const AMC_40 = getProtoFn(Game.AdventureMapCamera, 40);
  7680. const AMC_5 = getProtoFn(Game.AdventureMapCamera, 5);
  7681. const oldFunc = Game.AdventureMapCamera.prototype[AMC_40];
  7682. Game.AdventureMapCamera.prototype[AMC_40] = function (a) {
  7683. this[AMC_5] = 0.4;
  7684. oldFunc.bind(this)(a);
  7685. };
  7686. },
  7687. unlockMission: function () {
  7688. const WorldMapStoryDrommerHelper = selfGame['game.mediator.gui.worldmap.WorldMapStoryDrommerHelper'];
  7689. const WMSDH_4 = getFn(WorldMapStoryDrommerHelper, 4);
  7690. const WMSDH_7 = getFn(WorldMapStoryDrommerHelper, 7);
  7691. WorldMapStoryDrommerHelper[WMSDH_4] = function () {
  7692. return true;
  7693. };
  7694. WorldMapStoryDrommerHelper[WMSDH_7] = function () {
  7695. return true;
  7696. };
  7697. },
  7698. doublePets: function () {
  7699. const TeamGatherPopupMediator = selfGame['game.mediator.gui.popup.team.TeamGatherPopupMediator'];
  7700. const InvasionBossTeamGatherPopupMediator = selfGame['game.mechanics.invasion.mediator.boss.InvasionBossTeamGatherPopupMediator'];
  7701. const TeamGatherPopupHeroValueObject = selfGame['game.mediator.gui.popup.team.TeamGatherPopupHeroValueObject'];
  7702. const ObjectPropertyWriteable = selfGame['engine.core.utils.property.ObjectPropertyWriteable'];
  7703. const TGPM_8 = getProtoFn(TeamGatherPopupMediator, 8);
  7704. const TGPM_45 = getProtoFn(TeamGatherPopupMediator, 45);
  7705. const TGPM_114 = getProtoFn(TeamGatherPopupMediator, 114);
  7706. const TGPM_117 = getProtoFn(TeamGatherPopupMediator, 117);
  7707. const TGPM_123 = getProtoFn(TeamGatherPopupMediator, 123);
  7708. const TGPM_135 = getProtoFn(TeamGatherPopupMediator, 135);
  7709. const TGPHVO_40 = getProtoFn(TeamGatherPopupHeroValueObject, 40);
  7710. const OPW_0 = getProtoFn(ObjectPropertyWriteable, 0);
  7711. const oldFunc = InvasionBossTeamGatherPopupMediator.prototype[TGPM_135];
  7712. InvasionBossTeamGatherPopupMediator.prototype[TGPM_135] = function (a, b) {
  7713. try {
  7714. if (b == 0) {
  7715. this[TGPM_8].remove(a);
  7716. } else {
  7717. this[TGPM_8].F[a] = b;
  7718. }
  7719. this[TGPM_114](this[TGPM_45], a)[TGPHVO_40][OPW_0](this[TGPM_117](b));
  7720. this[TGPM_123]();
  7721. return;
  7722. } catch (e) {}
  7723. oldFunc.call(this, a, b);
  7724. };
  7725. },
  7726. };
  7727.  
  7728. /**
  7729. * Starts replacing recorded functions
  7730. *
  7731. * Запускает замену записанных функций
  7732. */
  7733. this.activateHacks = function () {
  7734. if (!selfGame) throw Error('Use connectGame');
  7735. for (let func in replaceFunction) {
  7736. try {
  7737. replaceFunction[func]();
  7738. } catch (error) {
  7739. console.error(error);
  7740. }
  7741. }
  7742. };
  7743.  
  7744. /**
  7745. * Returns the game object
  7746. *
  7747. * Возвращает объект игры
  7748. */
  7749. this.getSelfGame = function () {
  7750. return selfGame;
  7751. };
  7752.  
  7753. /** Возвращает объект игры */
  7754. this.getGame = function () {
  7755. return Game;
  7756. };
  7757.  
  7758. /**
  7759. * Updates game data
  7760. *
  7761. * Обновляет данные игры
  7762. */
  7763. this.refreshGame = function () {
  7764. new Game.NextDayUpdatedManager()[getProtoFn(Game.NextDayUpdatedManager, 5)]();
  7765. try {
  7766. cheats.refreshInventory();
  7767. } catch (e) {}
  7768. };
  7769.  
  7770. /**
  7771. * Update inventory
  7772. *
  7773. * Обновляет инвентарь
  7774. */
  7775. this.refreshInventory = async function () {
  7776. const GM_INST = getFnP(Game.GameModel, 'get_instance');
  7777. const GM_0 = getProtoFn(Game.GameModel, 0);
  7778. const P_24 = getProtoFn(selfGame['game.model.user.Player'], 24);
  7779. const Player = Game.GameModel[GM_INST]()[GM_0];
  7780. Player[P_24] = new selfGame['game.model.user.inventory.PlayerInventory']();
  7781. Player[P_24].init(await Send({ calls: [{ name: 'inventoryGet', args: {}, ident: 'body' }] }).then((e) => e.results[0].result.response));
  7782. };
  7783. this.updateInventory = function (reward) {
  7784. const GM_INST = getFnP(Game.GameModel, 'get_instance');
  7785. const GM_0 = getProtoFn(Game.GameModel, 0);
  7786. const P_24 = getProtoFn(selfGame['game.model.user.Player'], 24);
  7787. const Player = Game.GameModel[GM_INST]()[GM_0];
  7788. Player[P_24].init(reward);
  7789. };
  7790.  
  7791. this.updateMap = function (data) {
  7792. const PCDD_21 = getProtoFn(selfGame['game.mechanics.clanDomination.model.PlayerClanDominationData'], 21);
  7793. const P_60 = getProtoFn(selfGame['game.model.user.Player'], 60);
  7794. const GM_0 = getProtoFn(Game.GameModel, 0);
  7795. const getInstance = getFnP(selfGame['Game'], 'get_instance');
  7796. const PlayerClanDominationData = Game.GameModel[getInstance]()[GM_0];
  7797. PlayerClanDominationData[P_60][PCDD_21].update(data);
  7798. };
  7799.  
  7800. /**
  7801. * Change the play screen on windowName
  7802. *
  7803. * Сменить экран игры на windowName
  7804. *
  7805. * Possible options:
  7806. *
  7807. * Возможные варианты:
  7808. *
  7809. * 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
  7810. */
  7811. this.goNavigtor = function (windowName) {
  7812. let mechanicStorage = selfGame['game.data.storage.mechanic.MechanicStorage'];
  7813. let window = mechanicStorage[windowName];
  7814. let event = new selfGame['game.mediator.gui.popup.PopupStashEventParams']();
  7815. let Game = selfGame['Game'];
  7816. let navigator = getF(Game, 'get_navigator');
  7817. let navigate = getProtoFn(selfGame['game.screen.navigator.GameNavigator'], 20);
  7818. let instance = getFnP(Game, 'get_instance');
  7819. Game[instance]()[navigator]()[navigate](window, event);
  7820. };
  7821.  
  7822. /**
  7823. * Move to the sanctuary cheats.goSanctuary()
  7824. *
  7825. * Переместиться в святилище cheats.goSanctuary()
  7826. */
  7827. this.goSanctuary = () => {
  7828. this.goNavigtor('SANCTUARY');
  7829. };
  7830.  
  7831. /** Перейти в Долину титанов */
  7832. this.goTitanValley = () => {
  7833. this.goNavigtor('TITAN_VALLEY');
  7834. };
  7835.  
  7836. /**
  7837. * Go to Guild War
  7838. *
  7839. * Перейти к Войне Гильдий
  7840. */
  7841. this.goClanWar = function () {
  7842. let instance = getFnP(Game.GameModel, 'get_instance');
  7843. let player = Game.GameModel[instance]().A;
  7844. let clanWarSelect = selfGame['game.mechanics.cross_clan_war.popup.selectMode.CrossClanWarSelectModeMediator'];
  7845. new clanWarSelect(player).open();
  7846. };
  7847.  
  7848. /** Перейти к Острову гильдии */
  7849. this.goClanIsland = function () {
  7850. let instance = getFnP(Game.GameModel, 'get_instance');
  7851. let player = Game.GameModel[instance]().A;
  7852. let clanIslandSelect = selfGame['game.view.gui.ClanIslandPopupMediator'];
  7853. new clanIslandSelect(player).open();
  7854. };
  7855.  
  7856. /**
  7857. * Go to BrawlShop
  7858. *
  7859. * Переместиться в BrawlShop
  7860. */
  7861. this.goBrawlShop = () => {
  7862. const instance = getFnP(Game.GameModel, 'get_instance');
  7863. const P_36 = getProtoFn(selfGame['game.model.user.Player'], 36);
  7864. const PSD_0 = getProtoFn(selfGame['game.model.user.shop.PlayerShopData'], 0);
  7865. const IM_0 = getProtoFn(selfGame['haxe.ds.IntMap'], 0);
  7866. const PSDE_4 = getProtoFn(selfGame['game.model.user.shop.PlayerShopDataEntry'], 4);
  7867.  
  7868. const player = Game.GameModel[instance]().A;
  7869. const shop = player[P_36][PSD_0][IM_0][1038][PSDE_4];
  7870. const shopPopup = new selfGame['game.mechanics.brawl.mediator.BrawlShopPopupMediator'](player, shop);
  7871. shopPopup.open(new selfGame['game.mediator.gui.popup.PopupStashEventParams']());
  7872. };
  7873.  
  7874. /**
  7875. * Returns all stores from game data
  7876. *
  7877. * Возвращает все магазины из данных игры
  7878. */
  7879. this.getShops = () => {
  7880. const instance = getFnP(Game.GameModel, 'get_instance');
  7881. const P_36 = getProtoFn(selfGame['game.model.user.Player'], 36);
  7882. const PSD_0 = getProtoFn(selfGame['game.model.user.shop.PlayerShopData'], 0);
  7883. const IM_0 = getProtoFn(selfGame['haxe.ds.IntMap'], 0);
  7884.  
  7885. const player = Game.GameModel[instance]().A;
  7886. return player[P_36][PSD_0][IM_0];
  7887. };
  7888.  
  7889. /**
  7890. * Returns the store from the game data by ID
  7891. *
  7892. * Возвращает магазин из данных игры по идетификатору
  7893. */
  7894. this.getShop = (id) => {
  7895. const PSDE_4 = getProtoFn(selfGame['game.model.user.shop.PlayerShopDataEntry'], 4);
  7896. const shops = this.getShops();
  7897. const shop = shops[id]?.[PSDE_4];
  7898. return shop;
  7899. };
  7900.  
  7901. /**
  7902. * Change island map
  7903. *
  7904. * Сменить карту острова
  7905. */
  7906. this.changeIslandMap = (mapId = 2) => {
  7907. const GameInst = getFnP(selfGame['Game'], 'get_instance');
  7908. const GM_0 = getProtoFn(Game.GameModel, 0);
  7909. const PSAD_31 = getProtoFn(selfGame['game.mechanics.season_adventure.model.PlayerSeasonAdventureData'], 31);
  7910. const Player = Game.GameModel[GameInst]()[GM_0];
  7911. const PlayerSeasonAdventureData = findInstanceOf(Player, selfGame['game.mechanics.season_adventure.model.PlayerSeasonAdventureData']);
  7912. PlayerSeasonAdventureData[PSAD_31]({ id: mapId, seasonAdventure: { id: mapId, startDate: 1701914400, endDate: 1709690400, closed: false } });
  7913.  
  7914. const GN_15 = getProtoFn(selfGame['game.screen.navigator.GameNavigator'], 17);
  7915. const navigator = getF(selfGame['Game'], 'get_navigator');
  7916. selfGame['Game'][GameInst]()[navigator]()[GN_15](new selfGame['game.mediator.gui.popup.PopupStashEventParams']());
  7917. };
  7918.  
  7919. /**
  7920. * Game library availability tracker
  7921. *
  7922. * Отслеживание доступности игровой библиотеки
  7923. */
  7924. function checkLibLoad() {
  7925. timeout = setTimeout(() => {
  7926. if (Game.GameModel) {
  7927. changeLib();
  7928. } else {
  7929. checkLibLoad();
  7930. }
  7931. }, 100);
  7932. }
  7933.  
  7934. /**
  7935. * Game library data spoofing
  7936. *
  7937. * Подмена данных игровой библиотеки
  7938. */
  7939. function changeLib() {
  7940. console.log('lib connect');
  7941. const originalStartFunc = Game.GameModel.prototype.start;
  7942. Game.GameModel.prototype.start = function (a, b, c) {
  7943. self.libGame = b.raw;
  7944. self.doneLibLoad(self.libGame);
  7945. try {
  7946. const levels = b.raw.seasonAdventure.level;
  7947. for (const id in levels) {
  7948. const level = levels[id];
  7949. level.clientData.graphics.fogged = level.clientData.graphics.visible;
  7950. }
  7951. const adv = b.raw.seasonAdventure.list[1];
  7952. adv.clientData.asset = 'dialog_season_adventure_tiles';
  7953. } catch (e) {
  7954. console.warn(e);
  7955. }
  7956. originalStartFunc.call(this, a, b, c);
  7957. };
  7958. }
  7959.  
  7960. this.LibLoad = function () {
  7961. return new Promise((e) => {
  7962. this.doneLibLoad = e;
  7963. });
  7964. };
  7965.  
  7966. /**
  7967. * Returns the value of a language constant
  7968. *
  7969. * Возвращает значение языковой константы
  7970. * @param {*} langConst language constant // языковая константа
  7971. * @returns
  7972. */
  7973. this.translate = function (langConst) {
  7974. return Game.Translate.translate(langConst);
  7975. };
  7976.  
  7977. connectGame();
  7978. checkLibLoad();
  7979. }
  7980.  
  7981. /**
  7982. * Auto collection of gifts
  7983. *
  7984. * Автосбор подарков
  7985. */
  7986. function getAutoGifts() {
  7987. // c3ltYm9scyB0aGF0IG1lYW4gbm90aGluZw==
  7988. let valName = 'giftSendIds_' + userInfo.id;
  7989.  
  7990. if (!localStorage['clearGift' + userInfo.id]) {
  7991. localStorage[valName] = '';
  7992. localStorage['clearGift' + userInfo.id] = '+';
  7993. }
  7994.  
  7995. if (!localStorage[valName]) {
  7996. localStorage[valName] = '';
  7997. }
  7998.  
  7999. const giftsAPI = new ZingerYWebsiteAPI('getGifts.php', arguments);
  8000. /**
  8001. * Submit a request to receive gift codes
  8002. *
  8003. * Отправка запроса для получения кодов подарков
  8004. */
  8005. giftsAPI.request().then((data) => {
  8006. let freebieCheckCalls = {
  8007. calls: [],
  8008. };
  8009. data.forEach((giftId, n) => {
  8010. if (localStorage[valName].includes(giftId)) return;
  8011. freebieCheckCalls.calls.push({
  8012. name: 'registration',
  8013. args: {
  8014. user: { referrer: {} },
  8015. giftId,
  8016. },
  8017. context: {
  8018. actionTs: Math.floor(performance.now()),
  8019. cookie: window?.NXAppInfo?.session_id || null,
  8020. },
  8021. ident: giftId,
  8022. });
  8023. });
  8024.  
  8025. if (!freebieCheckCalls.calls.length) {
  8026. return;
  8027. }
  8028.  
  8029. send(JSON.stringify(freebieCheckCalls), (e) => {
  8030. let countGetGifts = 0;
  8031. const gifts = [];
  8032. for (check of e.results) {
  8033. gifts.push(check.ident);
  8034. if (check.result.response != null) {
  8035. countGetGifts++;
  8036. }
  8037. }
  8038. const saveGifts = localStorage[valName].split(';');
  8039. localStorage[valName] = [...saveGifts, ...gifts].slice(-50).join(';');
  8040. console.log(`${I18N('GIFTS')}: ${countGetGifts}`);
  8041. });
  8042. });
  8043. }
  8044.  
  8045. /**
  8046. * To fill the kills in the Forge of Souls
  8047. *
  8048. * Набить килов в горниле душ
  8049. */
  8050. async function bossRatingEvent() {
  8051. const topGet = await Send(JSON.stringify({ calls: [{ name: "topGet", args: { type: "bossRatingTop", extraId: 0 }, ident: "body" }] }));
  8052. if (!topGet || !topGet.results[0].result.response[0]) {
  8053. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  8054. return;
  8055. }
  8056. const replayId = topGet.results[0].result.response[0].userData.replayId;
  8057. const result = await Send(JSON.stringify({
  8058. calls: [
  8059. { name: "battleGetReplay", args: { id: replayId }, ident: "battleGetReplay" },
  8060. { name: "heroGetAll", args: {}, ident: "heroGetAll" },
  8061. { name: "pet_getAll", args: {}, ident: "pet_getAll" },
  8062. { name: "offerGetAll", args: {}, ident: "offerGetAll" }
  8063. ]
  8064. }));
  8065. const bossEventInfo = result.results[3].result.response.find(e => e.offerType == "bossEvent");
  8066. if (!bossEventInfo) {
  8067. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  8068. return;
  8069. }
  8070. const usedHeroes = bossEventInfo.progress.usedHeroes;
  8071. const party = Object.values(result.results[0].result.response.replay.attackers);
  8072. const availableHeroes = Object.values(result.results[1].result.response).map(e => e.id);
  8073. const availablePets = Object.values(result.results[2].result.response).map(e => e.id);
  8074. const calls = [];
  8075. /**
  8076. * First pack
  8077. *
  8078. * Первая пачка
  8079. */
  8080. const args = {
  8081. heroes: [],
  8082. favor: {}
  8083. }
  8084. for (let hero of party) {
  8085. if (hero.id >= 6000 && availablePets.includes(hero.id)) {
  8086. args.pet = hero.id;
  8087. continue;
  8088. }
  8089. if (!availableHeroes.includes(hero.id) || usedHeroes.includes(hero.id)) {
  8090. continue;
  8091. }
  8092. args.heroes.push(hero.id);
  8093. if (hero.favorPetId) {
  8094. args.favor[hero.id] = hero.favorPetId;
  8095. }
  8096. }
  8097. if (args.heroes.length) {
  8098. calls.push({
  8099. name: 'bossRating_startBattle',
  8100. args,
  8101. ident: 'body_0',
  8102. });
  8103. }
  8104. /**
  8105. * Other packs
  8106. *
  8107. * Другие пачки
  8108. */
  8109. let heroes = [];
  8110. let count = 1;
  8111. while (heroId = availableHeroes.pop()) {
  8112. if (args.heroes.includes(heroId) || usedHeroes.includes(heroId)) {
  8113. continue;
  8114. }
  8115. heroes.push(heroId);
  8116. if (heroes.length == 5) {
  8117. calls.push({
  8118. name: 'bossRating_startBattle',
  8119. args: {
  8120. heroes: [...heroes],
  8121. pet: availablePets[Math.floor(Math.random() * availablePets.length)],
  8122. },
  8123. ident: 'body_' + count,
  8124. });
  8125. heroes = [];
  8126. count++;
  8127. }
  8128. }
  8129.  
  8130. if (!calls.length) {
  8131. setProgress(`${I18N('NO_HEROES')}`, true);
  8132. return;
  8133. }
  8134.  
  8135. const resultBattles = await Send(JSON.stringify({ calls }));
  8136. console.log(resultBattles);
  8137. rewardBossRatingEvent();
  8138. }
  8139.  
  8140. /**
  8141. * Collecting Rewards from the Forge of Souls
  8142. *
  8143. * Сбор награды из Горнила Душ
  8144. */
  8145. function rewardBossRatingEvent() {
  8146. let rewardBossRatingCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  8147. send(rewardBossRatingCall, function (data) {
  8148. let bossEventInfo = data.results[0].result.response.find(e => e.offerType == "bossEvent");
  8149. if (!bossEventInfo) {
  8150. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  8151. return;
  8152. }
  8153.  
  8154. let farmedChests = bossEventInfo.progress.farmedChests;
  8155. let score = bossEventInfo.progress.score;
  8156. setProgress(`${I18N('DAMAGE_AMOUNT')}: ${score}`);
  8157. let revard = bossEventInfo.reward;
  8158.  
  8159. let getRewardCall = {
  8160. calls: []
  8161. }
  8162.  
  8163. let count = 0;
  8164. for (let i = 1; i < 10; i++) {
  8165. if (farmedChests.includes(i)) {
  8166. continue;
  8167. }
  8168. if (score < revard[i].score) {
  8169. break;
  8170. }
  8171. getRewardCall.calls.push({
  8172. name: 'bossRating_getReward',
  8173. args: {
  8174. rewardId: i,
  8175. },
  8176. ident: 'body_' + i,
  8177. });
  8178. count++;
  8179. }
  8180. if (!count) {
  8181. setProgress(`${I18N('NOTHING_TO_COLLECT')}`, true);
  8182. return;
  8183. }
  8184.  
  8185. send(JSON.stringify(getRewardCall), e => {
  8186. console.log(e);
  8187. setProgress(`${I18N('COLLECTED')} ${e?.results?.length} ${I18N('REWARD')}`, true);
  8188. });
  8189. });
  8190. }
  8191.  
  8192. /**
  8193. * Collect Easter eggs and event rewards
  8194. *
  8195. * Собрать пасхалки и награды событий
  8196. */
  8197. function offerFarmAllReward() {
  8198. const offerGetAllCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  8199. return Send(offerGetAllCall).then((data) => {
  8200. const offerGetAll = data.results[0].result.response.filter(e => e.type == "reward" && !e?.freeRewardObtained && e.reward);
  8201. if (!offerGetAll.length) {
  8202. setProgress(`${I18N('NOTHING_TO_COLLECT')}`, true);
  8203. return;
  8204. }
  8205.  
  8206. const calls = [];
  8207. for (let reward of offerGetAll) {
  8208. calls.push({
  8209. name: "offerFarmReward",
  8210. args: {
  8211. offerId: reward.id
  8212. },
  8213. ident: "offerFarmReward_" + reward.id
  8214. });
  8215. }
  8216.  
  8217. return Send(JSON.stringify({ calls })).then(e => {
  8218. console.log(e);
  8219. setProgress(`${I18N('COLLECTED')} ${e?.results?.length} ${I18N('REWARD')}`, true);
  8220. });
  8221. });
  8222. }
  8223.  
  8224. /**
  8225. * Assemble Outland
  8226. *
  8227. * Собрать запределье
  8228. */
  8229. function getOutland() {
  8230. return new Promise(function (resolve, reject) {
  8231. send('{"calls":[{"name":"bossGetAll","args":{},"ident":"bossGetAll"}]}', e => {
  8232. let bosses = e.results[0].result.response;
  8233.  
  8234. let bossRaidOpenChestCall = {
  8235. calls: []
  8236. };
  8237.  
  8238. for (let boss of bosses) {
  8239. if (boss.mayRaid) {
  8240. bossRaidOpenChestCall.calls.push({
  8241. name: "bossRaid",
  8242. args: {
  8243. bossId: boss.id
  8244. },
  8245. ident: "bossRaid_" + boss.id
  8246. });
  8247. bossRaidOpenChestCall.calls.push({
  8248. name: "bossOpenChest",
  8249. args: {
  8250. bossId: boss.id,
  8251. amount: 1,
  8252. starmoney: 0
  8253. },
  8254. ident: "bossOpenChest_" + boss.id
  8255. });
  8256. } else if (boss.chestId == 1) {
  8257. bossRaidOpenChestCall.calls.push({
  8258. name: "bossOpenChest",
  8259. args: {
  8260. bossId: boss.id,
  8261. amount: 1,
  8262. starmoney: 0
  8263. },
  8264. ident: "bossOpenChest_" + boss.id
  8265. });
  8266. }
  8267. }
  8268.  
  8269. if (!bossRaidOpenChestCall.calls.length) {
  8270. setProgress(`${I18N('OUTLAND')} ${I18N('NOTHING_TO_COLLECT')}`, true);
  8271. resolve();
  8272. return;
  8273. }
  8274.  
  8275. send(JSON.stringify(bossRaidOpenChestCall), e => {
  8276. setProgress(`${I18N('OUTLAND')} ${I18N('COLLECTED')}`, true);
  8277. resolve();
  8278. });
  8279. });
  8280. });
  8281. }
  8282.  
  8283. /**
  8284. * Collect all rewards
  8285. *
  8286. * Собрать все награды
  8287. */
  8288. function questAllFarm() {
  8289. return new Promise(function (resolve, reject) {
  8290. let questGetAllCall = {
  8291. calls: [{
  8292. name: "questGetAll",
  8293. args: {},
  8294. ident: "body"
  8295. }]
  8296. }
  8297. send(JSON.stringify(questGetAllCall), function (data) {
  8298. let questGetAll = data.results[0].result.response;
  8299. const questAllFarmCall = {
  8300. calls: []
  8301. }
  8302. let number = 0;
  8303. for (let quest of questGetAll) {
  8304. if (quest.id < 1e6 && quest.state == 2) {
  8305. questAllFarmCall.calls.push({
  8306. name: "questFarm",
  8307. args: {
  8308. questId: quest.id
  8309. },
  8310. ident: `group_${number}_body`
  8311. });
  8312. number++;
  8313. }
  8314. }
  8315.  
  8316. if (!questAllFarmCall.calls.length) {
  8317. setProgress(`${I18N('COLLECTED')} ${number} ${I18N('REWARD')}`, true);
  8318. resolve();
  8319. return;
  8320. }
  8321.  
  8322. send(JSON.stringify(questAllFarmCall), function (res) {
  8323. console.log(res);
  8324. setProgress(`${I18N('COLLECTED')} ${number} ${I18N('REWARD')}`, true);
  8325. resolve();
  8326. });
  8327. });
  8328. })
  8329. }
  8330.  
  8331. /**
  8332. * Mission auto repeat
  8333. *
  8334. * Автоповтор миссии
  8335. * isStopSendMission = false;
  8336. * isSendsMission = true;
  8337. **/
  8338. this.sendsMission = async function (param) {
  8339. async function stopMission() {
  8340. isSendsMission = false;
  8341. console.log(I18N('STOPPED'));
  8342. setProgress('');
  8343. await popup.confirm(`${I18N('STOPPED')}<br>${I18N('REPETITIONS')}: ${param.count}`, [{
  8344. msg: 'Ok',
  8345. result: true
  8346. }, ])
  8347. }
  8348. if (isStopSendMission) {
  8349. stopMission();
  8350. return;
  8351. }
  8352. lastMissionBattleStart = Date.now();
  8353. let missionStartCall = {
  8354. "calls": [{
  8355. "name": "missionStart",
  8356. "args": lastMissionStart,
  8357. "ident": "body"
  8358. }]
  8359. }
  8360. /**
  8361. * Mission Request
  8362. *
  8363. * Запрос на выполнение мисии
  8364. */
  8365. SendRequest(JSON.stringify(missionStartCall), async e => {
  8366. if (e['error']) {
  8367. isSendsMission = false;
  8368. console.log(e['error']);
  8369. setProgress('');
  8370. let msg = e['error'].name + ' ' + e['error'].description + `<br>${I18N('REPETITIONS')}: ${param.count}`;
  8371. await popup.confirm(msg, [
  8372. {msg: 'Ok', result: true},
  8373. ])
  8374. return;
  8375. }
  8376. /**
  8377. * Mission data calculation
  8378. *
  8379. * Расчет данных мисии
  8380. */
  8381. BattleCalc(e.results[0].result.response, 'get_tower', async r => {
  8382. /** missionTimer */
  8383. let timer = getTimer(r.battleTime) + 5;
  8384. const period = Math.ceil((Date.now() - lastMissionBattleStart) / 1000);
  8385. if (period < timer) {
  8386. timer = timer - period;
  8387. const isSuccess = await countdownTimer(timer, `${I18N('MISSIONS_PASSED')}: ${param.count}`, () => {
  8388. isStopSendMission = true;
  8389. });
  8390. if (!isSuccess) {
  8391. stopMission();
  8392. return;
  8393. }
  8394. }
  8395.  
  8396. let missionEndCall = {
  8397. "calls": [{
  8398. "name": "missionEnd",
  8399. "args": {
  8400. "id": param.id,
  8401. "result": r.result,
  8402. "progress": r.progress
  8403. },
  8404. "ident": "body"
  8405. }]
  8406. }
  8407. /**
  8408. * Mission Completion Request
  8409. *
  8410. * Запрос на завершение миссии
  8411. */
  8412. SendRequest(JSON.stringify(missionEndCall), async (e) => {
  8413. if (e['error']) {
  8414. isSendsMission = false;
  8415. console.log(e['error']);
  8416. setProgress('');
  8417. let msg = e['error'].name + ' ' + e['error'].description + `<br>${I18N('REPETITIONS')}: ${param.count}`;
  8418. await popup.confirm(msg, [
  8419. {msg: 'Ok', result: true},
  8420. ])
  8421. return;
  8422. }
  8423. r = e.results[0].result.response;
  8424. if (r['error']) {
  8425. isSendsMission = false;
  8426. console.log(r['error']);
  8427. setProgress('');
  8428. await popup.confirm(`<br>${I18N('REPETITIONS')}: ${param.count}` + ' 3 ' + r['error'], [
  8429. {msg: 'Ok', result: true},
  8430. ])
  8431. return;
  8432. }
  8433.  
  8434. param.count++;
  8435. setProgress(`${I18N('MISSIONS_PASSED')}: ${param.count} (${I18N('STOP')})`, false, () => {
  8436. isStopSendMission = true;
  8437. });
  8438. setTimeout(sendsMission, 1, param);
  8439. });
  8440. })
  8441. });
  8442. }
  8443.  
  8444. /**
  8445. * Opening of russian dolls
  8446. *
  8447. * Открытие матрешек
  8448. */
  8449. async function openRussianDolls(libId, amount) {
  8450. let sum = 0;
  8451. const sumResult = {};
  8452. let count = 0;
  8453.  
  8454. while (amount) {
  8455. sum += amount;
  8456. setProgress(`${I18N('TOTAL_OPEN')} ${sum}`);
  8457. const calls = [
  8458. {
  8459. name: 'consumableUseLootBox',
  8460. args: { libId, amount },
  8461. ident: 'body',
  8462. },
  8463. ];
  8464. const response = await Send(JSON.stringify({ calls })).then((e) => e.results[0].result.response);
  8465. let [countLootBox, result] = Object.entries(response).pop();
  8466. count += +countLootBox;
  8467. let newCount = 0;
  8468.  
  8469. if (result?.consumable && result.consumable[libId]) {
  8470. newCount = result.consumable[libId];
  8471. delete result.consumable[libId];
  8472. }
  8473.  
  8474. mergeItemsObj(sumResult, result);
  8475. amount = newCount;
  8476. }
  8477.  
  8478. setProgress(`${I18N('TOTAL_OPEN')} ${sum}`, 5000);
  8479. return [count, sumResult];
  8480. }
  8481.  
  8482. function mergeItemsObj(obj1, obj2) {
  8483. for (const key in obj2) {
  8484. if (obj1[key]) {
  8485. if (typeof obj1[key] == 'object') {
  8486. for (const innerKey in obj2[key]) {
  8487. obj1[key][innerKey] = (obj1[key][innerKey] || 0) + obj2[key][innerKey];
  8488. }
  8489. } else {
  8490. obj1[key] += obj2[key] || 0;
  8491. }
  8492. } else {
  8493. obj1[key] = obj2[key];
  8494. }
  8495. }
  8496.  
  8497. return obj1;
  8498. }
  8499.  
  8500. /**
  8501. * Collect all mail, except letters with energy and charges of the portal
  8502. *
  8503. * Собрать всю почту, кроме писем с энергией и зарядами портала
  8504. */
  8505. function mailGetAll() {
  8506. const getMailInfo = '{"calls":[{"name":"mailGetAll","args":{},"ident":"body"}]}';
  8507.  
  8508. return Send(getMailInfo).then(dataMail => {
  8509. const letters = dataMail.results[0].result.response.letters;
  8510. const letterIds = lettersFilter(letters);
  8511. if (!letterIds.length) {
  8512. setProgress(I18N('NOTHING_TO_COLLECT'), true);
  8513. return;
  8514. }
  8515.  
  8516. const calls = [
  8517. { name: "mailFarm", args: { letterIds }, ident: "body" }
  8518. ];
  8519.  
  8520. return Send(JSON.stringify({ calls })).then(res => {
  8521. const lettersIds = res.results[0].result.response;
  8522. if (lettersIds) {
  8523. const countLetters = Object.keys(lettersIds).length;
  8524. setProgress(`${I18N('RECEIVED')} ${countLetters} ${I18N('LETTERS')}`, true);
  8525. }
  8526. });
  8527. });
  8528. }
  8529.  
  8530. /**
  8531. * Filters received emails
  8532. *
  8533. * Фильтрует получаемые письма
  8534. */
  8535. function lettersFilter(letters) {
  8536. const lettersIds = [];
  8537. for (let l in letters) {
  8538. letter = letters[l];
  8539. const reward = letter?.reward;
  8540. if (!reward || !Object.keys(reward).length) {
  8541. continue;
  8542. }
  8543. /**
  8544. * Mail Collection Exceptions
  8545. *
  8546. * Исключения на сбор писем
  8547. */
  8548. const isFarmLetter = !(
  8549. /** Portals // сферы портала */
  8550. (reward?.refillable ? reward.refillable[45] : false) ||
  8551. /** Energy // энергия */
  8552. (reward?.stamina ? reward.stamina : false) ||
  8553. /** accelerating energy gain // ускорение набора энергии */
  8554. (reward?.buff ? true : false) ||
  8555. /** VIP Points // вип очки */
  8556. (reward?.vipPoints ? reward.vipPoints : false) ||
  8557. /** souls of heroes // душы героев */
  8558. (reward?.fragmentHero ? true : false) ||
  8559. /** heroes // герои */
  8560. (reward?.bundleHeroReward ? true : false)
  8561. );
  8562. if (isFarmLetter) {
  8563. lettersIds.push(~~letter.id);
  8564. continue;
  8565. }
  8566. /**
  8567. * Если до окончания годности письма менее 24 часов,
  8568. * то оно собирается не смотря на исключения
  8569. */
  8570. const availableUntil = +letter?.availableUntil;
  8571. if (availableUntil) {
  8572. const maxTimeLeft = 24 * 60 * 60 * 1000;
  8573. const timeLeft = (new Date(availableUntil * 1000) - new Date())
  8574. console.log('Time left:', timeLeft)
  8575. if (timeLeft < maxTimeLeft) {
  8576. lettersIds.push(~~letter.id);
  8577. continue;
  8578. }
  8579. }
  8580. }
  8581. return lettersIds;
  8582. }
  8583.  
  8584. function setPortals(value = 0, isChange = false) {
  8585. const { buttons } = HWHData;
  8586. const sanctuaryButton = buttons['testAdventure'].button;
  8587. const sanctuaryDot = sanctuaryButton.querySelector('.scriptMenu_dot');
  8588. if (isChange) {
  8589. value = Math.max(+sanctuaryDot.innerText + value, 0);
  8590. }
  8591. if (value) {
  8592. sanctuaryButton.classList.add('scriptMenu_attention');
  8593. sanctuaryDot.title = `${value} ${I18N('PORTALS')}`;
  8594. sanctuaryDot.innerText = value;
  8595. sanctuaryDot.style.backgroundColor = 'red';
  8596. } else {
  8597. sanctuaryButton.classList.remove('scriptMenu_attention');
  8598. sanctuaryDot.innerText = 0;
  8599. }
  8600. }
  8601.  
  8602. function setWarTries(value = 0, isChange = false, arePointsMax = false) {
  8603. const { buttons } = HWHData;
  8604. const clanWarButton = buttons['goToClanWar'].button;
  8605. const clanWarDot = clanWarButton.querySelector('.scriptMenu_dot');
  8606. if (isChange) {
  8607. value = Math.max(+clanWarDot.innerText + value, 0);
  8608. }
  8609. if (value && !arePointsMax) {
  8610. clanWarButton.classList.add('scriptMenu_attention');
  8611. clanWarDot.title = `${value} ${I18N('ATTEMPTS')}`;
  8612. clanWarDot.innerText = value;
  8613. clanWarDot.style.backgroundColor = 'red';
  8614. } else {
  8615. clanWarButton.classList.remove('scriptMenu_attention');
  8616. clanWarDot.innerText = 0;
  8617. }
  8618. }
  8619.  
  8620. /**
  8621. * Displaying information about the areas of the portal and attempts on the VG
  8622. *
  8623. * Отображение информации о сферах портала и попытках на ВГ
  8624. */
  8625. async function justInfo() {
  8626. return new Promise(async (resolve, reject) => {
  8627. const calls = [
  8628. {
  8629. name: 'userGetInfo',
  8630. args: {},
  8631. ident: 'userGetInfo',
  8632. },
  8633. {
  8634. name: 'clanWarGetInfo',
  8635. args: {},
  8636. ident: 'clanWarGetInfo',
  8637. },
  8638. {
  8639. name: 'titanArenaGetStatus',
  8640. args: {},
  8641. ident: 'titanArenaGetStatus',
  8642. },
  8643. {
  8644. name: 'quest_completeEasterEggQuest',
  8645. args: {},
  8646. ident: 'quest_completeEasterEggQuest',
  8647. },
  8648. ];
  8649. const result = await Send(JSON.stringify({ calls }));
  8650. const infos = result.results;
  8651. const portalSphere = infos[0].result.response.refillable.find(n => n.id == 45);
  8652. const clanWarMyTries = infos[1].result.response?.myTries ?? 0;
  8653. const arePointsMax = infos[1].result.response?.arePointsMax;
  8654. const titansLevel = +(infos[2].result.response?.tier ?? 0);
  8655. const titansStatus = infos[2].result.response?.status; //peace_time || battle
  8656.  
  8657. setPortals(portalSphere.amount);
  8658. setWarTries(clanWarMyTries, false, arePointsMax);
  8659.  
  8660. const { buttons } = HWHData;
  8661. const titansArenaButton = buttons['testTitanArena'].button;
  8662. const titansArenaDot = titansArenaButton.querySelector('.scriptMenu_dot');
  8663.  
  8664. if (titansLevel < 7 && titansStatus == 'battle') { ;
  8665. titansArenaButton.classList.add('scriptMenu_attention');
  8666. titansArenaDot.title = `${titansLevel} ${I18N('LEVEL')}`;
  8667. titansArenaDot.innerText = titansLevel;
  8668. titansArenaDot.style.backgroundColor = 'red';
  8669. } else {
  8670. titansArenaButton.classList.remove('scriptMenu_attention');
  8671. }
  8672.  
  8673. const imgPortal =
  8674. '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';
  8675.  
  8676. setProgress('<img src="' + imgPortal + '" style="height: 25px;position: relative;top: 5px;"> ' + `${portalSphere.amount} </br> ${I18N('GUILD_WAR')}: ${clanWarMyTries}`, true);
  8677. resolve();
  8678. });
  8679. }
  8680.  
  8681. async function getDailyBonus() {
  8682. const dailyBonusInfo = await Send(JSON.stringify({
  8683. calls: [{
  8684. name: "dailyBonusGetInfo",
  8685. args: {},
  8686. ident: "body"
  8687. }]
  8688. })).then(e => e.results[0].result.response);
  8689. const { availableToday, availableVip, currentDay } = dailyBonusInfo;
  8690.  
  8691. if (!availableToday) {
  8692. console.log('Уже собрано');
  8693. return;
  8694. }
  8695.  
  8696. const currentVipPoints = +userInfo.vipPoints;
  8697. const dailyBonusStat = lib.getData('dailyBonusStatic');
  8698. const vipInfo = lib.getData('level').vip;
  8699. let currentVipLevel = 0;
  8700. for (let i in vipInfo) {
  8701. vipLvl = vipInfo[i];
  8702. if (currentVipPoints >= vipLvl.vipPoints) {
  8703. currentVipLevel = vipLvl.level;
  8704. }
  8705. }
  8706. const vipLevelDouble = dailyBonusStat[`${currentDay}_0_0`].vipLevelDouble;
  8707.  
  8708. const calls = [{
  8709. name: "dailyBonusFarm",
  8710. args: {
  8711. vip: availableVip && currentVipLevel >= vipLevelDouble ? 1 : 0
  8712. },
  8713. ident: "body"
  8714. }];
  8715.  
  8716. const result = await Send(JSON.stringify({ calls }));
  8717. if (result.error) {
  8718. console.error(result.error);
  8719. return;
  8720. }
  8721.  
  8722. const reward = result.results[0].result.response;
  8723. const type = Object.keys(reward).pop();
  8724. const itemId = Object.keys(reward[type]).pop();
  8725. const count = reward[type][itemId];
  8726. const itemName = cheats.translate(`LIB_${type.toUpperCase()}_NAME_${itemId}`);
  8727.  
  8728. console.log(`Ежедневная награда: Получено ${count} ${itemName}`, reward);
  8729. }
  8730.  
  8731. async function farmStamina(lootBoxId = 148) {
  8732. const lootBox = await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"}]}')
  8733. .then(e => e.results[0].result.response.consumable[148]);
  8734.  
  8735. /** Добавить другие ящики */
  8736. /**
  8737. * 144 - медная шкатулка
  8738. * 145 - бронзовая шкатулка
  8739. * 148 - платиновая шкатулка
  8740. */
  8741. if (!lootBox) {
  8742. setProgress(I18N('NO_BOXES'), true);
  8743. return;
  8744. }
  8745.  
  8746. let maxFarmEnergy = getSaveVal('maxFarmEnergy', 100);
  8747. const result = await popup.confirm(I18N('OPEN_LOOTBOX', { lootBox }), [
  8748. { result: false, isClose: true },
  8749. { msg: I18N('BTN_YES'), result: true },
  8750. { msg: I18N('STAMINA'), isInput: true, default: maxFarmEnergy },
  8751. ]);
  8752. if (!+result) {
  8753. return;
  8754. }
  8755.  
  8756. if ((typeof result) !== 'boolean' && Number.parseInt(result)) {
  8757. maxFarmEnergy = +result;
  8758. setSaveVal('maxFarmEnergy', maxFarmEnergy);
  8759. } else {
  8760. maxFarmEnergy = 0;
  8761. }
  8762.  
  8763. let collectEnergy = 0;
  8764. for (let count = lootBox; count > 0; count--) {
  8765. const response = await Send('{"calls":[{"name":"consumableUseLootBox","args":{"libId":148,"amount":1},"ident":"body"}]}').then(
  8766. (e) => e.results[0].result.response
  8767. );
  8768. const result = Object.values(response).pop();
  8769. if ('stamina' in result) {
  8770. setProgress(`${I18N('OPEN')}: ${lootBox - count}/${lootBox} ${I18N('STAMINA')} +${result.stamina}<br>${I18N('STAMINA')}: ${collectEnergy}`, false);
  8771. console.log(`${ I18N('STAMINA') } + ${ result.stamina }`);
  8772. if (!maxFarmEnergy) {
  8773. return;
  8774. }
  8775. collectEnergy += +result.stamina;
  8776. if (collectEnergy >= maxFarmEnergy) {
  8777. console.log(`${I18N('STAMINA')} + ${ collectEnergy }`);
  8778. setProgress(`${I18N('STAMINA')} + ${ collectEnergy }`, false);
  8779. return;
  8780. }
  8781. } else {
  8782. setProgress(`${I18N('OPEN')}: ${lootBox - count}/${lootBox}<br>${I18N('STAMINA')}: ${collectEnergy}`, false);
  8783. console.log(result);
  8784. }
  8785. }
  8786.  
  8787. setProgress(I18N('BOXES_OVER'), true);
  8788. }
  8789.  
  8790. async function fillActive() {
  8791. const data = await Send(JSON.stringify({
  8792. calls: [{
  8793. name: "questGetAll",
  8794. args: {},
  8795. ident: "questGetAll"
  8796. }, {
  8797. name: "inventoryGet",
  8798. args: {},
  8799. ident: "inventoryGet"
  8800. }, {
  8801. name: "clanGetInfo",
  8802. args: {},
  8803. ident: "clanGetInfo"
  8804. }
  8805. ]
  8806. })).then(e => e.results.map(n => n.result.response));
  8807.  
  8808. const quests = data[0];
  8809. const inv = data[1];
  8810. const stat = data[2].stat;
  8811. const maxActive = 2000 - stat.todayItemsActivity;
  8812. if (maxActive <= 0) {
  8813. setProgress(I18N('NO_MORE_ACTIVITY'), true);
  8814. return;
  8815. }
  8816. let countGetActive = 0;
  8817. const quest = quests.find(e => e.id > 10046 && e.id < 10051);
  8818. if (quest) {
  8819. countGetActive = 1750 - quest.progress;
  8820. }
  8821. if (countGetActive <= 0) {
  8822. countGetActive = maxActive;
  8823. }
  8824. console.log(countGetActive);
  8825.  
  8826. countGetActive = +(await popup.confirm(I18N('EXCHANGE_ITEMS', { maxActive }), [
  8827. { result: false, isClose: true },
  8828. { msg: I18N('GET_ACTIVITY'), isInput: true, default: countGetActive.toString() },
  8829. ]));
  8830.  
  8831. if (!countGetActive) {
  8832. return;
  8833. }
  8834.  
  8835. if (countGetActive > maxActive) {
  8836. countGetActive = maxActive;
  8837. }
  8838.  
  8839. const items = lib.getData('inventoryItem');
  8840.  
  8841. let itemsInfo = [];
  8842. for (let type of ['gear', 'scroll']) {
  8843. for (let i in inv[type]) {
  8844. const v = items[type][i]?.enchantValue || 0;
  8845. itemsInfo.push({
  8846. id: i,
  8847. count: inv[type][i],
  8848. v,
  8849. type
  8850. })
  8851. }
  8852. const invType = 'fragment' + type.toLowerCase().charAt(0).toUpperCase() + type.slice(1);
  8853. for (let i in inv[invType]) {
  8854. const v = items[type][i]?.fragmentEnchantValue || 0;
  8855. itemsInfo.push({
  8856. id: i,
  8857. count: inv[invType][i],
  8858. v,
  8859. type: invType
  8860. })
  8861. }
  8862. }
  8863. itemsInfo = itemsInfo.filter(e => e.v < 4 && e.count > 200);
  8864. itemsInfo = itemsInfo.sort((a, b) => b.count - a.count);
  8865. console.log(itemsInfo);
  8866. const activeItem = itemsInfo.shift();
  8867. console.log(activeItem);
  8868. const countItem = Math.ceil(countGetActive / activeItem.v);
  8869. if (countItem > activeItem.count) {
  8870. setProgress(I18N('NOT_ENOUGH_ITEMS'), true);
  8871. console.log(activeItem);
  8872. return;
  8873. }
  8874.  
  8875. await Send(JSON.stringify({
  8876. calls: [{
  8877. name: "clanItemsForActivity",
  8878. args: {
  8879. items: {
  8880. [activeItem.type]: {
  8881. [activeItem.id]: countItem
  8882. }
  8883. }
  8884. },
  8885. ident: "body"
  8886. }]
  8887. })).then(e => {
  8888. /** TODO: Вывести потраченые предметы */
  8889. console.log(e);
  8890. setProgress(`${I18N('ACTIVITY_RECEIVED')}: ` + e.results[0].result.response, true);
  8891. });
  8892. }
  8893.  
  8894. async function buyHeroFragments() {
  8895. const result = await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"},{"name":"shopGetAll","args":{},"ident":"shopGetAll"}]}')
  8896. .then(e => e.results.map(n => n.result.response));
  8897. const inv = result[0];
  8898. const shops = Object.values(result[1]).filter(shop => [4, 5, 6, 8, 9, 10, 17].includes(shop.id));
  8899. const calls = [];
  8900.  
  8901. for (let shop of shops) {
  8902. const slots = Object.values(shop.slots);
  8903. for (const slot of slots) {
  8904. /* Уже куплено */
  8905. if (slot.bought) {
  8906. continue;
  8907. }
  8908. /* Не душа героя */
  8909. if (!('fragmentHero' in slot.reward)) {
  8910. continue;
  8911. }
  8912. const coin = Object.keys(slot.cost).pop();
  8913. const coinId = Object.keys(slot.cost[coin]).pop();
  8914. const stock = inv[coin][coinId] || 0;
  8915. /* Не хватает на покупку */
  8916. if (slot.cost[coin][coinId] > stock) {
  8917. continue;
  8918. }
  8919. inv[coin][coinId] -= slot.cost[coin][coinId];
  8920. calls.push({
  8921. name: "shopBuy",
  8922. args: {
  8923. shopId: shop.id,
  8924. slot: slot.id,
  8925. cost: slot.cost,
  8926. reward: slot.reward,
  8927. },
  8928. ident: `shopBuy_${shop.id}_${slot.id}`,
  8929. })
  8930. }
  8931. }
  8932.  
  8933. if (!calls.length) {
  8934. setProgress(I18N('NO_PURCHASABLE_HERO_SOULS'), true);
  8935. return;
  8936. }
  8937.  
  8938. const bought = await Send(JSON.stringify({ calls })).then(e => e.results.map(n => n.result.response));
  8939. if (!bought) {
  8940. console.log('что-то пошло не так')
  8941. return;
  8942. }
  8943.  
  8944. let countHeroSouls = 0;
  8945. for (const buy of bought) {
  8946. countHeroSouls += +Object.values(Object.values(buy).pop()).pop();
  8947. }
  8948. console.log(countHeroSouls, bought, calls);
  8949. setProgress(I18N('PURCHASED_HERO_SOULS', { countHeroSouls }), true);
  8950. }
  8951.  
  8952. /** Открыть платные сундуки в Запределье за 90 */
  8953. async function bossOpenChestPay() {
  8954. const callsNames = ['userGetInfo', 'bossGetAll', 'specialOffer_getAll', 'getTime'];
  8955. const info = await Send({ calls: callsNames.map((name) => ({ name, args: {}, ident: name })) }).then((e) =>
  8956. e.results.map((n) => n.result.response)
  8957. );
  8958.  
  8959. const user = info[0];
  8960. const boses = info[1];
  8961. const offers = info[2];
  8962. const time = info[3];
  8963.  
  8964. const discountOffer = offers.find((e) => e.offerType == 'costReplaceOutlandChest');
  8965.  
  8966. let discount = 1;
  8967. if (discountOffer && discountOffer.endTime > time) {
  8968. discount = 1 - discountOffer.offerData.outlandChest.discountPercent / 100;
  8969. }
  8970.  
  8971. cost9chests = 540 * discount;
  8972. cost18chests = 1740 * discount;
  8973. costFirstChest = 90 * discount;
  8974. costSecondChest = 200 * discount;
  8975.  
  8976. const currentStarMoney = user.starMoney;
  8977. if (currentStarMoney < cost9chests) {
  8978. setProgress('Недостаточно изюма, нужно ' + cost9chests + ' у Вас ' + currentStarMoney, true);
  8979. return;
  8980. }
  8981.  
  8982. const imgEmerald =
  8983. "<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='>";
  8984.  
  8985. if (currentStarMoney < cost9chests) {
  8986. setProgress(I18N('NOT_ENOUGH_EMERALDS_540', { currentStarMoney, imgEmerald }), true);
  8987. return;
  8988. }
  8989.  
  8990. const buttons = [{ result: false, isClose: true }];
  8991.  
  8992. if (currentStarMoney >= cost9chests) {
  8993. buttons.push({
  8994. msg: I18N('BUY_OUTLAND_BTN', { count: 9, countEmerald: cost9chests, imgEmerald }),
  8995. result: [costFirstChest, costFirstChest, 0],
  8996. });
  8997. }
  8998.  
  8999. if (currentStarMoney >= cost18chests) {
  9000. buttons.push({
  9001. msg: I18N('BUY_OUTLAND_BTN', { count: 18, countEmerald: cost18chests, imgEmerald }),
  9002. result: [costFirstChest, costFirstChest, 0, costSecondChest, costSecondChest, 0],
  9003. });
  9004. }
  9005.  
  9006. const answer = await popup.confirm(`<div style="margin-bottom: 15px;">${I18N('BUY_OUTLAND')}</div>`, buttons);
  9007.  
  9008. if (!answer) {
  9009. return;
  9010. }
  9011.  
  9012. const callBoss = [];
  9013. let n = 0;
  9014. for (let boss of boses) {
  9015. const bossId = boss.id;
  9016. if (boss.chestNum != 2) {
  9017. continue;
  9018. }
  9019. const calls = [];
  9020. for (const starmoney of answer) {
  9021. calls.push({
  9022. name: 'bossOpenChest',
  9023. args: {
  9024. amount: 1,
  9025. bossId,
  9026. starmoney,
  9027. },
  9028. ident: 'bossOpenChest_' + ++n,
  9029. });
  9030. }
  9031. callBoss.push(calls);
  9032. }
  9033.  
  9034. if (!callBoss.length) {
  9035. setProgress(I18N('CHESTS_NOT_AVAILABLE'), true);
  9036. return;
  9037. }
  9038.  
  9039. let count = 0;
  9040. let errors = 0;
  9041. for (const calls of callBoss) {
  9042. const result = await Send({ calls });
  9043. console.log(result);
  9044. if (result?.results) {
  9045. count += result.results.length;
  9046. } else {
  9047. errors++;
  9048. }
  9049. }
  9050.  
  9051. setProgress(`${I18N('OUTLAND_CHESTS_RECEIVED')}: ${count}`, true);
  9052. }
  9053.  
  9054. async function autoRaidAdventure() {
  9055. const calls = [
  9056. {
  9057. name: "userGetInfo",
  9058. args: {},
  9059. ident: "userGetInfo"
  9060. },
  9061. {
  9062. name: "adventure_raidGetInfo",
  9063. args: {},
  9064. ident: "adventure_raidGetInfo"
  9065. }
  9066. ];
  9067. const result = await Send(JSON.stringify({ calls }))
  9068. .then(e => e.results.map(n => n.result.response));
  9069.  
  9070. const portalSphere = result[0].refillable.find(n => n.id == 45);
  9071. const adventureRaid = Object.entries(result[1].raid).filter(e => e[1]).pop()
  9072. const adventureId = adventureRaid ? adventureRaid[0] : 0;
  9073.  
  9074. if (!portalSphere.amount || !adventureId) {
  9075. setProgress(I18N('RAID_NOT_AVAILABLE'), true);
  9076. return;
  9077. }
  9078.  
  9079. const countRaid = +(await popup.confirm(I18N('RAID_ADVENTURE', { adventureId }), [
  9080. { result: false, isClose: true },
  9081. { msg: I18N('RAID'), isInput: true, default: portalSphere.amount },
  9082. ]));
  9083.  
  9084. if (!countRaid) {
  9085. return;
  9086. }
  9087.  
  9088. if (countRaid > portalSphere.amount) {
  9089. countRaid = portalSphere.amount;
  9090. }
  9091.  
  9092. const resultRaid = await Send(JSON.stringify({
  9093. calls: [...Array(countRaid)].map((e, i) => ({
  9094. name: "adventure_raid",
  9095. args: {
  9096. adventureId
  9097. },
  9098. ident: `body_${i}`
  9099. }))
  9100. })).then(e => e.results.map(n => n.result.response));
  9101.  
  9102. if (!resultRaid.length) {
  9103. console.log(resultRaid);
  9104. setProgress(I18N('SOMETHING_WENT_WRONG'), true);
  9105. return;
  9106. }
  9107.  
  9108. console.log(resultRaid, adventureId, portalSphere.amount);
  9109. setProgress(I18N('ADVENTURE_COMPLETED', { adventureId, times: resultRaid.length }), true);
  9110. }
  9111.  
  9112. /** Вывести всю клановую статистику в консоль браузера */
  9113. async function clanStatistic() {
  9114. const copy = function (text) {
  9115. const copyTextarea = document.createElement("textarea");
  9116. copyTextarea.style.opacity = "0";
  9117. copyTextarea.textContent = text;
  9118. document.body.appendChild(copyTextarea);
  9119. copyTextarea.select();
  9120. document.execCommand("copy");
  9121. document.body.removeChild(copyTextarea);
  9122. delete copyTextarea;
  9123. }
  9124. const calls = [
  9125. { name: "clanGetInfo", args: {}, ident: "clanGetInfo" },
  9126. { name: "clanGetWeeklyStat", args: {}, ident: "clanGetWeeklyStat" },
  9127. { name: "clanGetLog", args: {}, ident: "clanGetLog" },
  9128. ];
  9129.  
  9130. const result = await Send(JSON.stringify({ calls }));
  9131.  
  9132. const dataClanInfo = result.results[0].result.response;
  9133. const dataClanStat = result.results[1].result.response;
  9134. const dataClanLog = result.results[2].result.response;
  9135.  
  9136. const membersStat = {};
  9137. for (let i = 0; i < dataClanStat.stat.length; i++) {
  9138. membersStat[dataClanStat.stat[i].id] = dataClanStat.stat[i];
  9139. }
  9140.  
  9141. const joinStat = {};
  9142. historyLog = dataClanLog.history;
  9143. for (let j in historyLog) {
  9144. his = historyLog[j];
  9145. if (his.event == 'join') {
  9146. joinStat[his.userId] = his.ctime;
  9147. }
  9148. }
  9149.  
  9150. const infoArr = [];
  9151. const members = dataClanInfo.clan.members;
  9152. for (let n in members) {
  9153. var member = [
  9154. n,
  9155. members[n].name,
  9156. members[n].level,
  9157. dataClanInfo.clan.warriors.includes(+n) ? 1 : 0,
  9158. (new Date(members[n].lastLoginTime * 1000)).toLocaleString().replace(',', ''),
  9159. joinStat[n] ? (new Date(joinStat[n] * 1000)).toLocaleString().replace(',', '') : '',
  9160. membersStat[n].activity.reverse().join('\t'),
  9161. membersStat[n].adventureStat.reverse().join('\t'),
  9162. membersStat[n].clanGifts.reverse().join('\t'),
  9163. membersStat[n].clanWarStat.reverse().join('\t'),
  9164. membersStat[n].dungeonActivity.reverse().join('\t'),
  9165. ];
  9166. infoArr.push(member);
  9167. }
  9168. const info = infoArr.sort((a, b) => (b[2] - a[2])).map((e) => e.join('\t')).join('\n');
  9169. console.log(info);
  9170. copy(info);
  9171. setProgress(I18N('CLAN_STAT_COPY'), true);
  9172. }
  9173.  
  9174. async function buyInStoreForGold() {
  9175. const result = await Send('{"calls":[{"name":"shopGetAll","args":{},"ident":"body"},{"name":"userGetInfo","args":{},"ident":"userGetInfo"}]}').then(e => e.results.map(n => n.result.response));
  9176. const shops = result[0];
  9177. const user = result[1];
  9178. let gold = user.gold;
  9179. const calls = [];
  9180. if (shops[17]) {
  9181. const slots = shops[17].slots;
  9182. for (let i = 1; i <= 2; i++) {
  9183. if (!slots[i].bought) {
  9184. const costGold = slots[i].cost.gold;
  9185. if ((gold - costGold) < 0) {
  9186. continue;
  9187. }
  9188. gold -= costGold;
  9189. calls.push({
  9190. name: "shopBuy",
  9191. args: {
  9192. shopId: 17,
  9193. slot: i,
  9194. cost: slots[i].cost,
  9195. reward: slots[i].reward,
  9196. },
  9197. ident: 'body_' + i,
  9198. })
  9199. }
  9200. }
  9201. }
  9202. const slots = shops[1].slots;
  9203. for (let i = 4; i <= 6; i++) {
  9204. if (!slots[i].bought && slots[i]?.cost?.gold) {
  9205. const costGold = slots[i].cost.gold;
  9206. if ((gold - costGold) < 0) {
  9207. continue;
  9208. }
  9209. gold -= costGold;
  9210. calls.push({
  9211. name: "shopBuy",
  9212. args: {
  9213. shopId: 1,
  9214. slot: i,
  9215. cost: slots[i].cost,
  9216. reward: slots[i].reward,
  9217. },
  9218. ident: 'body_' + i,
  9219. })
  9220. }
  9221. }
  9222.  
  9223. if (!calls.length) {
  9224. setProgress(I18N('NOTHING_BUY'), true);
  9225. return;
  9226. }
  9227.  
  9228. const resultBuy = await Send(JSON.stringify({ calls })).then(e => e.results.map(n => n.result.response));
  9229. console.log(resultBuy);
  9230. const countBuy = resultBuy.length;
  9231. setProgress(I18N('LOTS_BOUGHT', { countBuy }), true);
  9232. }
  9233.  
  9234. async function rewardsAndMailFarm() {
  9235. try {
  9236. const [questGetAll, mailGetAll, specialOffer] = await Caller.send(['questGetAll', 'mailGetAll', 'specialOffer_getAll']);
  9237. const questsFarm = questGetAll.filter((e) => e.state == 2);
  9238. const mailFarm = mailGetAll?.letters || [];
  9239. const stagesOffers = specialOffer.filter(e => e.offerType === "stagesOffer");
  9240.  
  9241. const questBattlePass = lib.getData('quest').battlePass;
  9242. const { questChain: questChainBPass, list: listBattlePass } = lib.getData('battlePass');
  9243. const currentTime = Date.now();
  9244.  
  9245. const farmCaller = new Caller();
  9246.  
  9247. for(const offer of stagesOffers) {
  9248. const offerId = offer.id;
  9249. const stage = 1 - offer.farmedStage;
  9250. for(let i = 0; i < stage; i++) {
  9251. farmCaller.add({
  9252. name: 'specialOffer_farmReward',
  9253. args: { offerId },
  9254. });
  9255. }
  9256. }
  9257.  
  9258. const farmQuestIds = [];
  9259. const questIds = [];
  9260. for (let quest of questsFarm) {
  9261. const questId = +quest.id;
  9262.  
  9263. /*
  9264. if ([20010001, 20010002, 20010004].includes(questId)) {
  9265. farmCaller.add({
  9266. name: 'questFarm',
  9267. args: { questId },
  9268. });
  9269. farmQuestIds.push(questId);
  9270. continue;
  9271. }
  9272. */
  9273.  
  9274. if (questId >= 2001e4) {
  9275. continue;
  9276. }
  9277.  
  9278. if (questId > 1e6 && questId < 2e7) {
  9279. const questInfo = questBattlePass[questId];
  9280. const chain = questChainBPass[questInfo.chain];
  9281. if (chain.requirement?.battlePassTicket) {
  9282. continue;
  9283. }
  9284. const battlePass = listBattlePass[chain.battlePass];
  9285. const startTime = battlePass.startCondition.time.value * 1e3;
  9286. const endTime = startTime + battlePass.duration * 1e3;
  9287. if (startTime > currentTime || endTime < currentTime) {
  9288. continue;
  9289. }
  9290. }
  9291.  
  9292. if (questId >= 2e7) {
  9293. questIds.push(questId);
  9294. farmQuestIds.push(questId);
  9295. continue;
  9296. }
  9297.  
  9298. farmCaller.add({
  9299. name: 'questFarm',
  9300. args: { questId },
  9301. });
  9302. farmQuestIds.push(questId);
  9303. }
  9304.  
  9305. if (questIds.length) {
  9306. farmCaller.add({
  9307. name: 'quest_questsFarm',
  9308. args: { questIds },
  9309. });
  9310. }
  9311.  
  9312. const letterIds = lettersFilter(mailFarm);
  9313. if (letterIds.length) {
  9314. farmCaller.add({
  9315. name: 'mailFarm',
  9316. args: { letterIds },
  9317. });
  9318. }
  9319.  
  9320. if (farmCaller.isEmpty()) {
  9321. setProgress(I18N('NOTHING_TO_COLLECT'), true);
  9322. return;
  9323. }
  9324.  
  9325. const farmResults = await farmCaller.send();
  9326.  
  9327. let countQuests = 0;
  9328. let countMail = 0;
  9329. let questsIds = [];
  9330.  
  9331. const questFarm = farmResults.result('questFarm', true);
  9332. countQuests += questFarm.length;
  9333. countQuests += questIds.length;
  9334. countMail += Object.keys(farmResults.result('mailFarm')).length;
  9335.  
  9336. const sideResult = farmResults.sideResult('questFarm', true);
  9337. sideResult.push(...farmResults.sideResult('quest_questsFarm', true));
  9338.  
  9339. for (let side of sideResult) {
  9340. const quests = [...(side.newQuests ?? []), ...(side.quests ?? [])];
  9341. for (let quest of quests) {
  9342. if ((quest.id < 1e6 || (quest.id >= 2e7 && quest.id < 2001e4)) && quest.state == 2) {
  9343. questsIds.push(quest.id);
  9344. }
  9345. }
  9346. }
  9347. questsIds = [...new Set(questsIds)];
  9348.  
  9349. while (questsIds.length) {
  9350. const recursiveCaller = new Caller();
  9351. const newQuestIds = [];
  9352.  
  9353. for (let questId of questsIds) {
  9354. if (farmQuestIds.includes(questId)) {
  9355. continue;
  9356. }
  9357. if (questId < 1e6) {
  9358. recursiveCaller.add({
  9359. name: 'questFarm',
  9360. args: { questId },
  9361. });
  9362. farmQuestIds.push(questId);
  9363. countQuests++;
  9364. } else if (questId >= 2e7 && questId < 2001e4) {
  9365. farmQuestIds.push(questId);
  9366. newQuestIds.push(questId);
  9367. countQuests++;
  9368. }
  9369. }
  9370.  
  9371. if (newQuestIds.length) {
  9372. recursiveCaller.add({
  9373. name: 'quest_questsFarm',
  9374. args: { questIds: newQuestIds },
  9375. });
  9376. }
  9377.  
  9378. questsIds = [];
  9379. if (recursiveCaller.isEmpty()) {
  9380. break;
  9381. }
  9382.  
  9383. await recursiveCaller.send();
  9384. const sideResult = recursiveCaller.sideResult('questFarm', true);
  9385. sideResult.push(...recursiveCaller.sideResult('quest_questsFarm', true));
  9386.  
  9387. for (let side of sideResult) {
  9388. const quests = [...(side.newQuests ?? []), ...(side.quests ?? [])];
  9389. for (let quest of quests) {
  9390. if ((quest.id < 1e6 || (quest.id >= 2e7 && quest.id < 2001e4)) && quest.state == 2) {
  9391. questsIds.push(quest.id);
  9392. }
  9393. }
  9394. }
  9395. questsIds = [...new Set(questsIds)];
  9396. }
  9397.  
  9398. setProgress(I18N('COLLECT_REWARDS_AND_MAIL', { countQuests, countMail }), true);
  9399. } catch (error) {
  9400. console.error('Error in questAllFarm:', error);
  9401. }
  9402. }
  9403.  
  9404. class epicBrawl {
  9405. timeout = null;
  9406. time = null;
  9407.  
  9408. constructor() {
  9409. if (epicBrawl.inst) {
  9410. return epicBrawl.inst;
  9411. }
  9412. epicBrawl.inst = this;
  9413. return this;
  9414. }
  9415.  
  9416. runTimeout(func, timeDiff) {
  9417. const worker = new Worker(URL.createObjectURL(new Blob([`
  9418. self.onmessage = function(e) {
  9419. const timeDiff = e.data;
  9420.  
  9421. if (timeDiff > 0) {
  9422. setTimeout(() => {
  9423. self.postMessage(1);
  9424. self.close();
  9425. }, timeDiff);
  9426. }
  9427. };
  9428. `])));
  9429. worker.postMessage(timeDiff);
  9430. worker.onmessage = () => {
  9431. func();
  9432. };
  9433. return true;
  9434. }
  9435.  
  9436. timeDiff(date1, date2) {
  9437. const date1Obj = new Date(date1);
  9438. const date2Obj = new Date(date2);
  9439.  
  9440. const timeDiff = Math.abs(date2Obj - date1Obj);
  9441.  
  9442. const totalSeconds = timeDiff / 1000;
  9443. const minutes = Math.floor(totalSeconds / 60);
  9444. const seconds = Math.floor(totalSeconds % 60);
  9445.  
  9446. const formattedMinutes = String(minutes).padStart(2, '0');
  9447. const formattedSeconds = String(seconds).padStart(2, '0');
  9448.  
  9449. return `${formattedMinutes}:${formattedSeconds}`;
  9450. }
  9451.  
  9452. check() {
  9453. console.log(new Date(this.time))
  9454. if (Date.now() > this.time) {
  9455. this.timeout = null;
  9456. this.start()
  9457. return;
  9458. }
  9459. this.timeout = this.runTimeout(() => this.check(), 6e4);
  9460. return this.timeDiff(this.time, Date.now())
  9461. }
  9462.  
  9463. async start() {
  9464. if (this.timeout) {
  9465. const time = this.timeDiff(this.time, Date.now());
  9466. console.log(new Date(this.time))
  9467. setProgress(I18N('TIMER_ALREADY', { time }), false, hideProgress);
  9468. return;
  9469. }
  9470. setProgress(I18N('EPIC_BRAWL'), false, hideProgress);
  9471. 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));
  9472. const refill = teamInfo[2].refillable.find(n => n.id == 52)
  9473. this.time = (refill.lastRefill + 3600) * 1000
  9474. const attempts = refill.amount;
  9475. if (!attempts) {
  9476. console.log(new Date(this.time));
  9477. const time = this.check();
  9478. setProgress(I18N('NO_ATTEMPTS_TIMER_START', { time }), false, hideProgress);
  9479. return;
  9480. }
  9481.  
  9482. if (!teamInfo[0].epic_brawl) {
  9483. setProgress(I18N('NO_HEROES_PACK'), false, hideProgress);
  9484. return;
  9485. }
  9486.  
  9487. const args = {
  9488. heroes: teamInfo[0].epic_brawl.filter(e => e < 1000),
  9489. pet: teamInfo[0].epic_brawl.filter(e => e > 6000).pop(),
  9490. favor: teamInfo[1].epic_brawl,
  9491. }
  9492.  
  9493. let wins = 0;
  9494. let coins = 0;
  9495. let streak = { progress: 0, nextStage: 0 };
  9496. for (let i = attempts; i > 0; i--) {
  9497. const info = await Send(JSON.stringify({
  9498. calls: [
  9499. { name: "epicBrawl_getEnemy", args: {}, ident: "epicBrawl_getEnemy" }, { name: "epicBrawl_startBattle", args, ident: "epicBrawl_startBattle" }
  9500. ]
  9501. })).then(e => e.results.map(n => n.result.response));
  9502.  
  9503. const { progress, result } = await Calc(info[1].battle);
  9504. 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));
  9505.  
  9506. const resultInfo = endResult[0].result;
  9507. streak = endResult[1];
  9508.  
  9509. wins += resultInfo.win;
  9510. coins += resultInfo.reward ? resultInfo.reward.coin[39] : 0;
  9511.  
  9512. console.log(endResult[0].result)
  9513. if (endResult[1].progress == endResult[1].nextStage) {
  9514. const farm = await Send('{"calls":[{"name":"epicBrawl_farmWinStreak","args":{},"ident":"body"}]}').then(e => e.results[0].result.response);
  9515. coins += farm.coin[39];
  9516. }
  9517.  
  9518. setProgress(I18N('EPIC_BRAWL_RESULT', {
  9519. i, wins, attempts, coins,
  9520. progress: streak.progress,
  9521. nextStage: streak.nextStage,
  9522. end: '',
  9523. }), false, hideProgress);
  9524. }
  9525.  
  9526. console.log(new Date(this.time));
  9527. const time = this.check();
  9528. setProgress(I18N('EPIC_BRAWL_RESULT', {
  9529. wins, attempts, coins,
  9530. i: '',
  9531. progress: streak.progress,
  9532. nextStage: streak.nextStage,
  9533. end: I18N('ATTEMPT_ENDED', { time }),
  9534. }), false, hideProgress);
  9535. }
  9536. }
  9537.  
  9538. function countdownTimer(seconds, message, onClick = null) {
  9539. message = message || I18N('TIMER');
  9540. const stopTimer = Date.now() + seconds * 1e3;
  9541. const isOnClick = typeof onClick === 'function';
  9542. return new Promise((resolve) => {
  9543. const interval = setInterval(async () => {
  9544. const now = Date.now();
  9545. const remaining = (stopTimer - now) / 1000;
  9546. const clickHandler = isOnClick
  9547. ? () => {
  9548. onClick();
  9549. clearInterval(interval);
  9550. setProgress('', true);
  9551. resolve(false);
  9552. }
  9553. : undefined;
  9554.  
  9555. setProgress(`${message} ${remaining.toFixed(2)}`, false, clickHandler);
  9556. if (now > stopTimer) {
  9557. clearInterval(interval);
  9558. setProgress('', true);
  9559. resolve(true);
  9560. }
  9561. }, 100);
  9562. });
  9563. }
  9564.  
  9565. this.HWHFuncs.countdownTimer = countdownTimer;
  9566.  
  9567. /** Набить килов в горниле душк */
  9568. async function bossRatingEventSouls() {
  9569. const data = await Send({
  9570. calls: [
  9571. { name: "heroGetAll", args: {}, ident: "teamGetAll" },
  9572. { name: "offerGetAll", args: {}, ident: "offerGetAll" },
  9573. { name: "pet_getAll", args: {}, ident: "pet_getAll" },
  9574. ]
  9575. });
  9576. const bossEventInfo = data.results[1].result.response.find(e => e.offerType == "bossEvent");
  9577. if (!bossEventInfo) {
  9578. setProgress('Эвент завершен', true);
  9579. return;
  9580. }
  9581.  
  9582. if (bossEventInfo.progress.score > 250) {
  9583. setProgress('Уже убито больше 250 врагов');
  9584. rewardBossRatingEventSouls();
  9585. return;
  9586. }
  9587. const availablePets = Object.values(data.results[2].result.response).map(e => e.id);
  9588. const heroGetAllList = data.results[0].result.response;
  9589. const usedHeroes = bossEventInfo.progress.usedHeroes;
  9590. const heroList = [];
  9591.  
  9592. for (let heroId in heroGetAllList) {
  9593. let hero = heroGetAllList[heroId];
  9594. if (usedHeroes.includes(hero.id)) {
  9595. continue;
  9596. }
  9597. heroList.push(hero.id);
  9598. }
  9599.  
  9600. if (!heroList.length) {
  9601. setProgress('Нет героев', true);
  9602. return;
  9603. }
  9604.  
  9605. const pet = availablePets.includes(6005) ? 6005 : availablePets[Math.floor(Math.random() * availablePets.length)];
  9606. const petLib = lib.getData('pet');
  9607. let count = 1;
  9608.  
  9609. for (const heroId of heroList) {
  9610. const args = {
  9611. heroes: [heroId],
  9612. pet
  9613. }
  9614. /** Поиск питомца для героя */
  9615. for (const petId of availablePets) {
  9616. if (petLib[petId].favorHeroes.includes(heroId)) {
  9617. args.favor = {
  9618. [heroId]: petId
  9619. }
  9620. break;
  9621. }
  9622. }
  9623.  
  9624. const calls = [{
  9625. name: "bossRatingEvent_startBattle",
  9626. args,
  9627. ident: "body"
  9628. }, {
  9629. name: "offerGetAll",
  9630. args: {},
  9631. ident: "offerGetAll"
  9632. }];
  9633.  
  9634. const res = await Send({ calls });
  9635. count++;
  9636.  
  9637. if ('error' in res) {
  9638. console.error(res.error);
  9639. setProgress('Перезагрузите игру и попробуйте позже', true);
  9640. return;
  9641. }
  9642.  
  9643. const eventInfo = res.results[1].result.response.find(e => e.offerType == "bossEvent");
  9644. if (eventInfo.progress.score > 250) {
  9645. break;
  9646. }
  9647. setProgress('Количество убитых врагов: ' + eventInfo.progress.score + '<br>Использовано ' + count + ' героев');
  9648. }
  9649.  
  9650. rewardBossRatingEventSouls();
  9651. }
  9652. /** Сбор награды из Горнила Душ */
  9653. async function rewardBossRatingEventSouls() {
  9654. const data = await Send({
  9655. calls: [
  9656. { name: "offerGetAll", args: {}, ident: "offerGetAll" }
  9657. ]
  9658. });
  9659.  
  9660. const bossEventInfo = data.results[0].result.response.find(e => e.offerType == "bossEvent");
  9661. if (!bossEventInfo) {
  9662. setProgress('Эвент завершен', true);
  9663. return;
  9664. }
  9665.  
  9666. const farmedChests = bossEventInfo.progress.farmedChests;
  9667. const score = bossEventInfo.progress.score;
  9668. // setProgress('Количество убитых врагов: ' + score);
  9669. const revard = bossEventInfo.reward;
  9670. const calls = [];
  9671.  
  9672. let count = 0;
  9673. for (let i = 1; i < 10; i++) {
  9674. if (farmedChests.includes(i)) {
  9675. continue;
  9676. }
  9677. if (score < revard[i].score) {
  9678. break;
  9679. }
  9680. calls.push({
  9681. name: "bossRatingEvent_getReward",
  9682. args: {
  9683. rewardId: i
  9684. },
  9685. ident: "body_" + i
  9686. });
  9687. count++;
  9688. }
  9689. if (!count) {
  9690. setProgress('Нечего собирать', true);
  9691. return;
  9692. }
  9693.  
  9694. Send({ calls }).then(e => {
  9695. console.log(e);
  9696. setProgress('Собрано ' + e?.results?.length + ' наград', true);
  9697. })
  9698. }
  9699. /**
  9700. * Spin the Seer
  9701. *
  9702. * Покрутить провидца
  9703. */
  9704. async function rollAscension() {
  9705. const refillable = await Send({calls:[
  9706. {
  9707. name:"userGetInfo",
  9708. args:{},
  9709. ident:"userGetInfo"
  9710. }
  9711. ]}).then(e => e.results[0].result.response.refillable);
  9712. const i47 = refillable.find(i => i.id == 47);
  9713. if (i47?.amount) {
  9714. await Send({ calls: [{ name: "ascensionChest_open", args: { paid: false, amount: 1 }, ident: "body" }] });
  9715. setProgress(I18N('DONE'), true);
  9716. } else {
  9717. setProgress(I18N('NOT_ENOUGH_AP'), true);
  9718. }
  9719. }
  9720.  
  9721. /**
  9722. * Collect gifts for the New Year
  9723. *
  9724. * Собрать подарки на новый год
  9725. */
  9726. function getGiftNewYear() {
  9727. Send({ calls: [{ name: "newYearGiftGet", args: { type: 0 }, ident: "body" }] }).then(e => {
  9728. const gifts = e.results[0].result.response.gifts;
  9729. const calls = gifts.filter(e => e.opened == 0).map(e => ({
  9730. name: "newYearGiftOpen",
  9731. args: {
  9732. giftId: e.id
  9733. },
  9734. ident: `body_${e.id}`
  9735. }));
  9736. if (!calls.length) {
  9737. setProgress(I18N('NY_NO_GIFTS'), 5000);
  9738. return;
  9739. }
  9740. Send({ calls }).then(e => {
  9741. console.log(e.results)
  9742. const msg = I18N('NY_GIFTS_COLLECTED', { count: e.results.length });
  9743. console.log(msg);
  9744. setProgress(msg, 5000);
  9745. });
  9746. })
  9747. }
  9748.  
  9749. async function updateArtifacts() {
  9750. const count = +await popup.confirm(I18N('SET_NUMBER_LEVELS'), [
  9751. { msg: I18N('BTN_GO'), isInput: true, default: 10 },
  9752. { result: false, isClose: true }
  9753. ]);
  9754. if (!count) {
  9755. return;
  9756. }
  9757. const quest = new questRun;
  9758. await quest.autoInit();
  9759. const heroes = Object.values(quest.questInfo['heroGetAll']);
  9760. const inventory = quest.questInfo['inventoryGet'];
  9761. const calls = [];
  9762. for (let i = count; i > 0; i--) {
  9763. const upArtifact = quest.getUpgradeArtifact();
  9764. if (!upArtifact.heroId) {
  9765. if (await popup.confirm(I18N('POSSIBLE_IMPROVE_LEVELS', { count: calls.length }), [
  9766. { msg: I18N('YES'), result: true },
  9767. { result: false, isClose: true }
  9768. ])) {
  9769. break;
  9770. } else {
  9771. return;
  9772. }
  9773. }
  9774. const hero = heroes.find(e => e.id == upArtifact.heroId);
  9775. hero.artifacts[upArtifact.slotId].level++;
  9776. inventory[upArtifact.costCurrency][upArtifact.costId] -= upArtifact.costValue;
  9777. calls.push({
  9778. name: "heroArtifactLevelUp",
  9779. args: {
  9780. heroId: upArtifact.heroId,
  9781. slotId: upArtifact.slotId
  9782. },
  9783. ident: `heroArtifactLevelUp_${i}`
  9784. });
  9785. }
  9786.  
  9787. if (!calls.length) {
  9788. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  9789. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  9790. return;
  9791. }
  9792.  
  9793. await Send(JSON.stringify({ calls })).then(e => {
  9794. if ('error' in e) {
  9795. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  9796. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  9797. } else {
  9798. console.log(I18N('IMPROVED_LEVELS', { count: e.results.length }));
  9799. setProgress(I18N('IMPROVED_LEVELS', { count: e.results.length }), false);
  9800. }
  9801. });
  9802. }
  9803.  
  9804. window.sign = a => {
  9805. const i = this['\x78\x79\x7a'];
  9806. 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'))
  9807. }
  9808.  
  9809. async function updateSkins() {
  9810. const count = +await popup.confirm(I18N('SET_NUMBER_LEVELS'), [
  9811. { msg: I18N('BTN_GO'), isInput: true, default: 10 },
  9812. { result: false, isClose: true }
  9813. ]);
  9814. if (!count) {
  9815. return;
  9816. }
  9817.  
  9818. const quest = new questRun;
  9819. await quest.autoInit();
  9820. const heroes = Object.values(quest.questInfo['heroGetAll']);
  9821. const inventory = quest.questInfo['inventoryGet'];
  9822. const calls = [];
  9823. for (let i = count; i > 0; i--) {
  9824. const upSkin = quest.getUpgradeSkin();
  9825. if (!upSkin.heroId) {
  9826. if (await popup.confirm(I18N('POSSIBLE_IMPROVE_LEVELS', { count: calls.length }), [
  9827. { msg: I18N('YES'), result: true },
  9828. { result: false, isClose: true }
  9829. ])) {
  9830. break;
  9831. } else {
  9832. return;
  9833. }
  9834. }
  9835. const hero = heroes.find(e => e.id == upSkin.heroId);
  9836. hero.skins[upSkin.skinId]++;
  9837. inventory[upSkin.costCurrency][upSkin.costCurrencyId] -= upSkin.cost;
  9838. calls.push({
  9839. name: "heroSkinUpgrade",
  9840. args: {
  9841. heroId: upSkin.heroId,
  9842. skinId: upSkin.skinId
  9843. },
  9844. ident: `heroSkinUpgrade_${i}`
  9845. })
  9846. }
  9847.  
  9848. if (!calls.length) {
  9849. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  9850. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  9851. return;
  9852. }
  9853.  
  9854. await Send(JSON.stringify({ calls })).then(e => {
  9855. if ('error' in e) {
  9856. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  9857. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  9858. } else {
  9859. console.log(I18N('IMPROVED_LEVELS', { count: e.results.length }));
  9860. setProgress(I18N('IMPROVED_LEVELS', { count: e.results.length }), false);
  9861. }
  9862. });
  9863. }
  9864.  
  9865. function getQuestionInfo(img, nameOnly = false) {
  9866. const libHeroes = Object.values(lib.data.hero);
  9867. const parts = img.split(':');
  9868. const id = parts[1];
  9869. switch (parts[0]) {
  9870. case 'titanArtifact_id':
  9871. return cheats.translate("LIB_TITAN_ARTIFACT_NAME_" + id);
  9872. case 'titan':
  9873. return cheats.translate("LIB_HERO_NAME_" + id);
  9874. case 'skill':
  9875. return cheats.translate("LIB_SKILL_" + id);
  9876. case 'inventoryItem_gear':
  9877. return cheats.translate("LIB_GEAR_NAME_" + id);
  9878. case 'inventoryItem_coin':
  9879. return cheats.translate("LIB_COIN_NAME_" + id);
  9880. case 'artifact':
  9881. if (nameOnly) {
  9882. return cheats.translate("LIB_ARTIFACT_NAME_" + id);
  9883. }
  9884. heroes = libHeroes.filter(h => h.id < 100 && h.artifacts.includes(+id));
  9885. return {
  9886. /** Как называется этот артефакт? */
  9887. name: cheats.translate("LIB_ARTIFACT_NAME_" + id),
  9888. /** Какому герою принадлежит этот артефакт? */
  9889. heroes: heroes.map(h => cheats.translate("LIB_HERO_NAME_" + h.id))
  9890. };
  9891. case 'hero':
  9892. if (nameOnly) {
  9893. return cheats.translate("LIB_HERO_NAME_" + id);
  9894. }
  9895. artifacts = lib.data.hero[id].artifacts;
  9896. return {
  9897. /** Как зовут этого героя? */
  9898. name: cheats.translate("LIB_HERO_NAME_" + id),
  9899. /** Какой артефакт принадлежит этому герою? */
  9900. artifact: artifacts.map(a => cheats.translate("LIB_ARTIFACT_NAME_" + a))
  9901. };
  9902. }
  9903. }
  9904.  
  9905. function hintQuest(quest) {
  9906. const result = {};
  9907. if (quest?.questionIcon) {
  9908. const info = getQuestionInfo(quest.questionIcon);
  9909. if (info?.heroes) {
  9910. /** Какому герою принадлежит этот артефакт? */
  9911. result.answer = quest.answers.filter(e => info.heroes.includes(e.answerText.slice(1)));
  9912. }
  9913. if (info?.artifact) {
  9914. /** Какой артефакт принадлежит этому герою? */
  9915. result.answer = quest.answers.filter(e => info.artifact.includes(e.answerText.slice(1)));
  9916. }
  9917. if (typeof info == 'string') {
  9918. result.info = { name: info };
  9919. } else {
  9920. result.info = info;
  9921. }
  9922. }
  9923.  
  9924. if (quest.answers[0]?.answerIcon) {
  9925. result.answer = quest.answers.filter(e => quest.question.includes(getQuestionInfo(e.answerIcon, true)))
  9926. }
  9927.  
  9928. if ((!result?.answer || !result.answer.length) && !result.info?.name) {
  9929. return false;
  9930. }
  9931.  
  9932. let resultText = '';
  9933. if (result?.info) {
  9934. resultText += I18N('PICTURE') + result.info.name;
  9935. }
  9936. console.log(result);
  9937. if (result?.answer && result.answer.length) {
  9938. resultText += I18N('ANSWER') + result.answer[0].id + (!result.answer[0].answerIcon ? ' - ' + result.answer[0].answerText : '');
  9939. }
  9940.  
  9941. return resultText;
  9942. }
  9943.  
  9944. async function farmBattlePass() {
  9945. const isFarmReward = (reward) => {
  9946. return !(reward?.buff || reward?.fragmentHero || reward?.bundleHeroReward);
  9947. };
  9948.  
  9949. const battlePassProcess = (pass) => {
  9950. if (!pass.id) {return []}
  9951. const levels = Object.values(lib.data.battlePass.level).filter(x => x.battlePass == pass.id)
  9952. const last_level = levels[levels.length - 1];
  9953. let actual = Math.max(...levels.filter(p => pass.exp >= p.experience).map(p => p.level))
  9954.  
  9955. if (pass.exp > last_level.experience) {
  9956. actual = last_level.level + (pass.exp - last_level.experience) / last_level.experienceByLevel;
  9957. }
  9958. const calls = [];
  9959. for(let i = 1; i <= actual; i++) {
  9960. const level = i >= last_level.level ? last_level : levels.find(l => l.level === i);
  9961. const reward = {free: level?.freeReward, paid:level?.paidReward};
  9962.  
  9963. if (!pass.rewards[i]?.free && isFarmReward(reward.free)) {
  9964. const args = {level: i, free:true};
  9965. if (!pass.gold) { args.id = pass.id }
  9966. calls.push({ name: 'battlePass_farmReward', args, ident: `${pass.gold ? 'body' : 'spesial'}_free_${args.id}_${i}` });
  9967. }
  9968. if (pass.ticket && !pass.rewards[i]?.paid && isFarmReward(reward.paid)) {
  9969. const args = {level: i, free:false};
  9970. if (!pass.gold) { args.id = pass.id}
  9971. calls.push({ name: 'battlePass_farmReward', args, ident: `${pass.gold ? 'body' : 'spesial'}_paid_${args.id}_${i}` });
  9972. }
  9973. }
  9974. return calls;
  9975. }
  9976.  
  9977. const passes = await Send({
  9978. calls: [
  9979. { name: 'battlePass_getInfo', args: {}, ident: 'getInfo' },
  9980. { name: 'battlePass_getSpecial', args: {}, ident: 'getSpecial' },
  9981. ],
  9982. }).then((e) => [{...e.results[0].result.response?.battlePass, gold: true}, ...Object.values(e.results[1].result.response)]);
  9983.  
  9984. const calls = passes.map(p => battlePassProcess(p)).flat()
  9985.  
  9986. if (!calls.length) {
  9987. setProgress(I18N('NOTHING_TO_COLLECT'));
  9988. return;
  9989. }
  9990.  
  9991. let results = await Send({calls});
  9992. if (results.error) {
  9993. console.log(results.error);
  9994. setProgress(I18N('SOMETHING_WENT_WRONG'));
  9995. } else {
  9996. setProgress(I18N('SEASON_REWARD_COLLECTED', {count: results.results.length}), true);
  9997. }
  9998. }
  9999.  
  10000. async function sellHeroSoulsForGold() {
  10001. let { fragmentHero, heroes } = await Send({
  10002. calls: [
  10003. { name: 'inventoryGet', args: {}, ident: 'inventoryGet' },
  10004. { name: 'heroGetAll', args: {}, ident: 'heroGetAll' },
  10005. ],
  10006. })
  10007. .then((e) => e.results.map((r) => r.result.response))
  10008. .then((e) => ({ fragmentHero: e[0].fragmentHero, heroes: e[1] }));
  10009.  
  10010. const calls = [];
  10011. for (let i in fragmentHero) {
  10012. if (heroes[i] && heroes[i].star == 6) {
  10013. calls.push({
  10014. name: 'inventorySell',
  10015. args: {
  10016. type: 'hero',
  10017. libId: i,
  10018. amount: fragmentHero[i],
  10019. fragment: true,
  10020. },
  10021. ident: 'inventorySell_' + i,
  10022. });
  10023. }
  10024. }
  10025. if (!calls.length) {
  10026. console.log(0);
  10027. return 0;
  10028. }
  10029. const rewards = await Send({ calls }).then((e) => e.results.map((r) => r.result?.response?.gold || 0));
  10030. const gold = rewards.reduce((e, a) => e + a, 0);
  10031. setProgress(I18N('GOLD_RECEIVED', { gold }), true);
  10032. }
  10033.  
  10034. /**
  10035. * Attack of the minions of Asgard
  10036. *
  10037. * Атака прислужников Асгарда
  10038. */
  10039. function testRaidNodes() {
  10040. const { executeRaidNodes } = HWHClasses;
  10041. return new Promise((resolve, reject) => {
  10042. const tower = new executeRaidNodes(resolve, reject);
  10043. tower.start();
  10044. });
  10045. }
  10046.  
  10047. /**
  10048. * Attack of the minions of Asgard
  10049. *
  10050. * Атака прислужников Асгарда
  10051. */
  10052. function executeRaidNodes(resolve, reject) {
  10053. let raidData = {
  10054. teams: [],
  10055. favor: {},
  10056. nodes: [],
  10057. attempts: 0,
  10058. countExecuteBattles: 0,
  10059. cancelBattle: 0,
  10060. }
  10061.  
  10062. callsExecuteRaidNodes = {
  10063. calls: [{
  10064. name: "clanRaid_getInfo",
  10065. args: {},
  10066. ident: "clanRaid_getInfo"
  10067. }, {
  10068. name: "teamGetAll",
  10069. args: {},
  10070. ident: "teamGetAll"
  10071. }, {
  10072. name: "teamGetFavor",
  10073. args: {},
  10074. ident: "teamGetFavor"
  10075. }]
  10076. }
  10077.  
  10078. this.start = function () {
  10079. send(JSON.stringify(callsExecuteRaidNodes), startRaidNodes);
  10080. }
  10081.  
  10082. async function startRaidNodes(data) {
  10083. res = data.results;
  10084. clanRaidInfo = res[0].result.response;
  10085. teamGetAll = res[1].result.response;
  10086. teamGetFavor = res[2].result.response;
  10087.  
  10088. let index = 0;
  10089. let isNotFullPack = false;
  10090. for (let team of teamGetAll.clanRaid_nodes) {
  10091. if (team.length < 6) {
  10092. isNotFullPack = true;
  10093. }
  10094. raidData.teams.push({
  10095. data: {},
  10096. heroes: team.filter(id => id < 6000),
  10097. pet: team.filter(id => id >= 6000).pop(),
  10098. battleIndex: index++
  10099. });
  10100. }
  10101. raidData.favor = teamGetFavor.clanRaid_nodes;
  10102.  
  10103. if (isNotFullPack) {
  10104. if (await popup.confirm(I18N('MINIONS_WARNING'), [
  10105. { msg: I18N('BTN_NO'), result: true },
  10106. { msg: I18N('BTN_YES'), result: false },
  10107. ])) {
  10108. endRaidNodes('isNotFullPack');
  10109. return;
  10110. }
  10111. }
  10112.  
  10113. raidData.nodes = clanRaidInfo.nodes;
  10114. raidData.attempts = clanRaidInfo.attempts;
  10115. setIsCancalBattle(false);
  10116.  
  10117. checkNodes();
  10118. }
  10119.  
  10120. function getAttackNode() {
  10121. for (let nodeId in raidData.nodes) {
  10122. let node = raidData.nodes[nodeId];
  10123. let points = 0
  10124. for (team of node.teams) {
  10125. points += team.points;
  10126. }
  10127. let now = Date.now() / 1000;
  10128. if (!points && now > node.timestamps.start && now < node.timestamps.end) {
  10129. let countTeam = node.teams.length;
  10130. delete raidData.nodes[nodeId];
  10131. return {
  10132. nodeId,
  10133. countTeam
  10134. };
  10135. }
  10136. }
  10137. return null;
  10138. }
  10139.  
  10140. function checkNodes() {
  10141. setProgress(`${I18N('REMAINING_ATTEMPTS')}: ${raidData.attempts}`);
  10142. let nodeInfo = getAttackNode();
  10143. if (nodeInfo && raidData.attempts) {
  10144. startNodeBattles(nodeInfo);
  10145. return;
  10146. }
  10147.  
  10148. endRaidNodes('EndRaidNodes');
  10149. }
  10150.  
  10151. function startNodeBattles(nodeInfo) {
  10152. let {nodeId, countTeam} = nodeInfo;
  10153. let teams = raidData.teams.slice(0, countTeam);
  10154. let heroes = raidData.teams.map(e => e.heroes).flat();
  10155. let favor = {...raidData.favor};
  10156. for (let heroId in favor) {
  10157. if (!heroes.includes(+heroId)) {
  10158. delete favor[heroId];
  10159. }
  10160. }
  10161.  
  10162. let calls = [{
  10163. name: "clanRaid_startNodeBattles",
  10164. args: {
  10165. nodeId,
  10166. teams,
  10167. favor
  10168. },
  10169. ident: "body"
  10170. }];
  10171.  
  10172. send(JSON.stringify({calls}), resultNodeBattles);
  10173. }
  10174.  
  10175. function resultNodeBattles(e) {
  10176. if (e['error']) {
  10177. endRaidNodes('nodeBattlesError', e['error']);
  10178. return;
  10179. }
  10180.  
  10181. console.log(e);
  10182. let battles = e.results[0].result.response.battles;
  10183. let promises = [];
  10184. let battleIndex = 0;
  10185. for (let battle of battles) {
  10186. battle.battleIndex = battleIndex++;
  10187. promises.push(calcBattleResult(battle));
  10188. }
  10189.  
  10190. Promise.all(promises)
  10191. .then(results => {
  10192. const endResults = {};
  10193. let isAllWin = true;
  10194. for (let r of results) {
  10195. isAllWin &&= r.result.win;
  10196. }
  10197. if (!isAllWin) {
  10198. cancelEndNodeBattle(results[0]);
  10199. return;
  10200. }
  10201. raidData.countExecuteBattles = results.length;
  10202. let timeout = 500;
  10203. for (let r of results) {
  10204. setTimeout(endNodeBattle, timeout, r);
  10205. timeout += 500;
  10206. }
  10207. });
  10208. }
  10209. /**
  10210. * Returns the battle calculation promise
  10211. *
  10212. * Возвращает промис расчета боя
  10213. */
  10214. function calcBattleResult(battleData) {
  10215. return new Promise(function (resolve, reject) {
  10216. BattleCalc(battleData, "get_clanPvp", resolve);
  10217. });
  10218. }
  10219. /**
  10220. * Cancels the fight
  10221. *
  10222. * Отменяет бой
  10223. */
  10224. function cancelEndNodeBattle(r) {
  10225. const fixBattle = function (heroes) {
  10226. for (const ids in heroes) {
  10227. hero = heroes[ids];
  10228. hero.energy = random(1, 999);
  10229. if (hero.hp > 0) {
  10230. hero.hp = random(1, hero.hp);
  10231. }
  10232. }
  10233. }
  10234. fixBattle(r.progress[0].attackers.heroes);
  10235. fixBattle(r.progress[0].defenders.heroes);
  10236. endNodeBattle(r);
  10237. }
  10238. /**
  10239. * Ends the fight
  10240. *
  10241. * Завершает бой
  10242. */
  10243. function endNodeBattle(r) {
  10244. let nodeId = r.battleData.result.nodeId;
  10245. let battleIndex = r.battleData.battleIndex;
  10246. let calls = [{
  10247. name: "clanRaid_endNodeBattle",
  10248. args: {
  10249. nodeId,
  10250. battleIndex,
  10251. result: r.result,
  10252. progress: r.progress
  10253. },
  10254. ident: "body"
  10255. }]
  10256.  
  10257. SendRequest(JSON.stringify({calls}), battleResult);
  10258. }
  10259. /**
  10260. * Processing the results of the battle
  10261. *
  10262. * Обработка результатов боя
  10263. */
  10264. function battleResult(e) {
  10265. if (e['error']) {
  10266. endRaidNodes('missionEndError', e['error']);
  10267. return;
  10268. }
  10269. r = e.results[0].result.response;
  10270. if (r['error']) {
  10271. if (r.reason == "invalidBattle") {
  10272. raidData.cancelBattle++;
  10273. checkNodes();
  10274. } else {
  10275. endRaidNodes('missionEndError', e['error']);
  10276. }
  10277. return;
  10278. }
  10279.  
  10280. if (!(--raidData.countExecuteBattles)) {
  10281. raidData.attempts--;
  10282. checkNodes();
  10283. }
  10284. }
  10285. /**
  10286. * Completing a task
  10287. *
  10288. * Завершение задачи
  10289. */
  10290. function endRaidNodes(reason, info) {
  10291. setIsCancalBattle(true);
  10292. let textCancel = raidData.cancelBattle ? ` ${I18N('BATTLES_CANCELED')}: ${raidData.cancelBattle}` : '';
  10293. setProgress(`${I18N('MINION_RAID')} ${I18N('COMPLETED')}! ${textCancel}`, true);
  10294. console.log(reason, info);
  10295. resolve();
  10296. }
  10297. }
  10298.  
  10299. this.HWHClasses.executeRaidNodes = executeRaidNodes;
  10300.  
  10301. /**
  10302. * Asgard Boss Attack Replay
  10303. *
  10304. * Повтор атаки босса Асгарда
  10305. */
  10306. function testBossBattle() {
  10307. const { executeBossBattle } = HWHClasses;
  10308. return new Promise((resolve, reject) => {
  10309. const bossBattle = new executeBossBattle(resolve, reject);
  10310. bossBattle.start(lastBossBattle);
  10311. });
  10312. }
  10313.  
  10314. /**
  10315. * Asgard Boss Attack Replay
  10316. *
  10317. * Повтор атаки босса Асгарда
  10318. */
  10319. function executeBossBattle(resolve, reject) {
  10320.  
  10321. this.start = function (battleInfo) {
  10322. preCalcBattle(battleInfo);
  10323. }
  10324.  
  10325. function getBattleInfo(battle) {
  10326. return new Promise(function (resolve) {
  10327. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  10328. BattleCalc(battle, getBattleType(battle.type), e => {
  10329. let extra = e.progress[0].defenders.heroes[1].extra;
  10330. resolve(extra.damageTaken + extra.damageTakenNextLevel);
  10331. });
  10332. });
  10333. }
  10334.  
  10335. function preCalcBattle(battle) {
  10336. let actions = [];
  10337. const countTestBattle = getInput('countTestBattle');
  10338. for (let i = 0; i < countTestBattle; i++) {
  10339. actions.push(getBattleInfo(battle, true));
  10340. }
  10341. Promise.all(actions)
  10342. .then(resultPreCalcBattle);
  10343. }
  10344.  
  10345. async function resultPreCalcBattle(damages) {
  10346. let maxDamage = 0;
  10347. let minDamage = 1e10;
  10348. let avgDamage = 0;
  10349. for (let damage of damages) {
  10350. avgDamage += damage
  10351. if (damage > maxDamage) {
  10352. maxDamage = damage;
  10353. }
  10354. if (damage < minDamage) {
  10355. minDamage = damage;
  10356. }
  10357. }
  10358. avgDamage /= damages.length;
  10359. console.log(damages.map(e => e.toLocaleString()).join('\n'), avgDamage, maxDamage);
  10360.  
  10361. await popup.confirm(
  10362. `${I18N('ROUND_STAT')} ${damages.length} ${I18N('BATTLE')}:` +
  10363. `<br>${I18N('MINIMUM')}: ` + minDamage.toLocaleString() +
  10364. `<br>${I18N('MAXIMUM')}: ` + maxDamage.toLocaleString() +
  10365. `<br>${I18N('AVERAGE')}: ` + avgDamage.toLocaleString()
  10366. , [
  10367. { msg: I18N('BTN_OK'), result: 0},
  10368. ])
  10369. endBossBattle(I18N('BTN_CANCEL'));
  10370. }
  10371.  
  10372. /**
  10373. * Completing a task
  10374. *
  10375. * Завершение задачи
  10376. */
  10377. function endBossBattle(reason, info) {
  10378. console.log(reason, info);
  10379. resolve();
  10380. }
  10381. }
  10382.  
  10383. this.HWHClasses.executeBossBattle = executeBossBattle;
  10384.  
  10385. class FixBattle {
  10386. minTimer = 1.3;
  10387. maxTimer = 15.3;
  10388.  
  10389. constructor(battle, isTimeout = true) {
  10390. this.battle = structuredClone(battle);
  10391. this.isTimeout = isTimeout;
  10392. this.isGetTimer = true;
  10393. }
  10394.  
  10395. timeout(callback, timeout) {
  10396. if (this.isTimeout) {
  10397. this.worker.postMessage(timeout);
  10398. this.worker.onmessage = callback;
  10399. } else {
  10400. callback();
  10401. }
  10402. }
  10403.  
  10404. randTimer() {
  10405. return Math.random() * (this.maxTimer - this.minTimer + 1) + this.minTimer;
  10406. }
  10407.  
  10408. getTimer() {
  10409. if (this.count === 1) {
  10410. this.initTimers();
  10411. }
  10412.  
  10413. return this.battleLogTimers[this.count];
  10414. }
  10415.  
  10416. setAvgTime(startTime) {
  10417. this.fixTime += Date.now() - startTime;
  10418. this.avgTime = this.fixTime / this.count;
  10419. }
  10420.  
  10421. initTimers() {
  10422. const timers = [...new Set(this.lastResult.battleLogs[0].map((e) => e.time))];
  10423. this.battleLogTimers = timers.sort(() => Math.random() - 0.5);
  10424. this.maxCount = Math.min(this.maxCount, this.battleLogTimers.length);
  10425. console.log('maxCount', this.maxCount);
  10426. }
  10427.  
  10428. init() {
  10429. this.fixTime = 0;
  10430. this.lastTimer = 0;
  10431. this.index = 0;
  10432. this.lastBossDamage = 0;
  10433. this.bestResult = {
  10434. count: 0,
  10435. timer: 0,
  10436. value: -Infinity,
  10437. result: null,
  10438. progress: null,
  10439. };
  10440. this.lastBattleResult = {
  10441. win: false,
  10442. };
  10443. this.worker = new Worker(
  10444. URL.createObjectURL(
  10445. new Blob([
  10446. `self.onmessage = function(e) {
  10447. const timeout = e.data;
  10448. setTimeout(() => {
  10449. self.postMessage(1);
  10450. }, timeout);
  10451. };`,
  10452. ])
  10453. )
  10454. );
  10455. }
  10456.  
  10457. async start(endTime = Date.now() + 6e4, maxCount = 100) {
  10458. this.endTime = endTime;
  10459. this.maxCount = maxCount;
  10460. this.init();
  10461. return await new Promise((resolve) => {
  10462. this.resolve = resolve;
  10463. this.count = 0;
  10464. this.loop();
  10465. });
  10466. }
  10467.  
  10468. endFix() {
  10469. this.bestResult.maxCount = this.count;
  10470. this.worker.terminate();
  10471. console.log('endFix', this.bestResult);
  10472. this.resolve(this.bestResult);
  10473. }
  10474.  
  10475. async loop() {
  10476. const start = Date.now();
  10477. if (this.isEndLoop()) {
  10478. this.endFix();
  10479. return;
  10480. }
  10481. this.count++;
  10482. try {
  10483. this.lastResult = await Calc(this.battle);
  10484. } catch (e) {
  10485. this.updateProgressTimer(this.index++);
  10486. this.timeout(this.loop.bind(this), 0);
  10487. return;
  10488. }
  10489. const { progress, result } = this.lastResult;
  10490. this.lastBattleResult = result;
  10491. this.lastBattleProgress = progress;
  10492. this.setAvgTime(start);
  10493. this.checkResult();
  10494. this.showResult();
  10495. this.updateProgressTimer();
  10496. this.timeout(this.loop.bind(this), 0);
  10497. }
  10498.  
  10499. isEndLoop() {
  10500. return this.count >= this.maxCount || this.endTime < Date.now();
  10501. }
  10502.  
  10503. updateProgressTimer(index = 0) {
  10504. this.lastTimer = this.isGetTimer ? this.getTimer() : this.randTimer();
  10505. this.battle.progress = [{ attackers: { input: ['auto', 0, 0, 'auto', index, this.lastTimer] } }];
  10506. }
  10507.  
  10508. showResult() {
  10509. console.log(
  10510. this.count,
  10511. this.avgTime.toFixed(2),
  10512. (this.endTime - Date.now()) / 1000,
  10513. this.lastTimer.toFixed(2),
  10514. this.lastBossDamage.toLocaleString(),
  10515. this.bestResult.value.toLocaleString()
  10516. );
  10517. }
  10518.  
  10519. checkResult() {
  10520. const { damageTaken, damageTakenNextLevel } = this.lastBattleProgress[0].defenders.heroes[1].extra;
  10521. this.lastBossDamage = damageTaken + damageTakenNextLevel;
  10522. if (this.lastBossDamage > this.bestResult.value) {
  10523. this.bestResult = {
  10524. count: this.count,
  10525. timer: this.lastTimer,
  10526. value: this.lastBossDamage,
  10527. result: structuredClone(this.lastBattleResult),
  10528. progress: structuredClone(this.lastBattleProgress),
  10529. };
  10530. }
  10531. }
  10532.  
  10533. stopFix() {
  10534. this.endTime = 0;
  10535. }
  10536. }
  10537.  
  10538. this.HWHClasses.FixBattle = FixBattle;
  10539.  
  10540. class WinFixBattle extends FixBattle {
  10541. checkResult() {
  10542. if (this.lastBattleResult.win) {
  10543. this.bestResult = {
  10544. count: this.count,
  10545. timer: this.lastTimer,
  10546. value: this.lastBattleResult.stars,
  10547. result: structuredClone(this.lastBattleResult),
  10548. progress: structuredClone(this.lastBattleProgress),
  10549. battleTimer: this.lastResult.battleTimer,
  10550. };
  10551. }
  10552. }
  10553.  
  10554. setWinTimer(value) {
  10555. this.winTimer = value;
  10556. }
  10557.  
  10558. setMaxTimer(value) {
  10559. this.maxTimer = value;
  10560. }
  10561.  
  10562. randTimer() {
  10563. if (this.winTimer) {
  10564. return this.winTimer;
  10565. }
  10566. return super.randTimer();
  10567. }
  10568.  
  10569. isEndLoop() {
  10570. return super.isEndLoop() || this.bestResult.result?.win;
  10571. }
  10572.  
  10573. showResult() {
  10574. console.log(
  10575. this.count,
  10576. this.avgTime.toFixed(2),
  10577. (this.endTime - Date.now()) / 1000,
  10578. this.lastResult.battleTime,
  10579. this.lastTimer,
  10580. this.bestResult.value
  10581. );
  10582. const endTime = ((this.endTime - Date.now()) / 1000).toFixed(2);
  10583. const avgTime = this.avgTime.toFixed(2);
  10584. const msg = `${I18N('LETS_FIX')} ${this.count}/${this.maxCount}<br/>${endTime}s<br/>${avgTime}ms`;
  10585. setProgress(msg, false, this.stopFix.bind(this));
  10586. }
  10587. }
  10588.  
  10589. this.HWHClasses.WinFixBattle = WinFixBattle;
  10590.  
  10591. class BestOrWinFixBattle extends WinFixBattle {
  10592. isNoMakeWin = false;
  10593.  
  10594. getState(result) {
  10595. let beforeSumFactor = 0;
  10596. const beforeHeroes = result.battleData.defenders[0];
  10597. for (let heroId in beforeHeroes) {
  10598. const hero = beforeHeroes[heroId];
  10599. const state = hero.state;
  10600. let factor = 1;
  10601. if (state) {
  10602. const hp = state.hp / (hero?.hp || 1);
  10603. const energy = state.energy / 1e3;
  10604. factor = hp + energy / 20;
  10605. }
  10606. beforeSumFactor += factor;
  10607. }
  10608.  
  10609. let afterSumFactor = 0;
  10610. const afterHeroes = result.progress[0].defenders.heroes;
  10611. for (let heroId in afterHeroes) {
  10612. const hero = afterHeroes[heroId];
  10613. const hp = hero.hp / (beforeHeroes[heroId]?.hp || 1);
  10614. const energy = hero.energy / 1e3;
  10615. const factor = hp + energy / 20;
  10616. afterSumFactor += factor;
  10617. }
  10618. return 100 - Math.floor((afterSumFactor / beforeSumFactor) * 1e4) / 100;
  10619. }
  10620.  
  10621. setNoMakeWin(value) {
  10622. this.isNoMakeWin = value;
  10623. }
  10624.  
  10625. checkResult() {
  10626. const state = this.getState(this.lastResult);
  10627. console.log(state);
  10628.  
  10629. if (state > this.bestResult.value) {
  10630. if (!(this.isNoMakeWin && this.lastBattleResult.win)) {
  10631. this.bestResult = {
  10632. count: this.count,
  10633. timer: this.lastTimer,
  10634. value: state,
  10635. result: structuredClone(this.lastBattleResult),
  10636. progress: structuredClone(this.lastBattleProgress),
  10637. battleTimer: this.lastResult.battleTimer,
  10638. };
  10639. }
  10640. }
  10641. }
  10642. }
  10643.  
  10644. this.HWHClasses.BestOrWinFixBattle = BestOrWinFixBattle;
  10645.  
  10646. class BossFixBattle extends FixBattle {
  10647. showResult() {
  10648. super.showResult();
  10649. //setTimeout(() => {
  10650. const best = this.bestResult;
  10651. const maxDmg = best.value.toLocaleString();
  10652. const avgTime = this.avgTime.toLocaleString();
  10653. const msg = `${I18N('LETS_FIX')} ${this.count}/${this.maxCount}<br/>${maxDmg}<br/>${avgTime}ms`;
  10654. setProgress(msg, false, this.stopFix.bind(this));
  10655. //}, 0);
  10656. }
  10657. }
  10658.  
  10659. this.HWHClasses.BossFixBattle = BossFixBattle;
  10660.  
  10661. class DungeonFixBattle extends FixBattle {
  10662. init() {
  10663. super.init();
  10664. this.isTimeout = false;
  10665. this.bestResult = {
  10666. count: 0,
  10667. timer: 0,
  10668. value: {
  10669. hp: -Infinity,
  10670. energy: -Infinity,
  10671. },
  10672. result: null,
  10673. progress: null,
  10674. };
  10675. }
  10676.  
  10677. setState() {
  10678. const result = this.lastResult;
  10679. const isAllDead = Object.values(result.progress[0].attackers.heroes).every((item) => item.isDead);
  10680. if (isAllDead) {
  10681. this.lastState = {
  10682. hp: -Infinity,
  10683. energy: -Infinity,
  10684. };
  10685. return;
  10686. }
  10687. let beforeHP = 0;
  10688. let beforeEnergy = 0;
  10689. const beforeTitans = result.battleData.attackers;
  10690. for (let titanId in beforeTitans) {
  10691. const titan = beforeTitans[titanId];
  10692. const state = titan.state;
  10693. if (state) {
  10694. beforeHP += state.hp / titan.hp;
  10695. beforeEnergy += state.energy / 1e3;
  10696. }
  10697. }
  10698.  
  10699. let afterHP = 0;
  10700. let afterEnergy = 0;
  10701. const afterTitans = result.progress[0].attackers.heroes;
  10702. for (let titanId in afterTitans) {
  10703. const titan = afterTitans[titanId];
  10704. afterHP += titan.hp / beforeTitans[titanId].hp;
  10705. afterEnergy += titan.energy / 1e3;
  10706. }
  10707.  
  10708. this.lastState = {
  10709. hp: afterHP - beforeHP,
  10710. energy: afterEnergy - beforeEnergy,
  10711. };
  10712. }
  10713.  
  10714. checkResult() {
  10715. this.setState();
  10716. if (
  10717. this.lastState.hp > this.bestResult.value.hp ||
  10718. (this.lastState.hp === this.bestResult.value.hp && this.lastState.energy > this.bestResult.value.energy)
  10719. ) {
  10720. this.bestResult = {
  10721. count: this.count,
  10722. timer: this.lastTimer,
  10723. value: this.lastState,
  10724. result: this.lastResult.result,
  10725. progress: this.lastResult.progress,
  10726. };
  10727. }
  10728. }
  10729.  
  10730. showResult() {
  10731. if (this.isShowResult) {
  10732. console.log(this.count, this.lastTimer.toFixed(2), JSON.stringify(this.lastState), JSON.stringify(this.bestResult.value));
  10733. }
  10734. }
  10735. }
  10736.  
  10737. this.HWHClasses.DungeonFixBattle = DungeonFixBattle;
  10738.  
  10739. const masterWsMixin = {
  10740. wsStart() {
  10741. const socket = new WebSocket(this.url);
  10742.  
  10743. socket.onopen = () => {
  10744. console.log('Connected to server');
  10745.  
  10746. // Пример создания новой задачи
  10747. const newTask = {
  10748. type: 'newTask',
  10749. battle: this.battle,
  10750. endTime: this.endTime - 1e4,
  10751. maxCount: this.maxCount,
  10752. };
  10753. socket.send(JSON.stringify(newTask));
  10754. };
  10755.  
  10756. socket.onmessage = this.onmessage.bind(this);
  10757.  
  10758. socket.onclose = () => {
  10759. console.log('Disconnected from server');
  10760. };
  10761.  
  10762. this.ws = socket;
  10763. },
  10764.  
  10765. onmessage(event) {
  10766. const data = JSON.parse(event.data);
  10767. switch (data.type) {
  10768. case 'newTask': {
  10769. console.log('newTask:', data);
  10770. this.id = data.id;
  10771. this.countExecutor = data.count;
  10772. break;
  10773. }
  10774. case 'getSolTask': {
  10775. console.log('getSolTask:', data);
  10776. this.endFix(data.solutions);
  10777. break;
  10778. }
  10779. case 'resolveTask': {
  10780. console.log('resolveTask:', data);
  10781. if (data.id === this.id && data.solutions.length === this.countExecutor) {
  10782. this.worker.terminate();
  10783. this.endFix(data.solutions);
  10784. }
  10785. break;
  10786. }
  10787. default:
  10788. console.log('Unknown message type:', data.type);
  10789. }
  10790. },
  10791.  
  10792. getTask() {
  10793. this.ws.send(
  10794. JSON.stringify({
  10795. type: 'getSolTask',
  10796. id: this.id,
  10797. })
  10798. );
  10799. },
  10800. };
  10801.  
  10802. /*
  10803. mFix = new action.masterFixBattle(battle)
  10804. await mFix.start(Date.now() + 6e4, 1);
  10805. */
  10806. class masterFixBattle extends FixBattle {
  10807. constructor(battle, url = 'wss://localho.st:3000') {
  10808. super(battle, true);
  10809. this.url = url;
  10810. }
  10811.  
  10812. async start(endTime, maxCount) {
  10813. this.endTime = endTime;
  10814. this.maxCount = maxCount;
  10815. this.init();
  10816. this.wsStart();
  10817. return await new Promise((resolve) => {
  10818. this.resolve = resolve;
  10819. const timeout = this.endTime - Date.now();
  10820. this.timeout(this.getTask.bind(this), timeout);
  10821. });
  10822. }
  10823.  
  10824. async endFix(solutions) {
  10825. this.ws.close();
  10826. let maxCount = 0;
  10827. for (const solution of solutions) {
  10828. maxCount += solution.maxCount;
  10829. if (solution.value > this.bestResult.value) {
  10830. this.bestResult = solution;
  10831. }
  10832. }
  10833. this.count = maxCount;
  10834. super.endFix();
  10835. }
  10836. }
  10837.  
  10838. Object.assign(masterFixBattle.prototype, masterWsMixin);
  10839.  
  10840. this.HWHClasses.masterFixBattle = masterFixBattle;
  10841.  
  10842. class masterWinFixBattle extends WinFixBattle {
  10843. constructor(battle, url = 'wss://localho.st:3000') {
  10844. super(battle, true);
  10845. this.url = url;
  10846. }
  10847.  
  10848. async start(endTime, maxCount) {
  10849. this.endTime = endTime;
  10850. this.maxCount = maxCount;
  10851. this.init();
  10852. this.wsStart();
  10853. return await new Promise((resolve) => {
  10854. this.resolve = resolve;
  10855. const timeout = this.endTime - Date.now();
  10856. this.timeout(this.getTask.bind(this), timeout);
  10857. });
  10858. }
  10859.  
  10860. async endFix(solutions) {
  10861. this.ws.close();
  10862. let maxCount = 0;
  10863. for (const solution of solutions) {
  10864. maxCount += solution.maxCount;
  10865. if (solution.value > this.bestResult.value) {
  10866. this.bestResult = solution;
  10867. }
  10868. }
  10869. this.count = maxCount;
  10870. super.endFix();
  10871. }
  10872. }
  10873.  
  10874. Object.assign(masterWinFixBattle.prototype, masterWsMixin);
  10875.  
  10876. this.HWHClasses.masterWinFixBattle = masterWinFixBattle;
  10877.  
  10878. const slaveWsMixin = {
  10879. wsStop() {
  10880. this.ws.close();
  10881. },
  10882.  
  10883. wsStart() {
  10884. const socket = new WebSocket(this.url);
  10885.  
  10886. socket.onopen = () => {
  10887. console.log('Connected to server');
  10888. };
  10889. socket.onmessage = this.onmessage.bind(this);
  10890. socket.onclose = () => {
  10891. console.log('Disconnected from server');
  10892. };
  10893.  
  10894. this.ws = socket;
  10895. },
  10896.  
  10897. async onmessage(event) {
  10898. const data = JSON.parse(event.data);
  10899. switch (data.type) {
  10900. case 'newTask': {
  10901. console.log('newTask:', data.task);
  10902. const { battle, endTime, maxCount } = data.task;
  10903. this.battle = battle;
  10904. const id = data.task.id;
  10905. const solution = await this.start(endTime, maxCount);
  10906. this.ws.send(
  10907. JSON.stringify({
  10908. type: 'resolveTask',
  10909. id,
  10910. solution,
  10911. })
  10912. );
  10913. break;
  10914. }
  10915. default:
  10916. console.log('Unknown message type:', data.type);
  10917. }
  10918. },
  10919. };
  10920. /*
  10921. sFix = new action.slaveFixBattle();
  10922. sFix.wsStart()
  10923. */
  10924. class slaveFixBattle extends FixBattle {
  10925. constructor(url = 'wss://localho.st:3000') {
  10926. super(null, false);
  10927. this.isTimeout = false;
  10928. this.url = url;
  10929. }
  10930. }
  10931.  
  10932. Object.assign(slaveFixBattle.prototype, slaveWsMixin);
  10933.  
  10934. this.HWHClasses.slaveFixBattle = slaveFixBattle;
  10935.  
  10936. class slaveWinFixBattle extends WinFixBattle {
  10937. constructor(url = 'wss://localho.st:3000') {
  10938. super(null, false);
  10939. this.isTimeout = false;
  10940. this.url = url;
  10941. }
  10942. }
  10943.  
  10944. Object.assign(slaveWinFixBattle.prototype, slaveWsMixin);
  10945.  
  10946. this.HWHClasses.slaveWinFixBattle = slaveWinFixBattle;
  10947. /**
  10948. * Auto-repeat attack
  10949. *
  10950. * Автоповтор атаки
  10951. */
  10952. function testAutoBattle() {
  10953. const { executeAutoBattle } = HWHClasses;
  10954. return new Promise((resolve, reject) => {
  10955. const bossBattle = new executeAutoBattle(resolve, reject);
  10956. bossBattle.start(lastBattleArg, lastBattleInfo);
  10957. });
  10958. }
  10959.  
  10960. /**
  10961. * Auto-repeat attack
  10962. *
  10963. * Автоповтор атаки
  10964. */
  10965. function executeAutoBattle(resolve, reject) {
  10966. let battleArg = {};
  10967. let countBattle = 0;
  10968. let countError = 0;
  10969. let findCoeff = 0;
  10970. let dataNotEeceived = 0;
  10971. let stopAutoBattle = false;
  10972.  
  10973. let isSetWinTimer = false;
  10974. 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>';
  10975. 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>';
  10976. 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>';
  10977.  
  10978. this.start = function (battleArgs, battleInfo) {
  10979. battleArg = battleArgs;
  10980. if (nameFuncStartBattle == 'invasion_bossStart') {
  10981. startBattle();
  10982. return;
  10983. }
  10984. preCalcBattle(battleInfo);
  10985. }
  10986. /**
  10987. * Returns a promise for combat recalculation
  10988. *
  10989. * Возвращает промис для прерасчета боя
  10990. */
  10991. function getBattleInfo(battle) {
  10992. return new Promise(function (resolve) {
  10993. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  10994. Calc(battle).then(e => {
  10995. e.coeff = calcCoeff(e, 'defenders');
  10996. resolve(e);
  10997. });
  10998. });
  10999. }
  11000. /**
  11001. * Battle recalculation
  11002. *
  11003. * Прерасчет боя
  11004. */
  11005. function preCalcBattle(battle) {
  11006. let actions = [];
  11007. const countTestBattle = getInput('countTestBattle');
  11008. for (let i = 0; i < countTestBattle; i++) {
  11009. actions.push(getBattleInfo(battle));
  11010. }
  11011. Promise.all(actions)
  11012. .then(resultPreCalcBattle);
  11013. }
  11014. /**
  11015. * Processing the results of the battle recalculation
  11016. *
  11017. * Обработка результатов прерасчета боя
  11018. */
  11019. async function resultPreCalcBattle(results) {
  11020. let countWin = results.reduce((s, w) => w.result.win + s, 0);
  11021. setProgress(`${I18N('CHANCE_TO_WIN')} ${Math.floor(countWin / results.length * 100)}% (${results.length})`, false, hideProgress);
  11022. if (countWin > 0) {
  11023. setIsCancalBattle(false);
  11024. startBattle();
  11025. return;
  11026. }
  11027.  
  11028. let minCoeff = 100;
  11029. let maxCoeff = -100;
  11030. let avgCoeff = 0;
  11031. results.forEach(e => {
  11032. if (e.coeff < minCoeff) minCoeff = e.coeff;
  11033. if (e.coeff > maxCoeff) maxCoeff = e.coeff;
  11034. avgCoeff += e.coeff;
  11035. });
  11036. avgCoeff /= results.length;
  11037.  
  11038. if (nameFuncStartBattle == 'invasion_bossStart' ||
  11039. nameFuncStartBattle == 'bossAttack') {
  11040. const result = await popup.confirm(
  11041. I18N('BOSS_VICTORY_IMPOSSIBLE', { battles: results.length }), [
  11042. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  11043. { msg: I18N('BTN_DO_IT'), result: true },
  11044. ])
  11045. if (result) {
  11046. setIsCancalBattle(false);
  11047. startBattle();
  11048. return;
  11049. }
  11050. setProgress(I18N('NOT_THIS_TIME'), true);
  11051. endAutoBattle('invasion_bossStart');
  11052. return;
  11053. }
  11054.  
  11055. const result = await popup.confirm(
  11056. I18N('VICTORY_IMPOSSIBLE') +
  11057. `<br>${I18N('ROUND_STAT')} ${results.length} ${I18N('BATTLE')}:` +
  11058. `<br>${I18N('MINIMUM')}: ` + minCoeff.toLocaleString() +
  11059. `<br>${I18N('MAXIMUM')}: ` + maxCoeff.toLocaleString() +
  11060. `<br>${I18N('AVERAGE')}: ` + avgCoeff.toLocaleString() +
  11061. `<br>${I18N('FIND_COEFF')} ` + avgCoeff.toLocaleString(), [
  11062. { msg: I18N('BTN_CANCEL'), result: 0, isCancel: true },
  11063. { msg: I18N('BTN_GO'), isInput: true, default: Math.round(avgCoeff * 1000) / 1000 },
  11064. ])
  11065. if (result) {
  11066. findCoeff = result;
  11067. setIsCancalBattle(false);
  11068. startBattle();
  11069. return;
  11070. }
  11071. setProgress(I18N('NOT_THIS_TIME'), true);
  11072. endAutoBattle(I18N('NOT_THIS_TIME'));
  11073. }
  11074.  
  11075. /**
  11076. * Calculation of the combat result coefficient
  11077. *
  11078. * Расчет коэфициента результата боя
  11079. */
  11080. function calcCoeff(result, packType) {
  11081. let beforeSumFactor = 0;
  11082. const beforePack = result.battleData[packType][0];
  11083. for (let heroId in beforePack) {
  11084. const hero = beforePack[heroId];
  11085. const state = hero.state;
  11086. let factor = 1;
  11087. if (state) {
  11088. const hp = state.hp / state.maxHp;
  11089. const energy = state.energy / 1e3;
  11090. factor = hp + energy / 20;
  11091. }
  11092. beforeSumFactor += factor;
  11093. }
  11094.  
  11095. let afterSumFactor = 0;
  11096. const afterPack = result.progress[0][packType].heroes;
  11097. for (let heroId in afterPack) {
  11098. const hero = afterPack[heroId];
  11099. const stateHp = beforePack[heroId]?.state?.hp || beforePack[heroId]?.stats?.hp;
  11100. const hp = hero.hp / stateHp;
  11101. const energy = hero.energy / 1e3;
  11102. const factor = hp + energy / 20;
  11103. afterSumFactor += factor;
  11104. }
  11105. const resultCoeff = -(afterSumFactor - beforeSumFactor);
  11106. return Math.round(resultCoeff * 1000) / 1000;
  11107. }
  11108. /**
  11109. * Start battle
  11110. *
  11111. * Начало боя
  11112. */
  11113. function startBattle() {
  11114. countBattle++;
  11115. const countMaxBattle = getInput('countAutoBattle');
  11116. // setProgress(countBattle + '/' + countMaxBattle);
  11117. if (countBattle > countMaxBattle) {
  11118. setProgress(`${I18N('RETRY_LIMIT_EXCEEDED')}: ${countMaxBattle}`, true);
  11119. endAutoBattle(`${I18N('RETRY_LIMIT_EXCEEDED')}: ${countMaxBattle}`)
  11120. return;
  11121. }
  11122. if (stopAutoBattle) {
  11123. setProgress(I18N('STOPPED'), true);
  11124. endAutoBattle('STOPPED');
  11125. return;
  11126. }
  11127. send({calls: [{
  11128. name: nameFuncStartBattle,
  11129. args: battleArg,
  11130. ident: "body"
  11131. }]}, calcResultBattle);
  11132. }
  11133. /**
  11134. * Battle calculation
  11135. *
  11136. * Расчет боя
  11137. */
  11138. async function calcResultBattle(e) {
  11139. if (!e) {
  11140. console.log('данные не были получены');
  11141. if (dataNotEeceived < 10) {
  11142. dataNotEeceived++;
  11143. startBattle();
  11144. return;
  11145. }
  11146. endAutoBattle('Error', 'данные не были получены ' + dataNotEeceived + ' раз');
  11147. return;
  11148. }
  11149. if ('error' in e) {
  11150. if (e.error.description === 'too many tries') {
  11151. invasionTimer += 100;
  11152. countBattle--;
  11153. countError++;
  11154. console.log(`Errors: ${countError}`, e.error);
  11155. startBattle();
  11156. return;
  11157. }
  11158. const result = await popup.confirm(I18N('ERROR_DURING_THE_BATTLE') + '<br>' + e.error.description, [
  11159. { msg: I18N('BTN_OK'), result: false },
  11160. { msg: I18N('RELOAD_GAME'), result: true },
  11161. ]);
  11162. endAutoBattle('Error', e.error);
  11163. if (result) {
  11164. location.reload();
  11165. }
  11166. return;
  11167. }
  11168. let battle = e.results[0].result.response.battle
  11169. if (nameFuncStartBattle == 'towerStartBattle' ||
  11170. nameFuncStartBattle == 'bossAttack' ||
  11171. nameFuncStartBattle == 'invasion_bossStart') {
  11172. battle = e.results[0].result.response;
  11173. }
  11174. lastBattleInfo = battle;
  11175. BattleCalc(battle, getBattleType(battle.type), resultBattle);
  11176. }
  11177. /**
  11178. * Processing the results of the battle
  11179. *
  11180. * Обработка результатов боя
  11181. */
  11182. async function resultBattle(e) {
  11183. const isWin = e.result.win;
  11184. if (isWin) {
  11185. endBattle(e, false);
  11186. return;
  11187. } else if (isChecked('tryFixIt_v2')) {
  11188. const { WinFixBattle } = HWHClasses;
  11189. const cloneBattle = structuredClone(e.battleData);
  11190. const bFix = new WinFixBattle(cloneBattle);
  11191. let attempts = Infinity;
  11192. if (nameFuncStartBattle == 'invasion_bossStart' && !isSetWinTimer) {
  11193. let winTimer = await popup.confirm(`Secret number:`, [
  11194. { result: false, isClose: true },
  11195. { msg: 'Go', isInput: true, default: '0' },
  11196. ]);
  11197. winTimer = Number.parseFloat(winTimer);
  11198. if (winTimer) {
  11199. attempts = 5;
  11200. bFix.setWinTimer(winTimer);
  11201. }
  11202. isSetWinTimer = true;
  11203. }
  11204. let endTime = Date.now() + 6e4;
  11205. if (nameFuncStartBattle == 'invasion_bossStart') {
  11206. endTime = Date.now() + 6e4 * 4;
  11207. bFix.setMaxTimer(120.3);
  11208. }
  11209. const result = await bFix.start(endTime, attempts);
  11210. console.log(result);
  11211. if (result.value) {
  11212. endBattle(result, false);
  11213. return;
  11214. }
  11215. }
  11216. const countMaxBattle = getInput('countAutoBattle');
  11217. if (findCoeff) {
  11218. const coeff = calcCoeff(e, 'defenders');
  11219. setProgress(`${countBattle}/${countMaxBattle}, ${coeff}`);
  11220. if (coeff > findCoeff) {
  11221. endBattle(e, false);
  11222. return;
  11223. }
  11224. } else {
  11225. if (nameFuncStartBattle == 'invasion_bossStart') {
  11226. const bossLvl = lastBattleInfo.typeId >= 130 ? lastBattleInfo.typeId : '';
  11227. const justice = lastBattleInfo?.effects?.attackers?.percentInOutDamageModAndEnergyIncrease_any_99_100_300_99_1000_300 || 0;
  11228. setProgress(`${svgBoss} ${bossLvl} ${svgJustice} ${justice} <br>${svgAttempt} ${countBattle}/${countMaxBattle}`, false, () => {
  11229. stopAutoBattle = true;
  11230. });
  11231. await new Promise((resolve) => setTimeout(resolve, 5000));
  11232. } else {
  11233. setProgress(`${countBattle}/${countMaxBattle}`);
  11234. }
  11235. }
  11236. if (nameFuncStartBattle == 'towerStartBattle' ||
  11237. nameFuncStartBattle == 'bossAttack' ||
  11238. nameFuncStartBattle == 'invasion_bossStart') {
  11239. startBattle();
  11240. return;
  11241. }
  11242. cancelEndBattle(e);
  11243. }
  11244. /**
  11245. * Cancel fight
  11246. *
  11247. * Отмена боя
  11248. */
  11249. function cancelEndBattle(r) {
  11250. const fixBattle = function (heroes) {
  11251. for (const ids in heroes) {
  11252. hero = heroes[ids];
  11253. hero.energy = random(1, 999);
  11254. if (hero.hp > 0) {
  11255. hero.hp = random(1, hero.hp);
  11256. }
  11257. }
  11258. }
  11259. fixBattle(r.progress[0].attackers.heroes);
  11260. fixBattle(r.progress[0].defenders.heroes);
  11261. endBattle(r, true);
  11262. }
  11263. /**
  11264. * End of the fight
  11265. *
  11266. * Завершение боя */
  11267. function endBattle(battleResult, isCancal) {
  11268. let calls = [{
  11269. name: nameFuncEndBattle,
  11270. args: {
  11271. result: battleResult.result,
  11272. progress: battleResult.progress
  11273. },
  11274. ident: "body"
  11275. }];
  11276.  
  11277. if (nameFuncStartBattle == 'invasion_bossStart') {
  11278. calls[0].args.id = lastBattleArg.id;
  11279. }
  11280.  
  11281. send(JSON.stringify({
  11282. calls
  11283. }), async e => {
  11284. console.log(e);
  11285. if (isCancal) {
  11286. startBattle();
  11287. return;
  11288. }
  11289.  
  11290. setProgress(`${I18N('SUCCESS')}!`, 5000)
  11291. if (nameFuncStartBattle == 'invasion_bossStart' ||
  11292. nameFuncStartBattle == 'bossAttack') {
  11293. const countMaxBattle = getInput('countAutoBattle');
  11294. const bossLvl = lastBattleInfo.typeId >= 130 ? lastBattleInfo.typeId : '';
  11295. const justice = lastBattleInfo?.effects?.attackers?.percentInOutDamageModAndEnergyIncrease_any_99_100_300_99_1000_300 || 0;
  11296. let winTimer = '';
  11297. if (nameFuncStartBattle == 'invasion_bossStart') {
  11298. winTimer = '<br>Secret number: ' + battleResult.progress[0].attackers.input[5];
  11299. }
  11300. const result = await popup.confirm(
  11301. I18N('BOSS_HAS_BEEN_DEF_TEXT', {
  11302. bossLvl: `${svgBoss} ${bossLvl} ${svgJustice} ${justice}`,
  11303. countBattle: svgAttempt + ' ' + countBattle,
  11304. countMaxBattle,
  11305. winTimer,
  11306. }),
  11307. [
  11308. { msg: I18N('BTN_OK'), result: 0 },
  11309. { msg: I18N('MAKE_A_SYNC'), result: 1 },
  11310. { msg: I18N('RELOAD_GAME'), result: 2 },
  11311. ]
  11312. );
  11313. if (result) {
  11314. if (result == 1) {
  11315. cheats.refreshGame();
  11316. }
  11317. if (result == 2) {
  11318. location.reload();
  11319. }
  11320. }
  11321.  
  11322. }
  11323. endAutoBattle(`${I18N('SUCCESS')}!`)
  11324. });
  11325. }
  11326. /**
  11327. * Completing a task
  11328. *
  11329. * Завершение задачи
  11330. */
  11331. function endAutoBattle(reason, info) {
  11332. setIsCancalBattle(true);
  11333. console.log(reason, info);
  11334. resolve();
  11335. }
  11336. }
  11337.  
  11338. this.HWHClasses.executeAutoBattle = executeAutoBattle;
  11339.  
  11340. function testDailyQuests() {
  11341. const { dailyQuests } = HWHClasses;
  11342. return new Promise((resolve, reject) => {
  11343. const quests = new dailyQuests(resolve, reject);
  11344. quests.init(questsInfo);
  11345. quests.start();
  11346. });
  11347. }
  11348.  
  11349. /**
  11350. * Automatic completion of daily quests
  11351. *
  11352. * Автоматическое выполнение ежедневных квестов
  11353. */
  11354. class dailyQuests {
  11355. /**
  11356. * Send(' {"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}').then(e => console.log(e))
  11357. * Send(' {"calls":[{"name":"heroGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  11358. * Send(' {"calls":[{"name":"titanGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  11359. * Send(' {"calls":[{"name":"inventoryGet","args":{},"ident":"body"}]}').then(e => console.log(e))
  11360. * Send(' {"calls":[{"name":"questGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  11361. * Send(' {"calls":[{"name":"bossGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  11362. */
  11363. callsList = ['userGetInfo', 'heroGetAll', 'titanGetAll', 'inventoryGet', 'questGetAll', 'bossGetAll', 'missionGetAll'];
  11364.  
  11365. dataQuests = {
  11366. 10001: {
  11367. description: 'Улучши умения героев 3 раза', // ++++++++++++++++
  11368. doItCall: () => {
  11369. const upgradeSkills = this.getUpgradeSkills();
  11370. return upgradeSkills.map(({ heroId, skill }, index) => ({
  11371. name: 'heroUpgradeSkill',
  11372. args: { heroId, skill },
  11373. ident: `heroUpgradeSkill_${index}`,
  11374. }));
  11375. },
  11376. isWeCanDo: () => {
  11377. const upgradeSkills = this.getUpgradeSkills();
  11378. let sumGold = 0;
  11379. for (const skill of upgradeSkills) {
  11380. sumGold += this.skillCost(skill.value);
  11381. if (!skill.heroId) {
  11382. return false;
  11383. }
  11384. }
  11385. return this.questInfo['userGetInfo'].gold > sumGold;
  11386. },
  11387. },
  11388. 10002: {
  11389. description: 'Пройди 10 миссий', // --------------
  11390. isWeCanDo: () => false,
  11391. },
  11392. 10003: {
  11393. description: 'Пройди 3 героические миссии', // ++++++++++++++++
  11394. isWeCanDo: () => {
  11395. const vipPoints = +this.questInfo.userGetInfo.vipPoints;
  11396. const goldTicket = !!this.questInfo.inventoryGet.consumable[151];
  11397. return (vipPoints > 100 || goldTicket) && this.getHeroicMissionId();
  11398. },
  11399. doItCall: () => {
  11400. const selectedMissionId = this.getHeroicMissionId();
  11401. const goldTicket = !!this.questInfo.inventoryGet.consumable[151];
  11402. const vipLevel = Math.max(...lib.data.level.vip.filter(l => l.vipPoints <= +this.questInfo.userGetInfo.vipPoints).map(l => l.level));
  11403. // Возвращаем массив команд для рейда
  11404. if (vipLevel >= 5 || goldTicket) {
  11405. return [{ name: 'missionRaid', args: { id: selectedMissionId, times: 3 }, ident: 'missionRaid_1' }];
  11406. } else {
  11407. return [
  11408. { name: 'missionRaid', args: { id: selectedMissionId, times: 1 }, ident: 'missionRaid_1' },
  11409. { name: 'missionRaid', args: { id: selectedMissionId, times: 1 }, ident: 'missionRaid_2' },
  11410. { name: 'missionRaid', args: { id: selectedMissionId, times: 1 }, ident: 'missionRaid_3' },
  11411. ];
  11412. }
  11413. },
  11414. },
  11415. 10004: {
  11416. description: 'Сразись 3 раза на Арене или Гранд Арене', // --------------
  11417. isWeCanDo: () => false,
  11418. },
  11419. 10006: {
  11420. description: 'Используй обмен изумрудов 1 раз', // ++++++++++++++++
  11421. doItCall: () => [
  11422. {
  11423. name: 'refillableAlchemyUse',
  11424. args: { multi: false },
  11425. ident: 'refillableAlchemyUse',
  11426. },
  11427. ],
  11428. isWeCanDo: () => {
  11429. const starMoney = this.questInfo['userGetInfo'].starMoney;
  11430. return starMoney >= 20;
  11431. },
  11432. },
  11433. 10007: {
  11434. description: 'Соверши 1 призыв в Атриуме Душ', // ++++++++++++++++
  11435. doItCall: () => [{ name: 'gacha_open', args: { ident: 'heroGacha', free: true, pack: false }, ident: 'gacha_open' }],
  11436. isWeCanDo: () => {
  11437. const soulCrystal = this.questInfo['inventoryGet'].coin[38];
  11438. return soulCrystal > 0;
  11439. },
  11440. },
  11441. 10016: {
  11442. description: 'Отправь подарки согильдийцам', // ++++++++++++++++
  11443. doItCall: () => [{ name: 'clanSendDailyGifts', args: {}, ident: 'clanSendDailyGifts' }],
  11444. isWeCanDo: () => true,
  11445. },
  11446. 10018: {
  11447. description: 'Используй зелье опыта', // ++++++++++++++++
  11448. doItCall: () => {
  11449. const expHero = this.getExpHero();
  11450. return [
  11451. {
  11452. name: 'consumableUseHeroXp',
  11453. args: {
  11454. heroId: expHero.heroId,
  11455. libId: expHero.libId,
  11456. amount: 1,
  11457. },
  11458. ident: 'consumableUseHeroXp',
  11459. },
  11460. ];
  11461. },
  11462. isWeCanDo: () => {
  11463. const expHero = this.getExpHero();
  11464. return expHero.heroId && expHero.libId;
  11465. },
  11466. },
  11467. 10019: {
  11468. description: 'Открой 1 сундук в Башне',
  11469. doItFunc: testTower,
  11470. isWeCanDo: () => false,
  11471. },
  11472. 10020: {
  11473. description: 'Открой 3 сундука в Запределье', // Готово
  11474. doItCall: () => {
  11475. return this.getOutlandChest();
  11476. },
  11477. isWeCanDo: () => {
  11478. const outlandChest = this.getOutlandChest();
  11479. return outlandChest.length > 0;
  11480. },
  11481. },
  11482. 10021: {
  11483. description: 'Собери 75 Титанита в Подземелье Гильдии',
  11484. isWeCanDo: () => false,
  11485. },
  11486. 10022: {
  11487. description: 'Собери 150 Титанита в Подземелье Гильдии',
  11488. doItFunc: testDungeon,
  11489. isWeCanDo: () => false,
  11490. },
  11491. 10023: {
  11492. description: 'Прокачай Дар Стихий на 1 уровень', // Готово
  11493. doItCall: () => {
  11494. const heroId = this.getHeroIdTitanGift();
  11495. return [
  11496. { name: 'heroTitanGiftLevelUp', args: { heroId }, ident: 'heroTitanGiftLevelUp' },
  11497. { name: 'heroTitanGiftDrop', args: { heroId }, ident: 'heroTitanGiftDrop' },
  11498. ];
  11499. },
  11500. isWeCanDo: () => {
  11501. const heroId = this.getHeroIdTitanGift();
  11502. return heroId;
  11503. },
  11504. },
  11505. 10024: {
  11506. description: 'Повысь уровень любого артефакта один раз', // Готово
  11507. doItCall: () => {
  11508. const upArtifact = this.getUpgradeArtifact();
  11509. return [
  11510. {
  11511. name: 'heroArtifactLevelUp',
  11512. args: {
  11513. heroId: upArtifact.heroId,
  11514. slotId: upArtifact.slotId,
  11515. },
  11516. ident: `heroArtifactLevelUp`,
  11517. },
  11518. ];
  11519. },
  11520. isWeCanDo: () => {
  11521. const upgradeArtifact = this.getUpgradeArtifact();
  11522. return upgradeArtifact.heroId;
  11523. },
  11524. },
  11525. 10025: {
  11526. description: 'Начни 1 Экспедицию',
  11527. doItFunc: checkExpedition,
  11528. isWeCanDo: () => false,
  11529. },
  11530. 10026: {
  11531. description: 'Начни 4 Экспедиции', // --------------
  11532. doItFunc: checkExpedition,
  11533. isWeCanDo: () => false,
  11534. },
  11535. 10027: {
  11536. description: 'Победи в 1 бою Турнира Стихий',
  11537. doItFunc: testTitanArena,
  11538. isWeCanDo: () => false,
  11539. },
  11540. 10028: {
  11541. description: 'Повысь уровень любого артефакта титанов', // Готово
  11542. doItCall: () => {
  11543. const upTitanArtifact = this.getUpgradeTitanArtifact();
  11544. return [
  11545. {
  11546. name: 'titanArtifactLevelUp',
  11547. args: {
  11548. titanId: upTitanArtifact.titanId,
  11549. slotId: upTitanArtifact.slotId,
  11550. },
  11551. ident: `titanArtifactLevelUp`,
  11552. },
  11553. ];
  11554. },
  11555. isWeCanDo: () => {
  11556. const upgradeTitanArtifact = this.getUpgradeTitanArtifact();
  11557. return upgradeTitanArtifact.titanId;
  11558. },
  11559. },
  11560. 10029: {
  11561. description: 'Открой сферу артефактов титанов', // ++++++++++++++++
  11562. doItCall: () => [{ name: 'titanArtifactChestOpen', args: { amount: 1, free: true }, ident: 'titanArtifactChestOpen' }],
  11563. isWeCanDo: () => {
  11564. return this.questInfo['inventoryGet']?.consumable[55] > 0;
  11565. },
  11566. },
  11567. 10030: {
  11568. description: 'Улучши облик любого героя 1 раз', // Готово
  11569. doItCall: () => {
  11570. const upSkin = this.getUpgradeSkin();
  11571. return [
  11572. {
  11573. name: 'heroSkinUpgrade',
  11574. args: {
  11575. heroId: upSkin.heroId,
  11576. skinId: upSkin.skinId,
  11577. },
  11578. ident: `heroSkinUpgrade`,
  11579. },
  11580. ];
  11581. },
  11582. isWeCanDo: () => {
  11583. const upgradeSkin = this.getUpgradeSkin();
  11584. return upgradeSkin.heroId;
  11585. },
  11586. },
  11587. 10031: {
  11588. description: 'Победи в 6 боях Турнира Стихий', // --------------
  11589. doItFunc: testTitanArena,
  11590. isWeCanDo: () => false,
  11591. },
  11592. 10043: {
  11593. description: 'Начни или присоеденись к Приключению', // --------------
  11594. isWeCanDo: () => false,
  11595. },
  11596. 10044: {
  11597. description: 'Воспользуйся призывом питомцев 1 раз', // ++++++++++++++++
  11598. doItCall: () => [{ name: 'pet_chestOpen', args: { amount: 1, paid: false }, ident: 'pet_chestOpen' }],
  11599. isWeCanDo: () => {
  11600. return this.questInfo['inventoryGet']?.consumable[90] > 0;
  11601. },
  11602. },
  11603. 10046: {
  11604. /**
  11605. * TODO: Watch Adventure
  11606. * TODO: Смотреть приключение
  11607. */
  11608. description: 'Открой 3 сундука в Приключениях',
  11609. isWeCanDo: () => false,
  11610. },
  11611. 10047: {
  11612. description: 'Набери 150 очков активности в Гильдии', // Готово
  11613. doItCall: () => {
  11614. const enchantRune = this.getEnchantRune();
  11615. return [
  11616. {
  11617. name: 'heroEnchantRune',
  11618. args: {
  11619. heroId: enchantRune.heroId,
  11620. tier: enchantRune.tier,
  11621. items: {
  11622. consumable: { [enchantRune.itemId]: 1 },
  11623. },
  11624. },
  11625. ident: `heroEnchantRune`,
  11626. },
  11627. ];
  11628. },
  11629. isWeCanDo: () => {
  11630. const userInfo = this.questInfo['userGetInfo'];
  11631. const enchantRune = this.getEnchantRune();
  11632. return enchantRune.heroId && userInfo.gold > 1e3;
  11633. },
  11634. },
  11635. };
  11636.  
  11637. constructor(resolve, reject, questInfo) {
  11638. this.resolve = resolve;
  11639. this.reject = reject;
  11640. }
  11641.  
  11642. init(questInfo) {
  11643. this.questInfo = questInfo;
  11644. this.isAuto = false;
  11645. }
  11646.  
  11647. async autoInit(isAuto) {
  11648. this.isAuto = isAuto || false;
  11649. const quests = {};
  11650. const calls = this.callsList.map((name) => ({
  11651. name,
  11652. args: {},
  11653. ident: name,
  11654. }));
  11655. const result = await Send(JSON.stringify({ calls })).then((e) => e.results);
  11656. for (const call of result) {
  11657. quests[call.ident] = call.result.response;
  11658. }
  11659. this.questInfo = quests;
  11660. }
  11661.  
  11662. async start() {
  11663. const weCanDo = [];
  11664. const selectedActions = getSaveVal('selectedActions', {});
  11665. for (let quest of this.questInfo['questGetAll']) {
  11666. if (quest.id in this.dataQuests && quest.state == 1) {
  11667. if (!selectedActions[quest.id]) {
  11668. selectedActions[quest.id] = {
  11669. checked: false,
  11670. };
  11671. }
  11672.  
  11673. const isWeCanDo = this.dataQuests[quest.id].isWeCanDo;
  11674. if (!isWeCanDo.call(this)) {
  11675. continue;
  11676. }
  11677.  
  11678. weCanDo.push({
  11679. name: quest.id,
  11680. label: I18N(`QUEST_${quest.id}`),
  11681. checked: selectedActions[quest.id].checked,
  11682. });
  11683. }
  11684. }
  11685.  
  11686. if (!weCanDo.length) {
  11687. this.end(I18N('NOTHING_TO_DO'));
  11688. return;
  11689. }
  11690.  
  11691. console.log(weCanDo);
  11692. let taskList = [];
  11693. if (this.isAuto) {
  11694. taskList = weCanDo;
  11695. } else {
  11696. const answer = await popup.confirm(
  11697. `${I18N('YOU_CAN_COMPLETE')}:`,
  11698. [
  11699. { msg: I18N('BTN_DO_IT'), result: true },
  11700. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  11701. ],
  11702. weCanDo
  11703. );
  11704. if (!answer) {
  11705. this.end('');
  11706. return;
  11707. }
  11708. taskList = popup.getCheckBoxes();
  11709. taskList.forEach((e) => {
  11710. selectedActions[e.name].checked = e.checked;
  11711. });
  11712. setSaveVal('selectedActions', selectedActions);
  11713. }
  11714.  
  11715. const calls = [];
  11716. let countChecked = 0;
  11717. for (const task of taskList) {
  11718. if (task.checked) {
  11719. countChecked++;
  11720. const quest = this.dataQuests[task.name];
  11721. console.log(quest.description);
  11722.  
  11723. if (quest.doItCall) {
  11724. const doItCall = quest.doItCall.call(this);
  11725. calls.push(...doItCall);
  11726. }
  11727. }
  11728. }
  11729.  
  11730. if (!countChecked) {
  11731. this.end(I18N('NOT_QUEST_COMPLETED'));
  11732. return;
  11733. }
  11734.  
  11735. const result = await Send(JSON.stringify({ calls }));
  11736. if (result.error) {
  11737. console.error(result.error, result.error.call);
  11738. }
  11739. this.end(`${I18N('COMPLETED_QUESTS')}: ${countChecked}`);
  11740. }
  11741.  
  11742. errorHandling(error) {
  11743. //console.error(error);
  11744. let errorInfo = error.toString() + '\n';
  11745. try {
  11746. const errorStack = error.stack.split('\n');
  11747. const endStack = errorStack.map((e) => e.split('@')[0]).indexOf('testDoYourBest');
  11748. errorInfo += errorStack.slice(0, endStack).join('\n');
  11749. } catch (e) {
  11750. errorInfo += error.stack;
  11751. }
  11752. copyText(errorInfo);
  11753. }
  11754.  
  11755. skillCost(lvl) {
  11756. return 573 * lvl ** 0.9 + lvl ** 2.379;
  11757. }
  11758.  
  11759. getUpgradeSkills() {
  11760. const heroes = Object.values(this.questInfo['heroGetAll']);
  11761. const upgradeSkills = [
  11762. { heroId: 0, slotId: 0, value: 130 },
  11763. { heroId: 0, slotId: 0, value: 130 },
  11764. { heroId: 0, slotId: 0, value: 130 },
  11765. ];
  11766. const skillLib = lib.getData('skill');
  11767. /**
  11768. * color - 1 (белый) открывает 1 навык
  11769. * color - 2 (зеленый) открывает 2 навык
  11770. * color - 4 (синий) открывает 3 навык
  11771. * color - 7 (фиолетовый) открывает 4 навык
  11772. */
  11773. const colors = [1, 2, 4, 7];
  11774. for (const hero of heroes) {
  11775. const level = hero.level;
  11776. const color = hero.color;
  11777. for (let skillId in hero.skills) {
  11778. const tier = skillLib[skillId].tier;
  11779. const sVal = hero.skills[skillId];
  11780. if (color < colors[tier] || tier < 1 || tier > 4) {
  11781. continue;
  11782. }
  11783. for (let upSkill of upgradeSkills) {
  11784. if (sVal < upSkill.value && sVal < level) {
  11785. upSkill.value = sVal;
  11786. upSkill.heroId = hero.id;
  11787. upSkill.skill = tier;
  11788. break;
  11789. }
  11790. }
  11791. }
  11792. }
  11793. return upgradeSkills;
  11794. }
  11795.  
  11796. getUpgradeArtifact() {
  11797. const heroes = Object.values(this.questInfo['heroGetAll']);
  11798. const inventory = this.questInfo['inventoryGet'];
  11799. const upArt = { heroId: 0, slotId: 0, level: 100 };
  11800.  
  11801. const heroLib = lib.getData('hero');
  11802. const artifactLib = lib.getData('artifact');
  11803.  
  11804. for (const hero of heroes) {
  11805. const heroInfo = heroLib[hero.id];
  11806. const level = hero.level;
  11807. if (level < 20) {
  11808. continue;
  11809. }
  11810.  
  11811. for (let slotId in hero.artifacts) {
  11812. const art = hero.artifacts[slotId];
  11813. /* Текущая звезданость арта */
  11814. const star = art.star;
  11815. if (!star) {
  11816. continue;
  11817. }
  11818. /* Текущий уровень арта */
  11819. const level = art.level;
  11820. if (level >= 100) {
  11821. continue;
  11822. }
  11823. /* Идентификатор арта в библиотеке */
  11824. const artifactId = heroInfo.artifacts[slotId];
  11825. const artInfo = artifactLib.id[artifactId];
  11826. const costNextLevel = artifactLib.type[artInfo.type].levels[level + 1].cost;
  11827.  
  11828. const costCurrency = Object.keys(costNextLevel).pop();
  11829. const costValues = Object.entries(costNextLevel[costCurrency]).pop();
  11830. const costId = costValues[0];
  11831. const costValue = +costValues[1];
  11832.  
  11833. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  11834. if (level < upArt.level && inventory[costCurrency][costId] >= costValue) {
  11835. upArt.level = level;
  11836. upArt.heroId = hero.id;
  11837. upArt.slotId = slotId;
  11838. upArt.costCurrency = costCurrency;
  11839. upArt.costId = costId;
  11840. upArt.costValue = costValue;
  11841. }
  11842. }
  11843. }
  11844. return upArt;
  11845. }
  11846.  
  11847. getUpgradeSkin() {
  11848. const heroes = Object.values(this.questInfo['heroGetAll']);
  11849. const inventory = this.questInfo['inventoryGet'];
  11850. const upSkin = { heroId: 0, skinId: 0, level: 60, cost: 1500 };
  11851.  
  11852. const skinLib = lib.getData('skin');
  11853.  
  11854. for (const hero of heroes) {
  11855. const level = hero.level;
  11856. if (level < 20) {
  11857. continue;
  11858. }
  11859.  
  11860. for (let skinId in hero.skins) {
  11861. /* Текущий уровень скина */
  11862. const level = hero.skins[skinId];
  11863. if (level >= 60) {
  11864. continue;
  11865. }
  11866. /* Идентификатор скина в библиотеке */
  11867. const skinInfo = skinLib[skinId];
  11868. if (!skinInfo.statData.levels?.[level + 1]) {
  11869. continue;
  11870. }
  11871. const costNextLevel = skinInfo.statData.levels[level + 1].cost;
  11872.  
  11873. const costCurrency = Object.keys(costNextLevel).pop();
  11874. const costCurrencyId = Object.keys(costNextLevel[costCurrency]).pop();
  11875. const costValue = +costNextLevel[costCurrency][costCurrencyId];
  11876.  
  11877. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  11878. if (level < upSkin.level && costValue < upSkin.cost && inventory[costCurrency][costCurrencyId] >= costValue) {
  11879. upSkin.cost = costValue;
  11880. upSkin.level = level;
  11881. upSkin.heroId = hero.id;
  11882. upSkin.skinId = skinId;
  11883. upSkin.costCurrency = costCurrency;
  11884. upSkin.costCurrencyId = costCurrencyId;
  11885. }
  11886. }
  11887. }
  11888. return upSkin;
  11889. }
  11890.  
  11891. getUpgradeTitanArtifact() {
  11892. const titans = Object.values(this.questInfo['titanGetAll']);
  11893. const inventory = this.questInfo['inventoryGet'];
  11894. const userInfo = this.questInfo['userGetInfo'];
  11895. const upArt = { titanId: 0, slotId: 0, level: 120 };
  11896.  
  11897. const titanLib = lib.getData('titan');
  11898. const artTitanLib = lib.getData('titanArtifact');
  11899.  
  11900. for (const titan of titans) {
  11901. const titanInfo = titanLib[titan.id];
  11902. // const level = titan.level
  11903. // if (level < 20) {
  11904. // continue;
  11905. // }
  11906.  
  11907. for (let slotId in titan.artifacts) {
  11908. const art = titan.artifacts[slotId];
  11909. /* Текущая звезданость арта */
  11910. const star = art.star;
  11911. if (!star) {
  11912. continue;
  11913. }
  11914. /* Текущий уровень арта */
  11915. const level = art.level;
  11916. if (level >= 120) {
  11917. continue;
  11918. }
  11919. /* Идентификатор арта в библиотеке */
  11920. const artifactId = titanInfo.artifacts[slotId];
  11921. const artInfo = artTitanLib.id[artifactId];
  11922. const costNextLevel = artTitanLib.type[artInfo.type].levels[level + 1].cost;
  11923.  
  11924. const costCurrency = Object.keys(costNextLevel).pop();
  11925. let costValue = 0;
  11926. let currentValue = 0;
  11927. if (costCurrency == 'gold') {
  11928. costValue = costNextLevel[costCurrency];
  11929. currentValue = userInfo.gold;
  11930. } else {
  11931. const costValues = Object.entries(costNextLevel[costCurrency]).pop();
  11932. const costId = costValues[0];
  11933. costValue = +costValues[1];
  11934. currentValue = inventory[costCurrency][costId];
  11935. }
  11936.  
  11937. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  11938. if (level < upArt.level && currentValue >= costValue) {
  11939. upArt.level = level;
  11940. upArt.titanId = titan.id;
  11941. upArt.slotId = slotId;
  11942. break;
  11943. }
  11944. }
  11945. }
  11946. return upArt;
  11947. }
  11948.  
  11949. getEnchantRune() {
  11950. const heroes = Object.values(this.questInfo['heroGetAll']);
  11951. const inventory = this.questInfo['inventoryGet'];
  11952. const enchRune = { heroId: 0, tier: 0, exp: 43750, itemId: 0 };
  11953. for (let i = 1; i <= 4; i++) {
  11954. if (inventory.consumable[i] > 0) {
  11955. enchRune.itemId = i;
  11956. break;
  11957. }
  11958. return enchRune;
  11959. }
  11960.  
  11961. const runeLib = lib.getData('rune');
  11962. const runeLvls = Object.values(runeLib.level);
  11963. /**
  11964. * color - 4 (синий) открывает 1 и 2 символ
  11965. * color - 7 (фиолетовый) открывает 3 символ
  11966. * color - 8 (фиолетовый +1) открывает 4 символ
  11967. * color - 9 (фиолетовый +2) открывает 5 символ
  11968. */
  11969. // TODO: кажется надо учесть уровень команды
  11970. const colors = [4, 4, 7, 8, 9];
  11971. for (const hero of heroes) {
  11972. const color = hero.color;
  11973.  
  11974. for (let runeTier in hero.runes) {
  11975. /* Проверка на доступность руны */
  11976. if (color < colors[runeTier]) {
  11977. continue;
  11978. }
  11979. /* Текущий опыт руны */
  11980. const exp = hero.runes[runeTier];
  11981. if (exp >= 43750) {
  11982. continue;
  11983. }
  11984.  
  11985. let level = 0;
  11986. if (exp) {
  11987. for (let lvl of runeLvls) {
  11988. if (exp >= lvl.enchantValue) {
  11989. level = lvl.level;
  11990. } else {
  11991. break;
  11992. }
  11993. }
  11994. }
  11995. /** Уровень героя необходимый для уровня руны */
  11996. const heroLevel = runeLib.level[level].heroLevel;
  11997. if (hero.level < heroLevel) {
  11998. continue;
  11999. }
  12000.  
  12001. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  12002. if (exp < enchRune.exp) {
  12003. enchRune.exp = exp;
  12004. enchRune.heroId = hero.id;
  12005. enchRune.tier = runeTier;
  12006. break;
  12007. }
  12008. }
  12009. }
  12010. return enchRune;
  12011. }
  12012.  
  12013. getOutlandChest() {
  12014. const bosses = this.questInfo['bossGetAll'];
  12015.  
  12016. const calls = [];
  12017.  
  12018. for (let boss of bosses) {
  12019. if (boss.mayRaid) {
  12020. calls.push({
  12021. name: 'bossRaid',
  12022. args: {
  12023. bossId: boss.id,
  12024. },
  12025. ident: 'bossRaid_' + boss.id,
  12026. });
  12027. calls.push({
  12028. name: 'bossOpenChest',
  12029. args: {
  12030. bossId: boss.id,
  12031. amount: 1,
  12032. starmoney: 0,
  12033. },
  12034. ident: 'bossOpenChest_' + boss.id,
  12035. });
  12036. } else if (boss.chestId == 1) {
  12037. calls.push({
  12038. name: 'bossOpenChest',
  12039. args: {
  12040. bossId: boss.id,
  12041. amount: 1,
  12042. starmoney: 0,
  12043. },
  12044. ident: 'bossOpenChest_' + boss.id,
  12045. });
  12046. }
  12047. }
  12048.  
  12049. return calls;
  12050. }
  12051.  
  12052. getExpHero() {
  12053. const heroes = Object.values(this.questInfo['heroGetAll']);
  12054. const inventory = this.questInfo['inventoryGet'];
  12055. const expHero = { heroId: 0, exp: 3625195, libId: 0 };
  12056. /** зелья опыта (consumable 9, 10, 11, 12) */
  12057. for (let i = 9; i <= 12; i++) {
  12058. if (inventory.consumable[i]) {
  12059. expHero.libId = i;
  12060. break;
  12061. }
  12062. }
  12063.  
  12064. for (const hero of heroes) {
  12065. const exp = hero.xp;
  12066. if (exp < expHero.exp) {
  12067. expHero.heroId = hero.id;
  12068. }
  12069. }
  12070. return expHero;
  12071. }
  12072.  
  12073. getHeroIdTitanGift() {
  12074. const heroes = Object.values(this.questInfo['heroGetAll']);
  12075. const inventory = this.questInfo['inventoryGet'];
  12076. const user = this.questInfo['userGetInfo'];
  12077. const titanGiftLib = lib.getData('titanGift');
  12078. /** Искры */
  12079. const titanGift = inventory.consumable[24];
  12080. let heroId = 0;
  12081. let minLevel = 30;
  12082.  
  12083. if (titanGift < 250 || user.gold < 7000) {
  12084. return 0;
  12085. }
  12086.  
  12087. for (const hero of heroes) {
  12088. if (hero.titanGiftLevel >= 30) {
  12089. continue;
  12090. }
  12091.  
  12092. if (!hero.titanGiftLevel) {
  12093. return hero.id;
  12094. }
  12095.  
  12096. const cost = titanGiftLib[hero.titanGiftLevel].cost;
  12097. if (minLevel > hero.titanGiftLevel && titanGift >= cost.consumable[24] && user.gold >= cost.gold) {
  12098. minLevel = hero.titanGiftLevel;
  12099. heroId = hero.id;
  12100. }
  12101. }
  12102.  
  12103. return heroId;
  12104. }
  12105.  
  12106. getHeroicMissionId() {
  12107. // Получаем доступные миссии с 3 звездами
  12108. const availableMissionsToRaid = Object.values(this.questInfo.missionGetAll)
  12109. .filter((mission) => mission.stars === 3)
  12110. .map((mission) => mission.id);
  12111.  
  12112. // Получаем героев для улучшения, у которых меньше 6 звезд
  12113. const heroesToUpgrade = Object.values(this.questInfo.heroGetAll)
  12114. .filter((hero) => hero.star < 6)
  12115. .sort((a, b) => b.power - a.power)
  12116. .map((hero) => hero.id);
  12117.  
  12118. // Получаем героические миссии, которые доступны для рейдов
  12119. const heroicMissions = Object.values(lib.data.mission).filter((mission) => mission.isHeroic && availableMissionsToRaid.includes(mission.id));
  12120.  
  12121. // Собираем дропы из героических миссий
  12122. const drops = heroicMissions.map((mission) => {
  12123. const lastWave = mission.normalMode.waves[mission.normalMode.waves.length - 1];
  12124. const allRewards = lastWave.enemies[lastWave.enemies.length - 1]
  12125. .drop.map((drop) => drop.reward);
  12126.  
  12127. const heroId = +Object.keys(allRewards.find((reward) => reward.fragmentHero).fragmentHero).pop();
  12128.  
  12129. return { id: mission.id, heroId };
  12130. });
  12131.  
  12132. // Определяем, какие дропы подходят для героев, которых нужно улучшить
  12133. const heroDrops = heroesToUpgrade.map((heroId) => drops.find((drop) => drop.heroId == heroId)).filter((drop) => drop);
  12134. const firstMission = heroDrops[0];
  12135. // Выбираем миссию для рейда
  12136. const selectedMissionId = firstMission ? firstMission.id : 1;
  12137.  
  12138. const stamina = this.questInfo.userGetInfo.refillable.find((x) => x.id == 1).amount;
  12139. const costMissions = 3 * lib.data.mission[selectedMissionId].normalMode.teamExp;
  12140. if (stamina < costMissions) {
  12141. console.log('Энергии не достаточно');
  12142. return 0;
  12143. }
  12144. return selectedMissionId;
  12145. }
  12146.  
  12147. end(status) {
  12148. setProgress(status, true);
  12149. this.resolve();
  12150. }
  12151. }
  12152.  
  12153. this.questRun = dailyQuests;
  12154. this.HWHClasses.dailyQuests = dailyQuests;
  12155.  
  12156. function testDoYourBest() {
  12157. const { doYourBest } = HWHClasses;
  12158. return new Promise((resolve, reject) => {
  12159. const doIt = new doYourBest(resolve, reject);
  12160. doIt.start();
  12161. });
  12162. }
  12163.  
  12164. /**
  12165. * Do everything button
  12166. *
  12167. * Кнопка сделать все
  12168. */
  12169. class doYourBest {
  12170.  
  12171. funcList = [
  12172. {
  12173. name: 'getOutland',
  12174. label: I18N('ASSEMBLE_OUTLAND'),
  12175. checked: false
  12176. },
  12177. {
  12178. name: 'testTower',
  12179. label: I18N('PASS_THE_TOWER'),
  12180. checked: false
  12181. },
  12182. {
  12183. name: 'checkExpedition',
  12184. label: I18N('CHECK_EXPEDITIONS'),
  12185. checked: false
  12186. },
  12187. {
  12188. name: 'testTitanArena',
  12189. label: I18N('COMPLETE_TOE'),
  12190. checked: false
  12191. },
  12192. {
  12193. name: 'mailGetAll',
  12194. label: I18N('COLLECT_MAIL'),
  12195. checked: false
  12196. },
  12197. {
  12198. name: 'collectAllStuff',
  12199. label: I18N('COLLECT_MISC'),
  12200. title: I18N('COLLECT_MISC_TITLE'),
  12201. checked: false
  12202. },
  12203. {
  12204. name: 'getDailyBonus',
  12205. label: I18N('DAILY_BONUS'),
  12206. checked: false
  12207. },
  12208. {
  12209. name: 'dailyQuests',
  12210. label: I18N('DO_DAILY_QUESTS'),
  12211. checked: false
  12212. },
  12213. {
  12214. name: 'rollAscension',
  12215. label: I18N('SEER_TITLE'),
  12216. checked: false
  12217. },
  12218. {
  12219. name: 'questAllFarm',
  12220. label: I18N('COLLECT_QUEST_REWARDS'),
  12221. checked: false
  12222. },
  12223. {
  12224. name: 'testDungeon',
  12225. label: I18N('COMPLETE_DUNGEON'),
  12226. checked: false
  12227. },
  12228. {
  12229. name: 'synchronization',
  12230. label: I18N('MAKE_A_SYNC'),
  12231. checked: false
  12232. },
  12233. {
  12234. name: 'reloadGame',
  12235. label: I18N('RELOAD_GAME'),
  12236. checked: false
  12237. },
  12238. ];
  12239.  
  12240. functions = {
  12241. getOutland,
  12242. testTower,
  12243. checkExpedition,
  12244. testTitanArena,
  12245. mailGetAll,
  12246. collectAllStuff: async () => {
  12247. await offerFarmAllReward();
  12248. 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"}]}');
  12249. },
  12250. dailyQuests: async function () {
  12251. const quests = new dailyQuests(() => { }, () => { });
  12252. await quests.autoInit(true);
  12253. await quests.start();
  12254. },
  12255. rollAscension,
  12256. getDailyBonus,
  12257. questAllFarm,
  12258. testDungeon,
  12259. synchronization: async () => {
  12260. cheats.refreshGame();
  12261. },
  12262. reloadGame: async () => {
  12263. location.reload();
  12264. },
  12265. }
  12266.  
  12267. constructor(resolve, reject, questInfo) {
  12268. this.resolve = resolve;
  12269. this.reject = reject;
  12270. this.questInfo = questInfo
  12271. }
  12272.  
  12273. async start() {
  12274. const selectedDoIt = getSaveVal('selectedDoIt', {});
  12275.  
  12276. this.funcList.forEach(task => {
  12277. if (!selectedDoIt[task.name]) {
  12278. selectedDoIt[task.name] = {
  12279. checked: task.checked
  12280. }
  12281. } else {
  12282. task.checked = selectedDoIt[task.name].checked
  12283. }
  12284. });
  12285.  
  12286. const answer = await popup.confirm(I18N('RUN_FUNCTION'), [
  12287. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  12288. { msg: I18N('BTN_GO'), result: true },
  12289. ], this.funcList);
  12290.  
  12291. if (!answer) {
  12292. this.end('');
  12293. return;
  12294. }
  12295.  
  12296. const taskList = popup.getCheckBoxes();
  12297. taskList.forEach(task => {
  12298. selectedDoIt[task.name].checked = task.checked;
  12299. });
  12300. setSaveVal('selectedDoIt', selectedDoIt);
  12301. for (const task of popup.getCheckBoxes()) {
  12302. if (task.checked) {
  12303. try {
  12304. setProgress(`${task.label} <br>${I18N('PERFORMED')}!`);
  12305. await this.functions[task.name]();
  12306. setProgress(`${task.label} <br>${I18N('DONE')}!`);
  12307. } catch (error) {
  12308. if (await popup.confirm(`${I18N('ERRORS_OCCURRES')}:<br> ${task.label} <br>${I18N('COPY_ERROR')}?`, [
  12309. { msg: I18N('BTN_NO'), result: false },
  12310. { msg: I18N('BTN_YES'), result: true },
  12311. ])) {
  12312. this.errorHandling(error);
  12313. }
  12314. }
  12315. }
  12316. }
  12317. setTimeout((msg) => {
  12318. this.end(msg);
  12319. }, 2000, I18N('ALL_TASK_COMPLETED'));
  12320. return;
  12321. }
  12322.  
  12323. errorHandling(error) {
  12324. //console.error(error);
  12325. let errorInfo = error.toString() + '\n';
  12326. try {
  12327. const errorStack = error.stack.split('\n');
  12328. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testDoYourBest");
  12329. errorInfo += errorStack.slice(0, endStack).join('\n');
  12330. } catch (e) {
  12331. errorInfo += error.stack;
  12332. }
  12333. copyText(errorInfo);
  12334. }
  12335.  
  12336. end(status) {
  12337. setProgress(status, true);
  12338. this.resolve();
  12339. }
  12340. }
  12341.  
  12342. this.HWHClasses.doYourBest = doYourBest;
  12343.  
  12344. /**
  12345. * Passing the adventure along the specified route
  12346. *
  12347. * Прохождение приключения по указанному маршруту
  12348. */
  12349. function testAdventure(type) {
  12350. const { executeAdventure } = HWHClasses;
  12351. return new Promise((resolve, reject) => {
  12352. const bossBattle = new executeAdventure(resolve, reject);
  12353. bossBattle.start(type);
  12354. });
  12355. }
  12356.  
  12357. /**
  12358. * Passing the adventure along the specified route
  12359. *
  12360. * Прохождение приключения по указанному маршруту
  12361. */
  12362. class executeAdventure {
  12363.  
  12364. type = 'default';
  12365.  
  12366. actions = {
  12367. default: {
  12368. getInfo: "adventure_getInfo",
  12369. startBattle: 'adventure_turnStartBattle',
  12370. endBattle: 'adventure_endBattle',
  12371. collectBuff: 'adventure_turnCollectBuff'
  12372. },
  12373. solo: {
  12374. getInfo: "adventureSolo_getInfo",
  12375. startBattle: 'adventureSolo_turnStartBattle',
  12376. endBattle: 'adventureSolo_endBattle',
  12377. collectBuff: 'adventureSolo_turnCollectBuff'
  12378. }
  12379. }
  12380.  
  12381. terminatеReason = I18N('UNKNOWN');
  12382. callAdventureInfo = {
  12383. name: "adventure_getInfo",
  12384. args: {},
  12385. ident: "adventure_getInfo"
  12386. }
  12387. callTeamGetAll = {
  12388. name: "teamGetAll",
  12389. args: {},
  12390. ident: "teamGetAll"
  12391. }
  12392. callTeamGetFavor = {
  12393. name: "teamGetFavor",
  12394. args: {},
  12395. ident: "teamGetFavor"
  12396. }
  12397. callStartBattle = {
  12398. name: "adventure_turnStartBattle",
  12399. args: {},
  12400. ident: "body"
  12401. }
  12402. callEndBattle = {
  12403. name: "adventure_endBattle",
  12404. args: {
  12405. result: {},
  12406. progress: {},
  12407. },
  12408. ident: "body"
  12409. }
  12410. callCollectBuff = {
  12411. name: "adventure_turnCollectBuff",
  12412. args: {},
  12413. ident: "body"
  12414. }
  12415.  
  12416. constructor(resolve, reject) {
  12417. this.resolve = resolve;
  12418. this.reject = reject;
  12419. }
  12420.  
  12421. async start(type) {
  12422. this.type = type || this.type;
  12423. this.callAdventureInfo.name = this.actions[this.type].getInfo;
  12424. const data = await Send(JSON.stringify({
  12425. calls: [
  12426. this.callAdventureInfo,
  12427. this.callTeamGetAll,
  12428. this.callTeamGetFavor
  12429. ]
  12430. }));
  12431. return this.checkAdventureInfo(data.results);
  12432. }
  12433.  
  12434. async getPath() {
  12435. const oldVal = getSaveVal('adventurePath', '');
  12436. const keyPath = `adventurePath:${this.mapIdent}`;
  12437. const answer = await popup.confirm(I18N('ENTER_THE_PATH'), [
  12438. {
  12439. msg: I18N('START_ADVENTURE'),
  12440. placeholder: '1,2,3,4,5,6',
  12441. isInput: true,
  12442. default: getSaveVal(keyPath, oldVal)
  12443. },
  12444. {
  12445. msg: I18N('BTN_CANCEL'),
  12446. result: false,
  12447. isCancel: true
  12448. },
  12449. ]);
  12450. if (!answer) {
  12451. this.terminatеReason = I18N('BTN_CANCELED');
  12452. return false;
  12453. }
  12454.  
  12455. let path = answer.split(',');
  12456. if (path.length < 2) {
  12457. path = answer.split('-');
  12458. }
  12459. if (path.length < 2) {
  12460. this.terminatеReason = I18N('MUST_TWO_POINTS');
  12461. return false;
  12462. }
  12463.  
  12464. for (let p in path) {
  12465. path[p] = +path[p].trim()
  12466. if (Number.isNaN(path[p])) {
  12467. this.terminatеReason = I18N('MUST_ONLY_NUMBERS');
  12468. return false;
  12469. }
  12470. }
  12471.  
  12472. if (!this.checkPath(path)) {
  12473. return false;
  12474. }
  12475. setSaveVal(keyPath, answer);
  12476. return path;
  12477. }
  12478.  
  12479. checkPath(path) {
  12480. for (let i = 0; i < path.length - 1; i++) {
  12481. const currentPoint = path[i];
  12482. const nextPoint = path[i + 1];
  12483.  
  12484. const isValidPath = this.paths.some(p =>
  12485. (p.from_id === currentPoint && p.to_id === nextPoint) ||
  12486. (p.from_id === nextPoint && p.to_id === currentPoint)
  12487. );
  12488.  
  12489. if (!isValidPath) {
  12490. this.terminatеReason = I18N('INCORRECT_WAY', {
  12491. from: currentPoint,
  12492. to: nextPoint,
  12493. });
  12494. return false;
  12495. }
  12496. }
  12497.  
  12498. return true;
  12499. }
  12500.  
  12501. async checkAdventureInfo(data) {
  12502. this.advInfo = data[0].result.response;
  12503. if (!this.advInfo) {
  12504. this.terminatеReason = I18N('NOT_ON_AN_ADVENTURE') ;
  12505. return this.end();
  12506. }
  12507. const heroesTeam = data[1].result.response.adventure_hero;
  12508. const favor = data[2]?.result.response.adventure_hero;
  12509. const heroes = heroesTeam.slice(0, 5);
  12510. const pet = heroesTeam[5];
  12511. this.args = {
  12512. pet,
  12513. heroes,
  12514. favor,
  12515. path: [],
  12516. broadcast: false
  12517. }
  12518. const advUserInfo = this.advInfo.users[userInfo.id];
  12519. this.turnsLeft = advUserInfo.turnsLeft;
  12520. this.currentNode = advUserInfo.currentNode;
  12521. this.nodes = this.advInfo.nodes;
  12522. this.paths = this.advInfo.paths;
  12523. this.mapIdent = this.advInfo.mapIdent;
  12524.  
  12525. this.path = await this.getPath();
  12526. if (!this.path) {
  12527. return this.end();
  12528. }
  12529.  
  12530. if (this.currentNode == 1 && this.path[0] != 1) {
  12531. this.path.unshift(1);
  12532. }
  12533.  
  12534. return this.loop();
  12535. }
  12536.  
  12537. async loop() {
  12538. const position = this.path.indexOf(+this.currentNode);
  12539. if (!(~position)) {
  12540. this.terminatеReason = I18N('YOU_IN_NOT_ON_THE_WAY');
  12541. return this.end();
  12542. }
  12543. this.path = this.path.slice(position);
  12544. if ((this.path.length - 1) > this.turnsLeft &&
  12545. await popup.confirm(I18N('ATTEMPTS_NOT_ENOUGH'), [
  12546. { msg: I18N('YES_CONTINUE'), result: false },
  12547. { msg: I18N('BTN_NO'), result: true },
  12548. ])) {
  12549. this.terminatеReason = I18N('NOT_ENOUGH_AP');
  12550. return this.end();
  12551. }
  12552. const toPath = [];
  12553. for (const nodeId of this.path) {
  12554. if (!this.turnsLeft) {
  12555. this.terminatеReason = I18N('ATTEMPTS_ARE_OVER');
  12556. return this.end();
  12557. }
  12558. toPath.push(nodeId);
  12559. console.log(toPath);
  12560. if (toPath.length > 1) {
  12561. setProgress(toPath.join(' > ') + ` ${I18N('MOVES')}: ` + this.turnsLeft);
  12562. }
  12563. if (nodeId == this.currentNode) {
  12564. continue;
  12565. }
  12566.  
  12567. const nodeInfo = this.getNodeInfo(nodeId);
  12568. if (nodeInfo.type == 'TYPE_COMBAT') {
  12569. if (nodeInfo.state == 'empty') {
  12570. this.turnsLeft--;
  12571. continue;
  12572. }
  12573.  
  12574. /**
  12575. * Disable regular battle cancellation
  12576. *
  12577. * Отключаем штатную отменую боя
  12578. */
  12579. setIsCancalBattle(false);
  12580. if (await this.battle(toPath)) {
  12581. this.turnsLeft--;
  12582. toPath.splice(0, toPath.indexOf(nodeId));
  12583. nodeInfo.state = 'empty';
  12584. setIsCancalBattle(true);
  12585. continue;
  12586. }
  12587. setIsCancalBattle(true);
  12588. return this.end()
  12589. }
  12590.  
  12591. if (nodeInfo.type == 'TYPE_PLAYERBUFF') {
  12592. const buff = this.checkBuff(nodeInfo);
  12593. if (buff == null) {
  12594. continue;
  12595. }
  12596.  
  12597. if (await this.collectBuff(buff, toPath)) {
  12598. this.turnsLeft--;
  12599. toPath.splice(0, toPath.indexOf(nodeId));
  12600. continue;
  12601. }
  12602. this.terminatеReason = I18N('BUFF_GET_ERROR');
  12603. return this.end();
  12604. }
  12605. }
  12606. this.terminatеReason = I18N('SUCCESS');
  12607. return this.end();
  12608. }
  12609.  
  12610. /**
  12611. * Carrying out a fight
  12612. *
  12613. * Проведение боя
  12614. */
  12615. async battle(path, preCalc = true) {
  12616. const data = await this.startBattle(path);
  12617. try {
  12618. const battle = data.results[0].result.response.battle;
  12619. let result = await Calc(battle);
  12620.  
  12621. if (!result.result.win && isChecked('tryFixIt_v2')) {
  12622. const cloneBattle = structuredClone(battle);
  12623. const bFix = new WinFixBattle(cloneBattle);
  12624. const endTime = Date.now() + 3e4; // 30 sec
  12625. const fixResult = await bFix.start(endTime, Infinity);
  12626. console.log(fixResult);
  12627. if (fixResult.value > 0) {
  12628. result = fixResult;
  12629. }
  12630. }
  12631.  
  12632. if (result.result.win) {
  12633. const info = await this.endBattle(result);
  12634. if (info.results[0].result.response?.error) {
  12635. this.terminatеReason = I18N('BATTLE_END_ERROR');
  12636. return false;
  12637. }
  12638. } else {
  12639. await this.cancelBattle(result);
  12640.  
  12641. if (preCalc && await this.preCalcBattle(battle)) {
  12642. path = path.slice(-2);
  12643. for (let i = 1; i <= getInput('countAutoBattle'); i++) {
  12644. setProgress(`${I18N('AUTOBOT')}: ${i}/${getInput('countAutoBattle')}`);
  12645. const result = await this.battle(path, false);
  12646. if (result) {
  12647. setProgress(I18N('VICTORY'));
  12648. return true;
  12649. }
  12650. }
  12651. this.terminatеReason = I18N('FAILED_TO_WIN_AUTO');
  12652. return false;
  12653. }
  12654. return false;
  12655. }
  12656. } catch (error) {
  12657. console.error(error);
  12658. if (await popup.confirm(I18N('ERROR_OF_THE_BATTLE_COPY'), [
  12659. { msg: I18N('BTN_NO'), result: false },
  12660. { msg: I18N('BTN_YES'), result: true },
  12661. ])) {
  12662. this.errorHandling(error, data);
  12663. }
  12664. this.terminatеReason = I18N('ERROR_DURING_THE_BATTLE');
  12665. return false;
  12666. }
  12667. return true;
  12668. }
  12669.  
  12670. /**
  12671. * Recalculate battles
  12672. *
  12673. * Прерасчтет битвы
  12674. */
  12675. async preCalcBattle(battle) {
  12676. const countTestBattle = getInput('countTestBattle');
  12677. for (let i = 0; i < countTestBattle; i++) {
  12678. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  12679. const result = await Calc(battle);
  12680. if (result.result.win) {
  12681. console.log(i, countTestBattle);
  12682. return true;
  12683. }
  12684. }
  12685. this.terminatеReason = I18N('NO_CHANCE_WIN') + countTestBattle;
  12686. return false;
  12687. }
  12688.  
  12689. /**
  12690. * Starts a fight
  12691. *
  12692. * Начинает бой
  12693. */
  12694. startBattle(path) {
  12695. this.args.path = path;
  12696. this.callStartBattle.name = this.actions[this.type].startBattle;
  12697. this.callStartBattle.args = this.args
  12698. const calls = [this.callStartBattle];
  12699. return Send(JSON.stringify({ calls }));
  12700. }
  12701.  
  12702. cancelBattle(battle) {
  12703. const fixBattle = function (heroes) {
  12704. for (const ids in heroes) {
  12705. const hero = heroes[ids];
  12706. hero.energy = random(1, 999);
  12707. if (hero.hp > 0) {
  12708. hero.hp = random(1, hero.hp);
  12709. }
  12710. }
  12711. }
  12712. fixBattle(battle.progress[0].attackers.heroes);
  12713. fixBattle(battle.progress[0].defenders.heroes);
  12714. return this.endBattle(battle);
  12715. }
  12716.  
  12717. /**
  12718. * Ends the fight
  12719. *
  12720. * Заканчивает бой
  12721. */
  12722. endBattle(battle) {
  12723. this.callEndBattle.name = this.actions[this.type].endBattle;
  12724. this.callEndBattle.args.result = battle.result
  12725. this.callEndBattle.args.progress = battle.progress
  12726. const calls = [this.callEndBattle];
  12727. return Send(JSON.stringify({ calls }));
  12728. }
  12729.  
  12730. /**
  12731. * Checks if you can get a buff
  12732. *
  12733. * Проверяет можно ли получить баф
  12734. */
  12735. checkBuff(nodeInfo) {
  12736. let id = null;
  12737. let value = 0;
  12738. for (const buffId in nodeInfo.buffs) {
  12739. const buff = nodeInfo.buffs[buffId];
  12740. if (buff.owner == null && buff.value > value) {
  12741. id = buffId;
  12742. value = buff.value;
  12743. }
  12744. }
  12745. nodeInfo.buffs[id].owner = 'Я';
  12746. return id;
  12747. }
  12748.  
  12749. /**
  12750. * Collects a buff
  12751. *
  12752. * Собирает баф
  12753. */
  12754. async collectBuff(buff, path) {
  12755. this.callCollectBuff.name = this.actions[this.type].collectBuff;
  12756. this.callCollectBuff.args = { buff, path };
  12757. const calls = [this.callCollectBuff];
  12758. return Send(JSON.stringify({ calls }));
  12759. }
  12760.  
  12761. getNodeInfo(nodeId) {
  12762. return this.nodes.find(node => node.id == nodeId);
  12763. }
  12764.  
  12765. errorHandling(error, data) {
  12766. //console.error(error);
  12767. let errorInfo = error.toString() + '\n';
  12768. try {
  12769. const errorStack = error.stack.split('\n');
  12770. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testAdventure");
  12771. errorInfo += errorStack.slice(0, endStack).join('\n');
  12772. } catch (e) {
  12773. errorInfo += error.stack;
  12774. }
  12775. if (data) {
  12776. errorInfo += '\nData: ' + JSON.stringify(data);
  12777. }
  12778. copyText(errorInfo);
  12779. }
  12780.  
  12781. end() {
  12782. setIsCancalBattle(true);
  12783. setProgress(this.terminatеReason, true);
  12784. console.log(this.terminatеReason);
  12785. this.resolve();
  12786. }
  12787. }
  12788.  
  12789. this.HWHClasses.executeAdventure = executeAdventure;
  12790.  
  12791. /**
  12792. * Passage of brawls
  12793. *
  12794. * Прохождение потасовок
  12795. */
  12796. function testBrawls(isAuto) {
  12797. const { executeBrawls } = HWHClasses;
  12798. return new Promise((resolve, reject) => {
  12799. const brawls = new executeBrawls(resolve, reject);
  12800. brawls.start(brawlsPack, isAuto);
  12801. });
  12802. }
  12803. /**
  12804. * Passage of brawls
  12805. *
  12806. * Прохождение потасовок
  12807. */
  12808. class executeBrawls {
  12809. callBrawlQuestGetInfo = {
  12810. name: "brawl_questGetInfo",
  12811. args: {},
  12812. ident: "brawl_questGetInfo"
  12813. }
  12814. callBrawlFindEnemies = {
  12815. name: "brawl_findEnemies",
  12816. args: {},
  12817. ident: "brawl_findEnemies"
  12818. }
  12819. callBrawlQuestFarm = {
  12820. name: "brawl_questFarm",
  12821. args: {},
  12822. ident: "brawl_questFarm"
  12823. }
  12824. callUserGetInfo = {
  12825. name: "userGetInfo",
  12826. args: {},
  12827. ident: "userGetInfo"
  12828. }
  12829. callTeamGetMaxUpgrade = {
  12830. name: "teamGetMaxUpgrade",
  12831. args: {},
  12832. ident: "teamGetMaxUpgrade"
  12833. }
  12834. callBrawlGetInfo = {
  12835. name: "brawl_getInfo",
  12836. args: {},
  12837. ident: "brawl_getInfo"
  12838. }
  12839.  
  12840. stats = {
  12841. win: 0,
  12842. loss: 0,
  12843. count: 0,
  12844. }
  12845.  
  12846. stage = {
  12847. '3': 1,
  12848. '7': 2,
  12849. '12': 3,
  12850. }
  12851.  
  12852. attempts = 0;
  12853.  
  12854. constructor(resolve, reject) {
  12855. this.resolve = resolve;
  12856. this.reject = reject;
  12857.  
  12858. const allHeroIds = Object.keys(lib.getData('hero'));
  12859. this.callTeamGetMaxUpgrade.args.units = {
  12860. hero: allHeroIds.filter((id) => +id < 1000),
  12861. titan: allHeroIds.filter((id) => +id >= 4000 && +id < 4100),
  12862. pet: allHeroIds.filter((id) => +id >= 6000 && +id < 6100),
  12863. };
  12864. }
  12865.  
  12866. async start(args, isAuto) {
  12867. this.isAuto = isAuto;
  12868. this.args = args;
  12869. setIsCancalBattle(false);
  12870. this.brawlInfo = await this.getBrawlInfo();
  12871. this.attempts = this.brawlInfo.attempts;
  12872.  
  12873. if (!this.attempts && !this.info.boughtEndlessLivesToday) {
  12874. this.end(I18N('DONT_HAVE_LIVES'));
  12875. return;
  12876. }
  12877.  
  12878. while (1) {
  12879. if (!isBrawlsAutoStart) {
  12880. this.end(I18N('BTN_CANCELED'));
  12881. return;
  12882. }
  12883.  
  12884. const maxStage = this.brawlInfo.questInfo.stage;
  12885. const stage = this.stage[maxStage];
  12886. const progress = this.brawlInfo.questInfo.progress;
  12887.  
  12888. setProgress(
  12889. `${I18N('STAGE')} ${stage}: ${progress}/${maxStage}<br>${I18N('FIGHTS')}: ${this.stats.count}<br>${I18N('WINS')}: ${
  12890. this.stats.win
  12891. }<br>${I18N('LOSSES')}: ${this.stats.loss}<br>${I18N('LIVES')}: ${this.attempts}<br>${I18N('STOP')}`,
  12892. false,
  12893. function () {
  12894. isBrawlsAutoStart = false;
  12895. }
  12896. );
  12897.  
  12898. if (this.brawlInfo.questInfo.canFarm) {
  12899. const result = await this.questFarm();
  12900. console.log(result);
  12901. }
  12902.  
  12903. if (!this.continueAttack && this.brawlInfo.questInfo.stage == 12 && this.brawlInfo.questInfo.progress == 12) {
  12904. if (
  12905. await popup.confirm(I18N('BRAWL_DAILY_TASK_COMPLETED'), [
  12906. { msg: I18N('BTN_NO'), result: true },
  12907. { msg: I18N('BTN_YES'), result: false },
  12908. ])
  12909. ) {
  12910. this.end(I18N('SUCCESS'));
  12911. return;
  12912. } else {
  12913. this.continueAttack = true;
  12914. }
  12915. }
  12916.  
  12917. if (!this.attempts && !this.info.boughtEndlessLivesToday) {
  12918. this.end(I18N('DONT_HAVE_LIVES'));
  12919. return;
  12920. }
  12921.  
  12922. const enemie = Object.values(this.brawlInfo.findEnemies).shift();
  12923.  
  12924. // Автоматический подбор пачки
  12925. if (this.isAuto) {
  12926. if (this.mandatoryId <= 4000 && this.mandatoryId != 13) {
  12927. this.end(I18N('BRAWL_AUTO_PACK_NOT_CUR_HERO'));
  12928. return;
  12929. }
  12930. if (this.mandatoryId >= 4000 && this.mandatoryId < 4100) {
  12931. this.args = await this.updateTitanPack(enemie.heroes);
  12932. } else if (this.mandatoryId < 4000 && this.mandatoryId == 13) {
  12933. this.args = await this.updateHeroesPack(enemie.heroes);
  12934. }
  12935. }
  12936.  
  12937. const result = await this.battle(enemie.userId);
  12938. this.brawlInfo = {
  12939. questInfo: result[1].result.response,
  12940. findEnemies: result[2].result.response,
  12941. };
  12942. }
  12943. }
  12944.  
  12945. async updateTitanPack(enemieHeroes) {
  12946. const packs = [
  12947. [4033, 4040, 4041, 4042, 4043],
  12948. [4032, 4040, 4041, 4042, 4043],
  12949. [4031, 4040, 4041, 4042, 4043],
  12950. [4030, 4040, 4041, 4042, 4043],
  12951. [4032, 4033, 4040, 4042, 4043],
  12952. [4030, 4033, 4041, 4042, 4043],
  12953. [4031, 4033, 4040, 4042, 4043],
  12954. [4032, 4033, 4040, 4041, 4043],
  12955. [4023, 4040, 4041, 4042, 4043],
  12956. [4030, 4033, 4040, 4042, 4043],
  12957. [4031, 4033, 4040, 4041, 4043],
  12958. [4022, 4040, 4041, 4042, 4043],
  12959. [4030, 4033, 4040, 4041, 4043],
  12960. [4021, 4040, 4041, 4042, 4043],
  12961. [4020, 4040, 4041, 4042, 4043],
  12962. [4023, 4033, 4040, 4042, 4043],
  12963. [4030, 4032, 4033, 4042, 4043],
  12964. [4023, 4033, 4040, 4041, 4043],
  12965. [4031, 4032, 4033, 4040, 4043],
  12966. [4030, 4032, 4033, 4041, 4043],
  12967. [4030, 4031, 4033, 4042, 4043],
  12968. [4013, 4040, 4041, 4042, 4043],
  12969. [4030, 4032, 4033, 4040, 4043],
  12970. [4030, 4031, 4033, 4041, 4043],
  12971. [4012, 4040, 4041, 4042, 4043],
  12972. [4030, 4031, 4033, 4040, 4043],
  12973. [4011, 4040, 4041, 4042, 4043],
  12974. [4010, 4040, 4041, 4042, 4043],
  12975. [4023, 4032, 4033, 4042, 4043],
  12976. [4022, 4032, 4033, 4042, 4043],
  12977. [4023, 4032, 4033, 4041, 4043],
  12978. [4021, 4032, 4033, 4042, 4043],
  12979. [4022, 4032, 4033, 4041, 4043],
  12980. [4023, 4030, 4033, 4042, 4043],
  12981. [4023, 4032, 4033, 4040, 4043],
  12982. [4013, 4033, 4040, 4042, 4043],
  12983. [4020, 4032, 4033, 4042, 4043],
  12984. [4021, 4032, 4033, 4041, 4043],
  12985. [4022, 4030, 4033, 4042, 4043],
  12986. [4022, 4032, 4033, 4040, 4043],
  12987. [4023, 4030, 4033, 4041, 4043],
  12988. [4023, 4031, 4033, 4040, 4043],
  12989. [4013, 4033, 4040, 4041, 4043],
  12990. [4020, 4031, 4033, 4042, 4043],
  12991. [4020, 4032, 4033, 4041, 4043],
  12992. [4021, 4030, 4033, 4042, 4043],
  12993. [4021, 4032, 4033, 4040, 4043],
  12994. [4022, 4030, 4033, 4041, 4043],
  12995. [4022, 4031, 4033, 4040, 4043],
  12996. [4023, 4030, 4033, 4040, 4043],
  12997. [4030, 4031, 4032, 4033, 4043],
  12998. [4003, 4040, 4041, 4042, 4043],
  12999. [4020, 4030, 4033, 4042, 4043],
  13000. [4020, 4031, 4033, 4041, 4043],
  13001. [4020, 4032, 4033, 4040, 4043],
  13002. [4021, 4030, 4033, 4041, 4043],
  13003. [4021, 4031, 4033, 4040, 4043],
  13004. [4022, 4030, 4033, 4040, 4043],
  13005. [4030, 4031, 4032, 4033, 4042],
  13006. [4002, 4040, 4041, 4042, 4043],
  13007. [4020, 4030, 4033, 4041, 4043],
  13008. [4020, 4031, 4033, 4040, 4043],
  13009. [4021, 4030, 4033, 4040, 4043],
  13010. [4030, 4031, 4032, 4033, 4041],
  13011. [4001, 4040, 4041, 4042, 4043],
  13012. [4030, 4031, 4032, 4033, 4040],
  13013. [4000, 4040, 4041, 4042, 4043],
  13014. [4013, 4032, 4033, 4042, 4043],
  13015. [4012, 4032, 4033, 4042, 4043],
  13016. [4013, 4032, 4033, 4041, 4043],
  13017. [4023, 4031, 4032, 4033, 4043],
  13018. [4011, 4032, 4033, 4042, 4043],
  13019. [4012, 4032, 4033, 4041, 4043],
  13020. [4013, 4030, 4033, 4042, 4043],
  13021. [4013, 4032, 4033, 4040, 4043],
  13022. [4023, 4030, 4032, 4033, 4043],
  13023. [4003, 4033, 4040, 4042, 4043],
  13024. [4013, 4023, 4040, 4042, 4043],
  13025. [4010, 4032, 4033, 4042, 4043],
  13026. [4011, 4032, 4033, 4041, 4043],
  13027. [4012, 4030, 4033, 4042, 4043],
  13028. [4012, 4032, 4033, 4040, 4043],
  13029. [4013, 4030, 4033, 4041, 4043],
  13030. [4013, 4031, 4033, 4040, 4043],
  13031. [4023, 4030, 4031, 4033, 4043],
  13032. [4003, 4033, 4040, 4041, 4043],
  13033. [4013, 4023, 4040, 4041, 4043],
  13034. [4010, 4031, 4033, 4042, 4043],
  13035. [4010, 4032, 4033, 4041, 4043],
  13036. [4011, 4030, 4033, 4042, 4043],
  13037. [4011, 4032, 4033, 4040, 4043],
  13038. [4012, 4030, 4033, 4041, 4043],
  13039. [4012, 4031, 4033, 4040, 4043],
  13040. [4013, 4030, 4033, 4040, 4043],
  13041. [4010, 4030, 4033, 4042, 4043],
  13042. [4010, 4031, 4033, 4041, 4043],
  13043. [4010, 4032, 4033, 4040, 4043],
  13044. [4011, 4030, 4033, 4041, 4043],
  13045. [4011, 4031, 4033, 4040, 4043],
  13046. [4012, 4030, 4033, 4040, 4043],
  13047. [4010, 4030, 4033, 4041, 4043],
  13048. [4010, 4031, 4033, 4040, 4043],
  13049. [4011, 4030, 4033, 4040, 4043],
  13050. [4003, 4032, 4033, 4042, 4043],
  13051. [4002, 4032, 4033, 4042, 4043],
  13052. [4003, 4032, 4033, 4041, 4043],
  13053. [4013, 4031, 4032, 4033, 4043],
  13054. [4001, 4032, 4033, 4042, 4043],
  13055. [4002, 4032, 4033, 4041, 4043],
  13056. [4003, 4030, 4033, 4042, 4043],
  13057. [4003, 4032, 4033, 4040, 4043],
  13058. [4013, 4030, 4032, 4033, 4043],
  13059. [4003, 4023, 4040, 4042, 4043],
  13060. [4000, 4032, 4033, 4042, 4043],
  13061. [4001, 4032, 4033, 4041, 4043],
  13062. [4002, 4030, 4033, 4042, 4043],
  13063. [4002, 4032, 4033, 4040, 4043],
  13064. [4003, 4030, 4033, 4041, 4043],
  13065. [4003, 4031, 4033, 4040, 4043],
  13066. [4020, 4022, 4023, 4042, 4043],
  13067. [4013, 4030, 4031, 4033, 4043],
  13068. [4003, 4023, 4040, 4041, 4043],
  13069. [4000, 4031, 4033, 4042, 4043],
  13070. [4000, 4032, 4033, 4041, 4043],
  13071. [4001, 4030, 4033, 4042, 4043],
  13072. [4001, 4032, 4033, 4040, 4043],
  13073. [4002, 4030, 4033, 4041, 4043],
  13074. [4002, 4031, 4033, 4040, 4043],
  13075. [4003, 4030, 4033, 4040, 4043],
  13076. [4021, 4022, 4023, 4040, 4043],
  13077. [4020, 4022, 4023, 4041, 4043],
  13078. [4020, 4021, 4023, 4042, 4043],
  13079. [4023, 4030, 4031, 4032, 4033],
  13080. [4000, 4030, 4033, 4042, 4043],
  13081. [4000, 4031, 4033, 4041, 4043],
  13082. [4000, 4032, 4033, 4040, 4043],
  13083. [4001, 4030, 4033, 4041, 4043],
  13084. [4001, 4031, 4033, 4040, 4043],
  13085. [4002, 4030, 4033, 4040, 4043],
  13086. [4020, 4022, 4023, 4040, 4043],
  13087. [4020, 4021, 4023, 4041, 4043],
  13088. [4022, 4030, 4031, 4032, 4033],
  13089. [4000, 4030, 4033, 4041, 4043],
  13090. [4000, 4031, 4033, 4040, 4043],
  13091. [4001, 4030, 4033, 4040, 4043],
  13092. [4020, 4021, 4023, 4040, 4043],
  13093. [4021, 4030, 4031, 4032, 4033],
  13094. [4020, 4030, 4031, 4032, 4033],
  13095. [4003, 4031, 4032, 4033, 4043],
  13096. [4020, 4022, 4023, 4033, 4043],
  13097. [4003, 4030, 4032, 4033, 4043],
  13098. [4003, 4013, 4040, 4042, 4043],
  13099. [4020, 4021, 4023, 4033, 4043],
  13100. [4003, 4030, 4031, 4033, 4043],
  13101. [4003, 4013, 4040, 4041, 4043],
  13102. [4013, 4030, 4031, 4032, 4033],
  13103. [4012, 4030, 4031, 4032, 4033],
  13104. [4011, 4030, 4031, 4032, 4033],
  13105. [4010, 4030, 4031, 4032, 4033],
  13106. [4013, 4023, 4031, 4032, 4033],
  13107. [4013, 4023, 4030, 4032, 4033],
  13108. [4020, 4022, 4023, 4032, 4033],
  13109. [4013, 4023, 4030, 4031, 4033],
  13110. [4021, 4022, 4023, 4030, 4033],
  13111. [4020, 4022, 4023, 4031, 4033],
  13112. [4020, 4021, 4023, 4032, 4033],
  13113. [4020, 4021, 4022, 4023, 4043],
  13114. [4003, 4030, 4031, 4032, 4033],
  13115. [4020, 4022, 4023, 4030, 4033],
  13116. [4020, 4021, 4023, 4031, 4033],
  13117. [4020, 4021, 4022, 4023, 4042],
  13118. [4002, 4030, 4031, 4032, 4033],
  13119. [4020, 4021, 4023, 4030, 4033],
  13120. [4020, 4021, 4022, 4023, 4041],
  13121. [4001, 4030, 4031, 4032, 4033],
  13122. [4020, 4021, 4022, 4023, 4040],
  13123. [4000, 4030, 4031, 4032, 4033],
  13124. [4003, 4023, 4031, 4032, 4033],
  13125. [4013, 4020, 4022, 4023, 4043],
  13126. [4003, 4023, 4030, 4032, 4033],
  13127. [4010, 4012, 4013, 4042, 4043],
  13128. [4013, 4020, 4021, 4023, 4043],
  13129. [4003, 4023, 4030, 4031, 4033],
  13130. [4011, 4012, 4013, 4040, 4043],
  13131. [4010, 4012, 4013, 4041, 4043],
  13132. [4010, 4011, 4013, 4042, 4043],
  13133. [4020, 4021, 4022, 4023, 4033],
  13134. [4010, 4012, 4013, 4040, 4043],
  13135. [4010, 4011, 4013, 4041, 4043],
  13136. [4020, 4021, 4022, 4023, 4032],
  13137. [4010, 4011, 4013, 4040, 4043],
  13138. [4020, 4021, 4022, 4023, 4031],
  13139. [4020, 4021, 4022, 4023, 4030],
  13140. [4003, 4013, 4031, 4032, 4033],
  13141. [4010, 4012, 4013, 4033, 4043],
  13142. [4003, 4020, 4022, 4023, 4043],
  13143. [4013, 4020, 4022, 4023, 4033],
  13144. [4003, 4013, 4030, 4032, 4033],
  13145. [4010, 4011, 4013, 4033, 4043],
  13146. [4003, 4020, 4021, 4023, 4043],
  13147. [4013, 4020, 4021, 4023, 4033],
  13148. [4003, 4013, 4030, 4031, 4033],
  13149. [4010, 4012, 4013, 4023, 4043],
  13150. [4003, 4020, 4022, 4023, 4033],
  13151. [4010, 4012, 4013, 4032, 4033],
  13152. [4010, 4011, 4013, 4023, 4043],
  13153. [4003, 4020, 4021, 4023, 4033],
  13154. [4011, 4012, 4013, 4030, 4033],
  13155. [4010, 4012, 4013, 4031, 4033],
  13156. [4010, 4011, 4013, 4032, 4033],
  13157. [4013, 4020, 4021, 4022, 4023],
  13158. [4010, 4012, 4013, 4030, 4033],
  13159. [4010, 4011, 4013, 4031, 4033],
  13160. [4012, 4020, 4021, 4022, 4023],
  13161. [4010, 4011, 4013, 4030, 4033],
  13162. [4011, 4020, 4021, 4022, 4023],
  13163. [4010, 4020, 4021, 4022, 4023],
  13164. [4010, 4012, 4013, 4023, 4033],
  13165. [4000, 4002, 4003, 4042, 4043],
  13166. [4010, 4011, 4013, 4023, 4033],
  13167. [4001, 4002, 4003, 4040, 4043],
  13168. [4000, 4002, 4003, 4041, 4043],
  13169. [4000, 4001, 4003, 4042, 4043],
  13170. [4010, 4011, 4012, 4013, 4043],
  13171. [4003, 4020, 4021, 4022, 4023],
  13172. [4000, 4002, 4003, 4040, 4043],
  13173. [4000, 4001, 4003, 4041, 4043],
  13174. [4010, 4011, 4012, 4013, 4042],
  13175. [4002, 4020, 4021, 4022, 4023],
  13176. [4000, 4001, 4003, 4040, 4043],
  13177. [4010, 4011, 4012, 4013, 4041],
  13178. [4001, 4020, 4021, 4022, 4023],
  13179. [4010, 4011, 4012, 4013, 4040],
  13180. [4000, 4020, 4021, 4022, 4023],
  13181. [4001, 4002, 4003, 4033, 4043],
  13182. [4000, 4002, 4003, 4033, 4043],
  13183. [4003, 4010, 4012, 4013, 4043],
  13184. [4003, 4013, 4020, 4022, 4023],
  13185. [4000, 4001, 4003, 4033, 4043],
  13186. [4003, 4010, 4011, 4013, 4043],
  13187. [4003, 4013, 4020, 4021, 4023],
  13188. [4010, 4011, 4012, 4013, 4033],
  13189. [4010, 4011, 4012, 4013, 4032],
  13190. [4010, 4011, 4012, 4013, 4031],
  13191. [4010, 4011, 4012, 4013, 4030],
  13192. [4001, 4002, 4003, 4023, 4043],
  13193. [4000, 4002, 4003, 4023, 4043],
  13194. [4003, 4010, 4012, 4013, 4033],
  13195. [4000, 4002, 4003, 4032, 4033],
  13196. [4000, 4001, 4003, 4023, 4043],
  13197. [4003, 4010, 4011, 4013, 4033],
  13198. [4001, 4002, 4003, 4030, 4033],
  13199. [4000, 4002, 4003, 4031, 4033],
  13200. [4000, 4001, 4003, 4032, 4033],
  13201. [4010, 4011, 4012, 4013, 4023],
  13202. [4000, 4002, 4003, 4030, 4033],
  13203. [4000, 4001, 4003, 4031, 4033],
  13204. [4010, 4011, 4012, 4013, 4022],
  13205. [4000, 4001, 4003, 4030, 4033],
  13206. [4010, 4011, 4012, 4013, 4021],
  13207. [4010, 4011, 4012, 4013, 4020],
  13208. [4001, 4002, 4003, 4013, 4043],
  13209. [4001, 4002, 4003, 4023, 4033],
  13210. [4000, 4002, 4003, 4013, 4043],
  13211. [4000, 4002, 4003, 4023, 4033],
  13212. [4003, 4010, 4012, 4013, 4023],
  13213. [4000, 4001, 4003, 4013, 4043],
  13214. [4000, 4001, 4003, 4023, 4033],
  13215. [4003, 4010, 4011, 4013, 4023],
  13216. [4001, 4002, 4003, 4013, 4033],
  13217. [4000, 4002, 4003, 4013, 4033],
  13218. [4000, 4001, 4003, 4013, 4033],
  13219. [4000, 4001, 4002, 4003, 4043],
  13220. [4003, 4010, 4011, 4012, 4013],
  13221. [4000, 4001, 4002, 4003, 4042],
  13222. [4002, 4010, 4011, 4012, 4013],
  13223. [4000, 4001, 4002, 4003, 4041],
  13224. [4001, 4010, 4011, 4012, 4013],
  13225. [4000, 4001, 4002, 4003, 4040],
  13226. [4000, 4010, 4011, 4012, 4013],
  13227. [4001, 4002, 4003, 4013, 4023],
  13228. [4000, 4002, 4003, 4013, 4023],
  13229. [4000, 4001, 4003, 4013, 4023],
  13230. [4000, 4001, 4002, 4003, 4033],
  13231. [4000, 4001, 4002, 4003, 4032],
  13232. [4000, 4001, 4002, 4003, 4031],
  13233. [4000, 4001, 4002, 4003, 4030],
  13234. [4000, 4001, 4002, 4003, 4023],
  13235. [4000, 4001, 4002, 4003, 4022],
  13236. [4000, 4001, 4002, 4003, 4021],
  13237. [4000, 4001, 4002, 4003, 4020],
  13238. [4000, 4001, 4002, 4003, 4013],
  13239. [4000, 4001, 4002, 4003, 4012],
  13240. [4000, 4001, 4002, 4003, 4011],
  13241. [4000, 4001, 4002, 4003, 4010],
  13242. ].filter((p) => p.includes(this.mandatoryId));
  13243.  
  13244. const bestPack = {
  13245. pack: packs[0],
  13246. winRate: 0,
  13247. countBattle: 0,
  13248. id: 0,
  13249. };
  13250.  
  13251. for (const id in packs) {
  13252. const pack = packs[id];
  13253. const attackers = this.maxUpgrade.filter((e) => pack.includes(e.id)).reduce((obj, e) => ({ ...obj, [e.id]: e }), {});
  13254. const battle = {
  13255. attackers,
  13256. defenders: [enemieHeroes],
  13257. type: 'brawl_titan',
  13258. };
  13259. const isRandom = this.isRandomBattle(battle);
  13260. const stat = {
  13261. count: 0,
  13262. win: 0,
  13263. winRate: 0,
  13264. };
  13265. for (let i = 1; i <= 20; i++) {
  13266. battle.seed = Math.floor(Date.now() / 1000) + Math.random() * 1000;
  13267. const result = await Calc(battle);
  13268. stat.win += result.result.win;
  13269. stat.count += 1;
  13270. stat.winRate = stat.win / stat.count;
  13271. if (!isRandom || (i >= 2 && stat.winRate < 0.65) || (i >= 10 && stat.winRate == 1)) {
  13272. break;
  13273. }
  13274. }
  13275.  
  13276. if (!isRandom && stat.win) {
  13277. return {
  13278. favor: {},
  13279. heroes: pack,
  13280. };
  13281. }
  13282. if (stat.winRate > 0.85) {
  13283. return {
  13284. favor: {},
  13285. heroes: pack,
  13286. };
  13287. }
  13288. if (stat.winRate > bestPack.winRate) {
  13289. bestPack.countBattle = stat.count;
  13290. bestPack.winRate = stat.winRate;
  13291. bestPack.pack = pack;
  13292. bestPack.id = id;
  13293. }
  13294. }
  13295.  
  13296. //console.log(bestPack.id, bestPack.pack, bestPack.winRate, bestPack.countBattle);
  13297. return {
  13298. favor: {},
  13299. heroes: bestPack.pack,
  13300. };
  13301. }
  13302.  
  13303. isRandomPack(pack) {
  13304. const ids = Object.keys(pack);
  13305. return ids.includes('4023') || ids.includes('4021');
  13306. }
  13307.  
  13308. isRandomBattle(battle) {
  13309. return this.isRandomPack(battle.attackers) || this.isRandomPack(battle.defenders[0]);
  13310. }
  13311.  
  13312. async updateHeroesPack(enemieHeroes) {
  13313. 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}}}];
  13314.  
  13315. const bestPack = {
  13316. pack: packs[0],
  13317. countWin: 0,
  13318. }
  13319.  
  13320. for (const pack of packs) {
  13321. const attackers = pack.attackers;
  13322. const battle = {
  13323. attackers,
  13324. defenders: [enemieHeroes],
  13325. type: 'brawl',
  13326. };
  13327.  
  13328. let countWinBattles = 0;
  13329. let countTestBattle = 10;
  13330. for (let i = 0; i < countTestBattle; i++) {
  13331. battle.seed = Math.floor(Date.now() / 1000) + Math.random() * 1000;
  13332. const result = await Calc(battle);
  13333. if (result.result.win) {
  13334. countWinBattles++;
  13335. }
  13336. if (countWinBattles > 7) {
  13337. console.log(pack)
  13338. return pack.args;
  13339. }
  13340. }
  13341. if (countWinBattles > bestPack.countWin) {
  13342. bestPack.countWin = countWinBattles;
  13343. bestPack.pack = pack.args;
  13344. }
  13345. }
  13346.  
  13347. console.log(bestPack);
  13348. return bestPack.pack;
  13349. }
  13350.  
  13351. async questFarm() {
  13352. const calls = [this.callBrawlQuestFarm];
  13353. const result = await Send(JSON.stringify({ calls }));
  13354. return result.results[0].result.response;
  13355. }
  13356.  
  13357. async getBrawlInfo() {
  13358. const data = await Send(JSON.stringify({
  13359. calls: [
  13360. this.callUserGetInfo,
  13361. this.callBrawlQuestGetInfo,
  13362. this.callBrawlFindEnemies,
  13363. this.callTeamGetMaxUpgrade,
  13364. this.callBrawlGetInfo,
  13365. ]
  13366. }));
  13367.  
  13368. let attempts = data.results[0].result.response.refillable.find(n => n.id == 48);
  13369.  
  13370. const maxUpgrade = data.results[3].result.response;
  13371. const maxHero = Object.values(maxUpgrade.hero);
  13372. const maxTitan = Object.values(maxUpgrade.titan);
  13373. const maxPet = Object.values(maxUpgrade.pet);
  13374. this.maxUpgrade = [...maxHero, ...maxPet, ...maxTitan];
  13375.  
  13376. this.info = data.results[4].result.response;
  13377. this.mandatoryId = lib.data.brawl.promoHero[this.info.id].promoHero;
  13378. return {
  13379. attempts: attempts.amount,
  13380. questInfo: data.results[1].result.response,
  13381. findEnemies: data.results[2].result.response,
  13382. }
  13383. }
  13384.  
  13385. /**
  13386. * Carrying out a fight
  13387. *
  13388. * Проведение боя
  13389. */
  13390. async battle(userId) {
  13391. this.stats.count++;
  13392. const battle = await this.startBattle(userId, this.args);
  13393. const result = await Calc(battle);
  13394. console.log(result.result);
  13395. if (result.result.win) {
  13396. this.stats.win++;
  13397. } else {
  13398. this.stats.loss++;
  13399. if (!this.info.boughtEndlessLivesToday) {
  13400. this.attempts--;
  13401. }
  13402. }
  13403. return await this.endBattle(result);
  13404. // return await this.cancelBattle(result);
  13405. }
  13406.  
  13407. /**
  13408. * Starts a fight
  13409. *
  13410. * Начинает бой
  13411. */
  13412. async startBattle(userId, args) {
  13413. const call = {
  13414. name: "brawl_startBattle",
  13415. args,
  13416. ident: "brawl_startBattle"
  13417. }
  13418. call.args.userId = userId;
  13419. const calls = [call];
  13420. const result = await Send(JSON.stringify({ calls }));
  13421. return result.results[0].result.response;
  13422. }
  13423.  
  13424. cancelBattle(battle) {
  13425. const fixBattle = function (heroes) {
  13426. for (const ids in heroes) {
  13427. const hero = heroes[ids];
  13428. hero.energy = random(1, 999);
  13429. if (hero.hp > 0) {
  13430. hero.hp = random(1, hero.hp);
  13431. }
  13432. }
  13433. }
  13434. fixBattle(battle.progress[0].attackers.heroes);
  13435. fixBattle(battle.progress[0].defenders.heroes);
  13436. return this.endBattle(battle);
  13437. }
  13438.  
  13439. /**
  13440. * Ends the fight
  13441. *
  13442. * Заканчивает бой
  13443. */
  13444. async endBattle(battle) {
  13445. battle.progress[0].attackers.input = ['auto', 0, 0, 'auto', 0, 0];
  13446. const calls = [{
  13447. name: "brawl_endBattle",
  13448. args: {
  13449. result: battle.result,
  13450. progress: battle.progress
  13451. },
  13452. ident: "brawl_endBattle"
  13453. },
  13454. this.callBrawlQuestGetInfo,
  13455. this.callBrawlFindEnemies,
  13456. ];
  13457. const result = await Send(JSON.stringify({ calls }));
  13458. return result.results;
  13459. }
  13460.  
  13461. end(endReason) {
  13462. setIsCancalBattle(true);
  13463. isBrawlsAutoStart = false;
  13464. setProgress(endReason, true);
  13465. console.log(endReason);
  13466. this.resolve();
  13467. }
  13468. }
  13469.  
  13470. this.HWHClasses.executeBrawls = executeBrawls;
  13471.  
  13472. /**
  13473. * Runs missions from the company on a specified list
  13474. * Выполняет миссии из компании по списку
  13475. * @param {Array} missions [{id: 25, times: 3}, {id: 45, times: 30}]
  13476. * @param {Boolean} isRaids выполнять миссии рейдом
  13477. * @returns
  13478. */
  13479. function testCompany(missions, isRaids = false) {
  13480. const { ExecuteCompany } = HWHClasses;
  13481. return new Promise((resolve, reject) => {
  13482. const tower = new ExecuteCompany(resolve, reject);
  13483. tower.start(missions, isRaids);
  13484. });
  13485. }
  13486.  
  13487. /**
  13488. * Fulfilling company missions
  13489. * Выполнение миссий компании
  13490. */
  13491. class ExecuteCompany {
  13492. constructor(resolve, reject) {
  13493. this.resolve = resolve;
  13494. this.reject = reject;
  13495. this.missionsIds = [];
  13496. this.currentNum = 0;
  13497. this.isRaid = false;
  13498. this.currentTimes = 0;
  13499.  
  13500. this.argsMission = {
  13501. id: 0,
  13502. heroes: [],
  13503. favor: {},
  13504. };
  13505. }
  13506.  
  13507. async start(missionIds, isRaids) {
  13508. this.missionsIds = missionIds;
  13509. this.isRaid = isRaids;
  13510. const data = await Caller.send(['teamGetAll', 'teamGetFavor']);
  13511. this.startCompany(data);
  13512. }
  13513.  
  13514. startCompany(data) {
  13515. const [teamGetAll, teamGetFavor] = data;
  13516.  
  13517. this.argsMission.heroes = teamGetAll.mission.filter((id) => id < 6000);
  13518. this.argsMission.favor = teamGetFavor.mission;
  13519.  
  13520. const pet = teamGetAll.mission.filter((id) => id >= 6000).pop();
  13521. if (pet) {
  13522. this.argsMission.pet = pet;
  13523. }
  13524.  
  13525. this.checkStat();
  13526. }
  13527.  
  13528. checkStat() {
  13529. if (!this.missionsIds[this.currentNum].times) {
  13530. this.currentNum++;
  13531. }
  13532.  
  13533. if (this.currentNum === this.missionsIds.length) {
  13534. this.endCompany('EndCompany');
  13535. return;
  13536. }
  13537.  
  13538. this.argsMission.id = this.missionsIds[this.currentNum].id;
  13539. this.currentTimes = this.missionsIds[this.currentNum].times;
  13540. setProgress('Сompany: ' + this.argsMission.id + ' - ' + this.currentTimes, false);
  13541. if (this.isRaid) {
  13542. this.missionRaid();
  13543. } else {
  13544. this.missionStart();
  13545. }
  13546. }
  13547.  
  13548. async missionRaid() {
  13549. try {
  13550. await Caller.send({
  13551. name: 'missionRaid',
  13552. args: {
  13553. id: this.argsMission.id,
  13554. times: this.currentTimes,
  13555. },
  13556. });
  13557. } catch (error) {
  13558. console.warn(error);
  13559. }
  13560.  
  13561. this.missionsIds[this.currentNum].times = 0;
  13562. this.checkStat();
  13563. }
  13564.  
  13565. async missionStart() {
  13566. this.lastMissionBattleStart = Date.now();
  13567. let result = null;
  13568. try {
  13569. result = await Caller.send({
  13570. name: 'missionStart',
  13571. args: this.argsMission,
  13572. });
  13573. } catch (error) {
  13574. console.warn(error);
  13575. this.endCompany('missionStartError', error['error']);
  13576. return;
  13577. }
  13578. this.missionEnd(await Calc(result));
  13579. }
  13580.  
  13581. async missionEnd(r) {
  13582. const timer = r.battleTimer;
  13583. await countdownTimer(timer, 'Сompany: ' + this.argsMission.id + ' - ' + this.currentTimes);
  13584.  
  13585. try {
  13586. await Caller.send({
  13587. name: 'missionEnd',
  13588. args: {
  13589. id: this.argsMission.id,
  13590. result: r.result,
  13591. progress: r.progress,
  13592. },
  13593. });
  13594. } catch (error) {
  13595. this.endCompany('missionEndError', error);
  13596. return;
  13597. }
  13598.  
  13599. this.missionsIds[this.currentNum].times--;
  13600. this.checkStat();
  13601. }
  13602.  
  13603. endCompany(reason, info) {
  13604. setProgress('Сompany completed!', true);
  13605. console.log(reason, info);
  13606. this.resolve();
  13607. }
  13608. }
  13609.  
  13610. this.HWHClasses.ExecuteCompany = ExecuteCompany;
  13611. })();
  13612.  
  13613. /**
  13614. * TODO:
  13615. * Закрытие окошек по Esc +-
  13616. * Починить работу скрипта на уровне команды ниже 10 +-
  13617. * Написать номальную синхронизацию
  13618. */