Greasy Fork is available in English.

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.340
  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 Solu 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. return original.send.call(this, sourceData);
  2010. } catch(e) {
  2011. debugger;
  2012. }
  2013. }
  2014. };
  2015. /**
  2016. * Processing and substitution of outgoing data
  2017. *
  2018. * Обработка и подмена исходящих данных
  2019. */
  2020. async function checkChangeSend(sourceData, tempData) {
  2021. try {
  2022. /**
  2023. * A function that replaces battle data with incorrect ones to cancel combatя
  2024. *
  2025. * Функция заменяющая данные боя на неверные для отмены боя
  2026. */
  2027. const fixBattle = function (heroes) {
  2028. for (const ids in heroes) {
  2029. hero = heroes[ids];
  2030. hero.energy = random(1, 999);
  2031. if (hero.hp > 0) {
  2032. hero.hp = random(1, hero.hp);
  2033. }
  2034. }
  2035. }
  2036. /**
  2037. * Dialog window 2
  2038. *
  2039. * Диалоговое окно 2
  2040. */
  2041. const showMsg = async function (msg, ansF, ansS) {
  2042. if (typeof popup == 'object') {
  2043. return await popup.confirm(msg, [
  2044. {msg: ansF, result: false},
  2045. {msg: ansS, result: true},
  2046. ]);
  2047. } else {
  2048. return !confirm(`${msg}\n ${ansF} (${I18N('BTN_OK')})\n ${ansS} (${I18N('BTN_CANCEL')})`);
  2049. }
  2050. }
  2051. /**
  2052. * Dialog window 3
  2053. *
  2054. * Диалоговое окно 3
  2055. */
  2056. const showMsgs = async function (msg, ansF, ansS, ansT) {
  2057. return await popup.confirm(msg, [
  2058. {msg: ansF, result: 0},
  2059. {msg: ansS, result: 1},
  2060. {msg: ansT, result: 2},
  2061. ]);
  2062. }
  2063.  
  2064. let changeRequest = false;
  2065. testData = JSON.parse(tempData);
  2066. for (const call of testData.calls) {
  2067. if (!artifactChestOpen) {
  2068. requestHistory[this.uniqid].calls[call.name] = call.ident;
  2069. }
  2070. /**
  2071. * Cancellation of the battle in adventures, on VG and with minions of Asgard
  2072. * Отмена боя в приключениях, на ВГ и с прислужниками Асгарда
  2073. */
  2074. if ((call.name == 'adventure_endBattle' ||
  2075. call.name == 'adventureSolo_endBattle' ||
  2076. call.name == 'clanWarEndBattle' &&
  2077. isChecked('cancelBattle') ||
  2078. call.name == 'crossClanWar_endBattle' &&
  2079. isChecked('cancelBattle') ||
  2080. call.name == 'brawl_endBattle' ||
  2081. call.name == 'towerEndBattle' ||
  2082. call.name == 'invasion_bossEnd' ||
  2083. call.name == 'titanArenaEndBattle' ||
  2084. call.name == 'bossEndBattle' ||
  2085. call.name == 'clanRaid_endNodeBattle') &&
  2086. isCancalBattle) {
  2087. nameFuncEndBattle = call.name;
  2088.  
  2089. if (isChecked('tryFixIt_v2') &&
  2090. !call.args.result.win &&
  2091. (call.name == 'brawl_endBattle' ||
  2092. //call.name == 'crossClanWar_endBattle' ||
  2093. call.name == 'epicBrawl_endBattle' ||
  2094. //call.name == 'clanWarEndBattle' ||
  2095. call.name == 'adventure_endBattle' ||
  2096. call.name == 'titanArenaEndBattle' ||
  2097. call.name == 'bossEndBattle' ||
  2098. call.name == 'adventureSolo_endBattle') &&
  2099. lastBattleInfo) {
  2100. const noFixWin = call.name == 'clanWarEndBattle' || call.name == 'crossClanWar_endBattle';
  2101. const cloneBattle = structuredClone(lastBattleInfo);
  2102. lastBattleInfo = null;
  2103. try {
  2104. const { BestOrWinFixBattle } = HWHClasses;
  2105. const bFix = new BestOrWinFixBattle(cloneBattle);
  2106. bFix.setNoMakeWin(noFixWin);
  2107. let endTime = Date.now() + 3e4;
  2108. if (endTime < cloneBattle.endTime) {
  2109. endTime = cloneBattle.endTime;
  2110. }
  2111. const result = await bFix.start(cloneBattle.endTime, 150);
  2112.  
  2113. if (result.result.win) {
  2114. call.args.result = result.result;
  2115. call.args.progress = result.progress;
  2116. changeRequest = true;
  2117. } else if (result.value) {
  2118. if (
  2119. await popup.confirm(I18N('DEFEAT') + '<br>' + I18N('BEST_RESULT', { value: result.value }), [
  2120. { msg: I18N('BTN_CANCEL'), result: 0 },
  2121. { msg: I18N('BTN_ACCEPT'), result: 1 },
  2122. ])
  2123. ) {
  2124. call.args.result = result.result;
  2125. call.args.progress = result.progress;
  2126. changeRequest = true;
  2127. }
  2128. }
  2129. } catch (error) {
  2130. console.error(error);
  2131. }
  2132. }
  2133.  
  2134. if (!call.args.result.win) {
  2135. let resultPopup = false;
  2136. if (call.name == 'adventure_endBattle' ||
  2137. //call.name == 'invasion_bossEnd' ||
  2138. call.name == 'bossEndBattle' ||
  2139. call.name == 'adventureSolo_endBattle') {
  2140. resultPopup = await showMsgs(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_CANCEL'), I18N('BTN_AUTO'));
  2141. } else if (call.name == 'clanWarEndBattle' ||
  2142. call.name == 'crossClanWar_endBattle') {
  2143. resultPopup = await showMsg(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_AUTO_F5'));
  2144. } else if (call.name !== 'epicBrawl_endBattle' && call.name !== 'titanArenaEndBattle') {
  2145. resultPopup = await showMsg(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_CANCEL'));
  2146. }
  2147. if (resultPopup) {
  2148. if (call.name == 'invasion_bossEnd') {
  2149. this.errorRequest = true;
  2150. }
  2151. fixBattle(call.args.progress[0].attackers.heroes);
  2152. fixBattle(call.args.progress[0].defenders.heroes);
  2153. changeRequest = true;
  2154. if (resultPopup > 1) {
  2155. this.onReadySuccess = testAutoBattle;
  2156. // setTimeout(bossBattle, 1000);
  2157. }
  2158. }
  2159. } else if (call.args.result.stars < 3 && call.name == 'towerEndBattle') {
  2160. resultPopup = await showMsg(I18N('LOST_HEROES'), I18N('BTN_OK'), I18N('BTN_CANCEL'), I18N('BTN_AUTO'));
  2161. if (resultPopup) {
  2162. fixBattle(call.args.progress[0].attackers.heroes);
  2163. fixBattle(call.args.progress[0].defenders.heroes);
  2164. changeRequest = true;
  2165. if (resultPopup > 1) {
  2166. this.onReadySuccess = testAutoBattle;
  2167. }
  2168. }
  2169. }
  2170. // Потасовки
  2171. if (isChecked('autoBrawls') && !isBrawlsAutoStart && call.name == 'brawl_endBattle') {}
  2172. }
  2173. /**
  2174. * Save pack for Brawls
  2175. *
  2176. * Сохраняем пачку для потасовок
  2177. */
  2178. if (isChecked('autoBrawls') && !isBrawlsAutoStart && call.name == 'brawl_startBattle') {
  2179. console.log(JSON.stringify(call.args));
  2180. brawlsPack = call.args;
  2181. if (
  2182. await popup.confirm(
  2183. I18N('START_AUTO_BRAWLS'),
  2184. [
  2185. { msg: I18N('BTN_NO'), result: false },
  2186. { msg: I18N('BTN_YES'), result: true },
  2187. ],
  2188. [
  2189. {
  2190. name: 'isAuto',
  2191. get label() { return I18N('BRAWL_AUTO_PACK'); },
  2192. checked: false,
  2193. },
  2194. ]
  2195. )
  2196. ) {
  2197. isBrawlsAutoStart = true;
  2198. const isAuto = popup.getCheckBoxes().find((e) => e.name === 'isAuto');
  2199. this.errorRequest = true;
  2200. testBrawls(isAuto.checked);
  2201. }
  2202. }
  2203. /**
  2204. * Canceled fight in Asgard
  2205. * Отмена боя в Асгарде
  2206. */
  2207. if (call.name == 'clanRaid_endBossBattle' && isChecked('cancelBattle')) {
  2208. const bossDamage = call.args.progress[0].defenders.heroes[1].extra;
  2209. let maxDamage = bossDamage.damageTaken + bossDamage.damageTakenNextLevel;
  2210. const lastDamage = maxDamage;
  2211.  
  2212. const testFunc = [];
  2213.  
  2214. if (testFuntions.masterFix) {
  2215. testFunc.push({ msg: 'masterFix', isInput: true, default: 100 });
  2216. }
  2217.  
  2218. const resultPopup = await popup.confirm(
  2219. `${I18N('MSG_YOU_APPLIED')} ${lastDamage.toLocaleString()} ${I18N('MSG_DAMAGE')}.`,
  2220. [
  2221. { msg: I18N('BTN_OK'), result: false },
  2222. { msg: I18N('BTN_AUTO_F5'), result: 1 },
  2223. { msg: I18N('BTN_TRY_FIX_IT'), result: 2 },
  2224. ...testFunc,
  2225. ],
  2226. [
  2227. {
  2228. name: 'isStat',
  2229. get label() { return I18N('CALC_STAT'); },
  2230. checked: false,
  2231. },
  2232. ]
  2233. );
  2234. if (resultPopup) {
  2235. if (resultPopup == 2) {
  2236. setProgress(I18N('LETS_FIX'), false);
  2237. await new Promise((e) => setTimeout(e, 0));
  2238. const cloneBattle = structuredClone(lastBossBattle);
  2239. const endTime = cloneBattle.endTime - 1e4;
  2240. console.log('fixBossBattleStart');
  2241.  
  2242. const { BossFixBattle } = HWHClasses;
  2243. const bFix = new BossFixBattle(cloneBattle);
  2244. const result = await bFix.start(endTime, 300);
  2245. console.log(result);
  2246.  
  2247. let msgResult = I18N('DAMAGE_NO_FIXED', {
  2248. lastDamage: lastDamage.toLocaleString()
  2249. });
  2250. if (result.value > lastDamage) {
  2251. call.args.result = result.result;
  2252. call.args.progress = result.progress;
  2253. msgResult = I18N('DAMAGE_FIXED', {
  2254. lastDamage: lastDamage.toLocaleString(),
  2255. maxDamage: result.value.toLocaleString(),
  2256. });
  2257. }
  2258. console.log(lastDamage, '>', result.value);
  2259. setProgress(
  2260. msgResult +
  2261. '<br/>' +
  2262. I18N('COUNT_FIXED', {
  2263. count: result.maxCount,
  2264. }),
  2265. false,
  2266. hideProgress
  2267. );
  2268. } else if (resultPopup > 3) {
  2269. const cloneBattle = structuredClone(lastBossBattle);
  2270. const { masterFixBattle } = HWHClasses;
  2271. const mFix = new masterFixBattle(cloneBattle);
  2272. const result = await mFix.start(cloneBattle.endTime, resultPopup);
  2273. console.log(result);
  2274. let msgResult = I18N('DAMAGE_NO_FIXED', {
  2275. lastDamage: lastDamage.toLocaleString(),
  2276. });
  2277. if (result.value > lastDamage) {
  2278. maxDamage = result.value;
  2279. call.args.result = result.result;
  2280. call.args.progress = result.progress;
  2281. msgResult = I18N('DAMAGE_FIXED', {
  2282. lastDamage: lastDamage.toLocaleString(),
  2283. maxDamage: maxDamage.toLocaleString(),
  2284. });
  2285. }
  2286. console.log('Урон:', lastDamage, maxDamage);
  2287. setProgress(msgResult, false, hideProgress);
  2288. } else {
  2289. fixBattle(call.args.progress[0].attackers.heroes);
  2290. fixBattle(call.args.progress[0].defenders.heroes);
  2291. }
  2292. changeRequest = true;
  2293. }
  2294. const isStat = popup.getCheckBoxes().find((e) => e.name === 'isStat');
  2295. if (isStat.checked) {
  2296. this.onReadySuccess = testBossBattle;
  2297. }
  2298. }
  2299. /**
  2300. * Save the Asgard Boss Attack Pack
  2301. * Сохраняем пачку для атаки босса Асгарда
  2302. */
  2303. if (call.name == 'clanRaid_startBossBattle') {
  2304. console.log(JSON.stringify(call.args));
  2305. }
  2306. /**
  2307. * Saving the request to start the last battle
  2308. * Сохранение запроса начала последнего боя
  2309. */
  2310. if (
  2311. call.name == 'clanWarAttack' ||
  2312. call.name == 'crossClanWar_startBattle' ||
  2313. call.name == 'adventure_turnStartBattle' ||
  2314. call.name == 'adventureSolo_turnStartBattle' ||
  2315. call.name == 'bossAttack' ||
  2316. call.name == 'invasion_bossStart' ||
  2317. call.name == 'towerStartBattle'
  2318. ) {
  2319. nameFuncStartBattle = call.name;
  2320. lastBattleArg = call.args;
  2321.  
  2322. if (call.name == 'invasion_bossStart') {
  2323. const timePassed = Date.now() - lastBossBattleStart;
  2324. if (timePassed < invasionTimer) {
  2325. await new Promise((e) => setTimeout(e, invasionTimer - timePassed));
  2326. }
  2327. invasionTimer -= 1;
  2328. }
  2329. lastBossBattleStart = Date.now();
  2330. }
  2331. if (call.name == 'invasion_bossEnd') {
  2332. const lastBattle = lastBattleInfo;
  2333. if (lastBattle && call.args.result.win) {
  2334. lastBattle.progress = call.args.progress;
  2335. const result = await Calc(lastBattle);
  2336. let timer = getTimer(result.battleTime, 1) + addBattleTimer;
  2337. const period = Math.ceil((Date.now() - lastBossBattleStart) / 1000);
  2338. console.log(timer, period);
  2339. if (period < timer) {
  2340. timer = timer - period;
  2341. await countdownTimer(timer);
  2342. }
  2343. }
  2344. }
  2345. /**
  2346. * Disable spending divination cards
  2347. * Отключить трату карт предсказаний
  2348. */
  2349. if (call.name == 'dungeonEndBattle') {
  2350. if (call.args.isRaid) {
  2351. if (countPredictionCard <= 0) {
  2352. delete call.args.isRaid;
  2353. changeRequest = true;
  2354. } else if (countPredictionCard > 0) {
  2355. countPredictionCard--;
  2356. }
  2357. }
  2358. console.log(`Cards: ${countPredictionCard}`);
  2359. /**
  2360. * Fix endless cards
  2361. * Исправление бесконечных карт
  2362. */
  2363. const lastBattle = lastDungeonBattleData;
  2364. if (lastBattle && !call.args.isRaid) {
  2365. if (changeRequest) {
  2366. lastBattle.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  2367. } else {
  2368. lastBattle.progress = call.args.progress;
  2369. }
  2370. const result = await Calc(lastBattle);
  2371.  
  2372. if (changeRequest) {
  2373. call.args.progress = result.progress;
  2374. call.args.result = result.result;
  2375. }
  2376. let timer = result.battleTimer + addBattleTimer;
  2377. const period = Math.ceil((Date.now() - lastDungeonBattleStart) / 1000);
  2378. console.log(timer, period);
  2379. if (period < timer) {
  2380. timer = timer - period;
  2381. await countdownTimer(timer);
  2382. }
  2383. }
  2384. }
  2385. /**
  2386. * Quiz Answer
  2387. * Ответ на викторину
  2388. */
  2389. if (call.name == 'quiz_answer') {
  2390. /**
  2391. * Automatically changes the answer to the correct one if there is one.
  2392. * Автоматически меняет ответ на правильный если он есть
  2393. */
  2394. if (lastAnswer && isChecked('getAnswer')) {
  2395. call.args.answerId = lastAnswer;
  2396. lastAnswer = null;
  2397. changeRequest = true;
  2398. }
  2399. }
  2400. /**
  2401. * Present
  2402. * Подарки
  2403. */
  2404. if (call.name == 'freebieCheck') {
  2405. freebieCheckInfo = call;
  2406. }
  2407. /** missionTimer */
  2408. if (call.name == 'missionEnd' && missionBattle) {
  2409. let startTimer = false;
  2410. if (!call.args.result.win) {
  2411. startTimer = await popup.confirm(I18N('DEFEAT_TURN_TIMER'), [
  2412. { msg: I18N('BTN_NO'), result: false },
  2413. { msg: I18N('BTN_YES'), result: true },
  2414. ]);
  2415. }
  2416.  
  2417. if (call.args.result.win || startTimer) {
  2418. missionBattle.progress = call.args.progress;
  2419. missionBattle.result = call.args.result;
  2420. const result = await Calc(missionBattle);
  2421.  
  2422. let timer = result.battleTimer + addBattleTimer;
  2423. const period = Math.ceil((Date.now() - lastMissionBattleStart) / 1000);
  2424. if (period < timer) {
  2425. timer = timer - period;
  2426. await countdownTimer(timer);
  2427. }
  2428. missionBattle = null;
  2429. } else {
  2430. this.errorRequest = true;
  2431. }
  2432. }
  2433. /**
  2434. * Getting mission data for auto-repeat
  2435. * Получение данных миссии для автоповтора
  2436. */
  2437. if (isChecked('repeatMission') &&
  2438. call.name == 'missionEnd') {
  2439. let missionInfo = {
  2440. id: call.args.id,
  2441. result: call.args.result,
  2442. heroes: call.args.progress[0].attackers.heroes,
  2443. count: 0,
  2444. }
  2445. setTimeout(async () => {
  2446. if (!isSendsMission && await popup.confirm(I18N('MSG_REPEAT_MISSION'), [
  2447. { msg: I18N('BTN_REPEAT'), result: true},
  2448. { msg: I18N('BTN_NO'), result: false},
  2449. ])) {
  2450. isStopSendMission = false;
  2451. isSendsMission = true;
  2452. sendsMission(missionInfo);
  2453. }
  2454. }, 0);
  2455. }
  2456. /**
  2457. * Getting mission data
  2458. * Получение данных миссии
  2459. * missionTimer
  2460. */
  2461. if (call.name == 'missionStart') {
  2462. lastMissionStart = call.args;
  2463. lastMissionBattleStart = Date.now();
  2464. }
  2465. /**
  2466. * Specify the quantity for Titan Orbs and Pet Eggs
  2467. * Указать количество для сфер титанов и яиц петов
  2468. */
  2469. if (isChecked('countControl') &&
  2470. (call.name == 'pet_chestOpen' ||
  2471. call.name == 'titanUseSummonCircle') &&
  2472. call.args.amount > 1) {
  2473. const startAmount = call.args.amount;
  2474. const result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2475. { msg: I18N('BTN_OPEN'), isInput: true, default: 1},
  2476. ]);
  2477. if (result) {
  2478. const item = call.name == 'pet_chestOpen' ? { id: 90, type: 'consumable' } : { id: 13, type: 'coin' };
  2479. cheats.updateInventory({
  2480. [item.type]: {
  2481. [item.id]: -(result - startAmount),
  2482. },
  2483. });
  2484. call.args.amount = result;
  2485. changeRequest = true;
  2486. }
  2487. }
  2488. /**
  2489. * Specify the amount for keys and spheres of titan artifacts
  2490. * Указать колличество для ключей и сфер артефактов титанов
  2491. */
  2492. if (isChecked('countControl') &&
  2493. (call.name == 'artifactChestOpen' ||
  2494. call.name == 'titanArtifactChestOpen') &&
  2495. call.args.amount > 1 &&
  2496. call.args.free &&
  2497. !changeRequest) {
  2498. artifactChestOpenCallName = call.name;
  2499. const startAmount = call.args.amount;
  2500. let result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2501. { msg: I18N('BTN_OPEN'), isInput: true, default: 1 },
  2502. ]);
  2503. if (result) {
  2504. const openChests = result;
  2505. let sphere = result < 10 ? 1 : 10;
  2506. call.args.amount = sphere;
  2507. for (let count = openChests - sphere; count > 0; count -= sphere) {
  2508. if (count < 10) sphere = 1;
  2509. const ident = artifactChestOpenCallName + "_" + count;
  2510. testData.calls.push({
  2511. name: artifactChestOpenCallName,
  2512. args: {
  2513. amount: sphere,
  2514. free: true,
  2515. },
  2516. ident: ident
  2517. });
  2518. if (!Array.isArray(requestHistory[this.uniqid].calls[call.name])) {
  2519. requestHistory[this.uniqid].calls[call.name] = [requestHistory[this.uniqid].calls[call.name]];
  2520. }
  2521. requestHistory[this.uniqid].calls[call.name].push(ident);
  2522. }
  2523.  
  2524. const consumableId = call.name == 'artifactChestOpen' ? 45 : 55;
  2525. cheats.updateInventory({
  2526. consumable: {
  2527. [consumableId]: -(openChests - startAmount),
  2528. },
  2529. });
  2530. artifactChestOpen = true;
  2531. changeRequest = true;
  2532. }
  2533. }
  2534. if (call.name == 'consumableUseLootBox') {
  2535. lastRussianDollId = call.args.libId;
  2536. /**
  2537. * Specify quantity for gold caskets
  2538. * Указать количество для золотых шкатулок
  2539. */
  2540. if (isChecked('countControl') &&
  2541. call.args.libId == 148 &&
  2542. call.args.amount > 1) {
  2543. const result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2544. { msg: I18N('BTN_OPEN'), isInput: true, default: call.args.amount},
  2545. ]);
  2546. call.args.amount = result;
  2547. changeRequest = true;
  2548. }
  2549. if (isChecked('countControl') && call.args.libId >= 362 && call.args.libId <= 389) {
  2550. this.massOpen = call.args.libId;
  2551. }
  2552. }
  2553. if (call.name == 'invasion_bossStart' && isChecked('tryFixIt_v2')) {
  2554. const { invasionInfo, invasionDataPacks } = HWHData;
  2555. if (call.args.id == invasionInfo.id) {
  2556. const pack = invasionDataPacks[invasionInfo.bossLvl];
  2557. if (pack) {
  2558. if (pack.buff != invasionInfo.buff) {
  2559. setProgress(
  2560. I18N('INVASION_BOSS_BUFF', {
  2561. bossLvl: invasionInfo.bossLvl,
  2562. needBuff: pack.buff,
  2563. haveBuff: invasionInfo.buff,
  2564. }),
  2565. false
  2566. );
  2567. } else {
  2568. call.args.pet = pack.pet;
  2569. call.args.heroes = pack.heroes;
  2570. call.args.favor = pack.favor;
  2571. changeRequest = true;
  2572. }
  2573. }
  2574. }
  2575. }
  2576. if (call.name == 'workshopBuff_create') {
  2577. const { invasionInfo, invasionDataPacks } = HWHData;
  2578. const pack = invasionDataPacks[invasionInfo.bossLvl];
  2579. if (pack) {
  2580. const addBuff = call.args.amount * 5;
  2581. if (pack.buff < addBuff + invasionInfo.buff) {
  2582. this.errorRequest = true;
  2583. }
  2584. setProgress(
  2585. I18N('INVASION_BOSS_BUFF', {
  2586. bossLvl: invasionInfo.bossLvl,
  2587. needBuff: pack.buff,
  2588. haveBuff: invasionInfo.buff,
  2589. }),
  2590. false
  2591. );
  2592. }
  2593. }
  2594. /**
  2595. * Changing the maximum number of raids in the campaign
  2596. * Изменение максимального количества рейдов в кампании
  2597. */
  2598. // if (call.name == 'missionRaid') {
  2599. // if (isChecked('countControl') && call.args.times > 1) {
  2600. // const result = +(await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2601. // { msg: I18N('BTN_RUN'), isInput: true, default: call.args.times },
  2602. // ]));
  2603. // call.args.times = result > call.args.times ? call.args.times : result;
  2604. // changeRequest = true;
  2605. // }
  2606. // }
  2607. }
  2608.  
  2609. let headers = requestHistory[this.uniqid].headers;
  2610. if (changeRequest) {
  2611. sourceData = JSON.stringify(testData);
  2612. headers['X-Auth-Signature'] = getSignature(headers, sourceData);
  2613. }
  2614.  
  2615. let signature = headers['X-Auth-Signature'];
  2616. if (signature) {
  2617. original.setRequestHeader.call(this, 'X-Auth-Signature', signature);
  2618. }
  2619. } catch (err) {
  2620. console.log("Request(send, " + this.uniqid + "):\n", sourceData, "Error:\n", err);
  2621. }
  2622. return sourceData;
  2623. }
  2624. /**
  2625. * Processing and substitution of incoming data
  2626. *
  2627. * Обработка и подмена входящих данных
  2628. */
  2629. async function checkChangeResponse(response) {
  2630. try {
  2631. isChange = false;
  2632. let nowTime = Math.round(Date.now() / 1000);
  2633. callsIdent = requestHistory[this.uniqid].calls;
  2634. respond = JSON.parse(response);
  2635. /**
  2636. * If the request returned an error removes the error (removes synchronization errors)
  2637. * Если запрос вернул ошибку удаляет ошибку (убирает ошибки синхронизации)
  2638. */
  2639. if (respond.error) {
  2640. isChange = true;
  2641. console.error(respond.error);
  2642. if (isChecked('showErrors')) {
  2643. popup.confirm(I18N('ERROR_MSG', {
  2644. name: respond.error.name,
  2645. description: respond.error.description,
  2646. }));
  2647. }
  2648. if (respond.error.name != 'AccountBan') {
  2649. delete respond.error;
  2650. respond.results = [];
  2651. }
  2652. }
  2653. let mainReward = null;
  2654. const allReward = {};
  2655. let countTypeReward = 0;
  2656. let readQuestInfo = false;
  2657. for (const call of respond.results) {
  2658. /**
  2659. * Obtaining initial data for completing quests
  2660. * Получение исходных данных для выполнения квестов
  2661. */
  2662. if (readQuestInfo) {
  2663. questsInfo[call.ident] = call.result.response;
  2664. }
  2665. /**
  2666. * Getting a user ID
  2667. * Получение идетификатора пользователя
  2668. */
  2669. if (call.ident == callsIdent['registration']) {
  2670. userId = call.result.response.userId;
  2671. if (localStorage['userId'] != userId) {
  2672. localStorage['newGiftSendIds'] = '';
  2673. localStorage['userId'] = userId;
  2674. }
  2675. await openOrMigrateDatabase(userId);
  2676. readQuestInfo = true;
  2677. }
  2678. /**
  2679. * Hiding donation offers 1
  2680. * Скрываем предложения доната 1
  2681. */
  2682. if (call.ident == callsIdent['billingGetAll'] && getSaveVal('noOfferDonat')) {
  2683. const billings = call.result.response?.billings;
  2684. const bundle = call.result.response?.bundle;
  2685. if (billings && bundle) {
  2686. call.result.response.billings = call.result.response.billings.filter((e) => ['repeatableOffer'].includes(e.type));
  2687. call.result.response.bundle = [];
  2688. isChange = true;
  2689. }
  2690. }
  2691. /**
  2692. * Hiding donation offers 2
  2693. * Скрываем предложения доната 2
  2694. */
  2695. if (getSaveVal('noOfferDonat') &&
  2696. (call.ident == callsIdent['offerGetAll'] ||
  2697. call.ident == callsIdent['specialOffer_getAll'])) {
  2698. let offers = call.result.response;
  2699. if (offers) {
  2700. call.result.response = offers.filter(
  2701. (e) => !['addBilling', 'bundleCarousel'].includes(e.type) || ['idleResource', 'stagesOffer'].includes(e.offerType)
  2702. );
  2703. isChange = true;
  2704. }
  2705. }
  2706. /**
  2707. * Hiding donation offers 3
  2708. * Скрываем предложения доната 3
  2709. */
  2710. if (getSaveVal('noOfferDonat') && call.result?.bundleUpdate) {
  2711. delete call.result.bundleUpdate;
  2712. isChange = true;
  2713. }
  2714. /**
  2715. * Hiding donation offers 4
  2716. * Скрываем предложения доната 4
  2717. */
  2718. if (call.result?.specialOffers) {
  2719. const offers = call.result.specialOffers;
  2720. call.result.specialOffers = offers.filter(
  2721. (e) => !['addBilling', 'bundleCarousel'].includes(e.type) || ['idleResource', 'stagesOffer'].includes(e.offerType)
  2722. );
  2723. isChange = true;
  2724. }
  2725. /**
  2726. * Copies a quiz question to the clipboard
  2727. * Копирует вопрос викторины в буфер обмена и получает на него ответ если есть
  2728. */
  2729. if (call.ident == callsIdent['quiz_getNewQuestion']) {
  2730. let quest = call.result.response;
  2731. console.log(quest.question);
  2732. copyText(quest.question);
  2733. setProgress(I18N('QUESTION_COPY'), true);
  2734. quest.lang = null;
  2735. if (typeof NXFlashVars !== 'undefined') {
  2736. quest.lang = NXFlashVars.interface_lang;
  2737. }
  2738. lastQuestion = quest;
  2739. if (isChecked('getAnswer')) {
  2740. const answer = await getAnswer(lastQuestion);
  2741. let showText = '';
  2742. if (answer) {
  2743. lastAnswer = answer;
  2744. console.log(answer);
  2745. showText = `${I18N('ANSWER_KNOWN')}: ${answer}`;
  2746. } else {
  2747. showText = I18N('ANSWER_NOT_KNOWN');
  2748. }
  2749.  
  2750. try {
  2751. const hint = hintQuest(quest);
  2752. if (hint) {
  2753. showText += I18N('HINT') + hint;
  2754. }
  2755. } catch (e) {}
  2756.  
  2757. setProgress(showText, true);
  2758. }
  2759. }
  2760. /**
  2761. * Submits a question with an answer to the database
  2762. * Отправляет вопрос с ответом в базу данных
  2763. */
  2764. if (call.ident == callsIdent['quiz_answer']) {
  2765. const answer = call.result.response;
  2766. if (lastQuestion) {
  2767. const answerInfo = {
  2768. answer,
  2769. question: lastQuestion,
  2770. lang: null,
  2771. };
  2772. if (typeof NXFlashVars !== 'undefined') {
  2773. answerInfo.lang = NXFlashVars.interface_lang;
  2774. }
  2775. lastQuestion = null;
  2776. setTimeout(sendAnswerInfo, 0, answerInfo);
  2777. }
  2778. }
  2779. /**
  2780. * Get user data
  2781. * Получить даныне пользователя
  2782. */
  2783. if (call.ident == callsIdent['userGetInfo']) {
  2784. let user = call.result.response;
  2785. document.title = user.name;
  2786. userInfo = Object.assign({}, user);
  2787. delete userInfo.refillable;
  2788. if (!questsInfo['userGetInfo']) {
  2789. questsInfo['userGetInfo'] = user;
  2790. }
  2791. }
  2792. /**
  2793. * Start of the battle for recalculation
  2794. * Начало боя для прерасчета
  2795. */
  2796. if (call.ident == callsIdent['clanWarAttack'] ||
  2797. call.ident == callsIdent['crossClanWar_startBattle'] ||
  2798. call.ident == callsIdent['bossAttack'] ||
  2799. call.ident == callsIdent['battleGetReplay'] ||
  2800. call.ident == callsIdent['brawl_startBattle'] ||
  2801. call.ident == callsIdent['adventureSolo_turnStartBattle'] ||
  2802. call.ident == callsIdent['invasion_bossStart'] ||
  2803. call.ident == callsIdent['titanArenaStartBattle'] ||
  2804. call.ident == callsIdent['towerStartBattle'] ||
  2805. call.ident == callsIdent['epicBrawl_startBattle'] ||
  2806. call.ident == callsIdent['adventure_turnStartBattle']) {
  2807. let battle = call.result.response.battle || call.result.response.replay;
  2808. if (call.ident == callsIdent['brawl_startBattle'] ||
  2809. call.ident == callsIdent['bossAttack'] ||
  2810. call.ident == callsIdent['towerStartBattle'] ||
  2811. call.ident == callsIdent['invasion_bossStart']) {
  2812. battle = call.result.response;
  2813. }
  2814. lastBattleInfo = battle;
  2815. if (call.ident == callsIdent['battleGetReplay'] && call.result.response.replay.type === "clan_raid") {
  2816. if (call?.result?.response?.replay?.result?.damage) {
  2817. const damages = Object.values(call.result.response.replay.result.damage);
  2818. const bossDamage = damages.reduce((a, v) => a + v, 0);
  2819. setProgress(I18N('BOSS_DAMAGE') + bossDamage.toLocaleString(), false, hideProgress);
  2820. continue;
  2821. }
  2822. }
  2823. if (!isChecked('preCalcBattle')) {
  2824. continue;
  2825. }
  2826. const preCalcBattle = structuredClone(battle);
  2827. setProgress(I18N('BEING_RECALC'));
  2828. let battleDuration = 120;
  2829. try {
  2830. const typeBattle = getBattleType(preCalcBattle.type);
  2831. battleDuration = +lib.data.battleConfig[typeBattle.split('_')[1]].config.battleDuration;
  2832. } catch (e) { }
  2833. //console.log(battle.type);
  2834. function getBattleInfo(battle, isRandSeed) {
  2835. return new Promise(function (resolve) {
  2836. if (isRandSeed) {
  2837. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  2838. }
  2839. BattleCalc(battle, getBattleType(battle.type), e => resolve(e));
  2840. });
  2841. }
  2842. let actions = [getBattleInfo(preCalcBattle, false)];
  2843. let countTestBattle = getInput('countTestBattle');
  2844. if (call.ident == callsIdent['invasion_bossStart'] ) {
  2845. countTestBattle = 0;
  2846. }
  2847. if (call.ident == callsIdent['battleGetReplay']) {
  2848. preCalcBattle.progress = [{ attackers: { input: ['auto', 0, 0, 'auto', 0, 0] } }];
  2849. }
  2850. for (let i = 0; i < countTestBattle; i++) {
  2851. actions.push(getBattleInfo(preCalcBattle, true));
  2852. }
  2853. Promise.all(actions)
  2854. .then(e => {
  2855. e = e.map(n => ({win: n.result.win, time: n.battleTime}));
  2856. let firstBattle = e.shift();
  2857. const timer = Math.floor(battleDuration - firstBattle.time);
  2858. const min = ('00' + Math.floor(timer / 60)).slice(-2);
  2859. const sec = ('00' + Math.floor(timer - min * 60)).slice(-2);
  2860. let msg = `${I18N('THIS_TIME')} ${firstBattle.win ? I18N('VICTORY') : I18N('DEFEAT')}`;
  2861. if (e.length) {
  2862. const countWin = e.reduce((w, s) => w + s.win, 0);
  2863. msg += ` ${I18N('CHANCE_TO_WIN')}: ${Math.floor((countWin / e.length) * 100)}% (${e.length})`;
  2864. }
  2865. msg += `, ${min}:${sec}`
  2866. setProgress(msg, false, hideProgress)
  2867. });
  2868. }
  2869. /**
  2870. * Start of the Asgard boss fight
  2871. * Начало боя с боссом Асгарда
  2872. */
  2873. if (call.ident == callsIdent['clanRaid_startBossBattle']) {
  2874. lastBossBattle = call.result.response.battle;
  2875. lastBossBattle.endTime = Date.now() + 160 * 1000;
  2876. if (isChecked('preCalcBattle')) {
  2877. const result = await Calc(lastBossBattle).then(e => e.progress[0].defenders.heroes[1].extra);
  2878. const bossDamage = result.damageTaken + result.damageTakenNextLevel;
  2879. setProgress(I18N('BOSS_DAMAGE') + bossDamage.toLocaleString(), false, hideProgress);
  2880. }
  2881. }
  2882. /**
  2883. * Cancel tutorial
  2884. * Отмена туториала
  2885. */
  2886. if (isCanceledTutorial && call.ident == callsIdent['tutorialGetInfo']) {
  2887. let chains = call.result.response.chains;
  2888. for (let n in chains) {
  2889. chains[n] = 9999;
  2890. }
  2891. isChange = true;
  2892. }
  2893. /**
  2894. * Opening keys and spheres of titan artifacts
  2895. * Открытие ключей и сфер артефактов титанов
  2896. */
  2897. if (artifactChestOpen &&
  2898. (call.ident == callsIdent[artifactChestOpenCallName] ||
  2899. (callsIdent[artifactChestOpenCallName] && callsIdent[artifactChestOpenCallName].includes(call.ident)))) {
  2900. let reward = call.result.response[artifactChestOpenCallName == 'artifactChestOpen' ? 'chestReward' : 'reward'];
  2901.  
  2902. reward.forEach(e => {
  2903. for (let f in e) {
  2904. if (!allReward[f]) {
  2905. allReward[f] = {};
  2906. }
  2907. for (let o in e[f]) {
  2908. if (!allReward[f][o]) {
  2909. allReward[f][o] = e[f][o];
  2910. countTypeReward++;
  2911. } else {
  2912. allReward[f][o] += e[f][o];
  2913. }
  2914. }
  2915. }
  2916. });
  2917.  
  2918. if (!call.ident.includes(artifactChestOpenCallName)) {
  2919. mainReward = call.result.response;
  2920. }
  2921. }
  2922.  
  2923. if (countTypeReward > 20) {
  2924. correctShowOpenArtifact = 3;
  2925. } else {
  2926. correctShowOpenArtifact = 0;
  2927. }
  2928. /**
  2929. * Sum the result of opening Pet Eggs
  2930. * Суммирование результата открытия яиц питомцев
  2931. */
  2932. if (isChecked('countControl') && call.ident == callsIdent['pet_chestOpen']) {
  2933. const rewards = call.result.response.rewards;
  2934. if (rewards.length > 10) {
  2935. /**
  2936. * Removing pet cards
  2937. * Убираем карточки петов
  2938. */
  2939. for (const reward of rewards) {
  2940. if (reward.petCard) {
  2941. delete reward.petCard;
  2942. }
  2943. }
  2944. }
  2945. rewards.forEach(e => {
  2946. for (let f in e) {
  2947. if (!allReward[f]) {
  2948. allReward[f] = {};
  2949. }
  2950. for (let o in e[f]) {
  2951. if (!allReward[f][o]) {
  2952. allReward[f][o] = e[f][o];
  2953. } else {
  2954. allReward[f][o] += e[f][o];
  2955. }
  2956. }
  2957. }
  2958. });
  2959. call.result.response.rewards = [allReward];
  2960. isChange = true;
  2961. }
  2962. /**
  2963. * Removing titan cards
  2964. * Убираем карточки титанов
  2965. */
  2966. if (call.ident == callsIdent['titanUseSummonCircle']) {
  2967. if (call.result.response.rewards.length > 10) {
  2968. for (const reward of call.result.response.rewards) {
  2969. if (reward.titanCard) {
  2970. delete reward.titanCard;
  2971. }
  2972. }
  2973. isChange = true;
  2974. }
  2975. }
  2976. /**
  2977. * Auto-repeat opening matryoshkas
  2978. * АвтоПовтор открытия матрешек
  2979. */
  2980. if (isChecked('countControl') && call.ident == callsIdent['consumableUseLootBox']) {
  2981. let [countLootBox, lootBox] = Object.entries(call.result.response).pop();
  2982. countLootBox = +countLootBox;
  2983. let newCount = 0;
  2984. if (lootBox?.consumable && lootBox.consumable[lastRussianDollId]) {
  2985. newCount += lootBox.consumable[lastRussianDollId];
  2986. delete lootBox.consumable[lastRussianDollId];
  2987. }
  2988. if (
  2989. newCount &&
  2990. (await popup.confirm(`${I18N('BTN_OPEN')} ${newCount} ${I18N('OPEN_DOLLS')}?`, [
  2991. { msg: I18N('BTN_OPEN'), result: true },
  2992. { msg: I18N('BTN_NO'), result: false, isClose: true },
  2993. ]))
  2994. ) {
  2995. const [count, recursionResult] = await openRussianDolls(lastRussianDollId, newCount);
  2996. countLootBox += +count;
  2997. mergeItemsObj(lootBox, recursionResult);
  2998. isChange = true;
  2999. }
  3000.  
  3001. if (this.massOpen) {
  3002. if (
  3003. await popup.confirm(I18N('OPEN_ALL_EQUIP_BOXES'), [
  3004. { msg: I18N('BTN_OPEN'), result: true },
  3005. { msg: I18N('BTN_NO'), result: false, isClose: true },
  3006. ])
  3007. ) {
  3008. const consumable = await Send({ calls: [{ name: 'inventoryGet', args: {}, ident: 'inventoryGet' }] }).then((e) =>
  3009. Object.entries(e.results[0].result.response.consumable)
  3010. );
  3011. const calls = [];
  3012. const deleteItems = {};
  3013. for (const [libId, amount] of consumable) {
  3014. if (libId != this.massOpen && libId >= 362 && libId <= 389) {
  3015. calls.push({
  3016. name: 'consumableUseLootBox',
  3017. args: { libId, amount },
  3018. ident: 'consumableUseLootBox_' + libId,
  3019. });
  3020. deleteItems[libId] = -amount;
  3021. }
  3022. }
  3023. const responses = await Send({ calls }).then((e) => e.results.map((r) => r.result.response).flat());
  3024.  
  3025. for (const loot of responses) {
  3026. const [count, result] = Object.entries(loot).pop();
  3027. countLootBox += +count;
  3028.  
  3029. mergeItemsObj(lootBox, result);
  3030. }
  3031. isChange = true;
  3032.  
  3033. this.onReadySuccess = () => {
  3034. cheats.updateInventory({ consumable: deleteItems });
  3035. cheats.refreshInventory();
  3036. };
  3037. }
  3038. }
  3039.  
  3040. if (isChange) {
  3041. call.result.response = {
  3042. [countLootBox]: lootBox,
  3043. };
  3044. }
  3045. }
  3046. /**
  3047. * Dungeon recalculation (fix endless cards)
  3048. * Прерасчет подземки (исправление бесконечных карт)
  3049. */
  3050. if (call.ident == callsIdent['dungeonStartBattle']) {
  3051. lastDungeonBattleData = call.result.response;
  3052. lastDungeonBattleStart = Date.now();
  3053. }
  3054. /**
  3055. * Getting the number of prediction cards
  3056. * Получение количества карт предсказаний
  3057. */
  3058. if (call.ident == callsIdent['inventoryGet']) {
  3059. countPredictionCard = call.result.response.consumable[81] || 0;
  3060. }
  3061. /**
  3062. * Getting subscription status
  3063. * Получение состояния подписки
  3064. */
  3065. if (call.ident == callsIdent['subscriptionGetInfo']) {
  3066. const subscription = call.result.response.subscription;
  3067. if (subscription) {
  3068. subEndTime = subscription.endTime * 1000;
  3069. }
  3070. }
  3071. /**
  3072. * Getting prediction cards
  3073. * Получение карт предсказаний
  3074. */
  3075. if (call.ident == callsIdent['questFarm']) {
  3076. const consumable = call.result.response?.consumable;
  3077. if (consumable && consumable[81]) {
  3078. countPredictionCard += consumable[81];
  3079. console.log(`Cards: ${countPredictionCard}`);
  3080. }
  3081. }
  3082. /**
  3083. * Hiding extra servers
  3084. * Скрытие лишних серверов
  3085. */
  3086. if (call.ident == callsIdent['serverGetAll'] && isChecked('hideServers')) {
  3087. let servers = call.result.response.users.map(s => s.serverId)
  3088. call.result.response.servers = call.result.response.servers.filter(s => servers.includes(s.id));
  3089. isChange = true;
  3090. }
  3091. /**
  3092. * Displays player positions in the adventure
  3093. * Отображает позиции игроков в приключении
  3094. */
  3095. if (call.ident == callsIdent['adventure_getLobbyInfo']) {
  3096. const users = Object.values(call.result.response.users);
  3097. const mapIdent = call.result.response.mapIdent;
  3098. const adventureId = call.result.response.adventureId;
  3099. const maps = {
  3100. adv_strongford_3pl_hell: 9,
  3101. adv_valley_3pl_hell: 10,
  3102. adv_ghirwil_3pl_hell: 11,
  3103. adv_angels_3pl_hell: 12,
  3104. }
  3105. let msg = I18N('MAP') + (mapIdent in maps ? maps[mapIdent] : adventureId);
  3106. msg += '<br>' + I18N('PLAYER_POS');
  3107. for (const user of users) {
  3108. msg += `<br>${user.user.name} - ${user.currentNode}`;
  3109. }
  3110. setProgress(msg, false, hideProgress);
  3111. }
  3112. /**
  3113. * Automatic launch of a raid at the end of the adventure
  3114. * Автоматический запуск рейда при окончании приключения
  3115. */
  3116. if (call.ident == callsIdent['adventure_end']) {
  3117. autoRaidAdventure()
  3118. }
  3119. /** Удаление лавки редкостей */
  3120. if (call.ident == callsIdent['missionRaid']) {
  3121. if (call.result?.heroesMerchant) {
  3122. delete call.result.heroesMerchant;
  3123. isChange = true;
  3124. }
  3125. }
  3126. /** missionTimer */
  3127. if (call.ident == callsIdent['missionStart']) {
  3128. missionBattle = call.result.response;
  3129. }
  3130. /** Награды турнира стихий */
  3131. if (call.ident == callsIdent['hallOfFameGetTrophies']) {
  3132. const trophys = call.result.response;
  3133. const calls = [];
  3134. for (const week in trophys) {
  3135. const trophy = trophys[week];
  3136. if (!trophy.championRewardFarmed) {
  3137. calls.push({
  3138. name: 'hallOfFameFarmTrophyReward',
  3139. args: { trophyId: week, rewardType: 'champion' },
  3140. ident: 'body_champion_' + week,
  3141. });
  3142. }
  3143. if (Object.keys(trophy.clanReward).length && !trophy.clanRewardFarmed) {
  3144. calls.push({
  3145. name: 'hallOfFameFarmTrophyReward',
  3146. args: { trophyId: week, rewardType: 'clan' },
  3147. ident: 'body_clan_' + week,
  3148. });
  3149. }
  3150. }
  3151. if (calls.length) {
  3152. Send({ calls })
  3153. .then((e) => e.results.map((e) => e.result.response))
  3154. .then(async results => {
  3155. let coin18 = 0,
  3156. coin19 = 0,
  3157. gold = 0,
  3158. starmoney = 0;
  3159. for (const r of results) {
  3160. coin18 += r?.coin ? +r.coin[18] : 0;
  3161. coin19 += r?.coin ? +r.coin[19] : 0;
  3162. gold += r?.gold ? +r.gold : 0;
  3163. starmoney += r?.starmoney ? +r.starmoney : 0;
  3164. }
  3165.  
  3166. let msg = I18N('ELEMENT_TOURNAMENT_REWARD') + '<br>';
  3167. if (coin18) {
  3168. msg += cheats.translate('LIB_COIN_NAME_18') + `: ${coin18}<br>`;
  3169. }
  3170. if (coin19) {
  3171. msg += cheats.translate('LIB_COIN_NAME_19') + `: ${coin19}<br>`;
  3172. }
  3173. if (gold) {
  3174. msg += cheats.translate('LIB_PSEUDO_COIN') + `: ${gold}<br>`;
  3175. }
  3176. if (starmoney) {
  3177. msg += cheats.translate('LIB_PSEUDO_STARMONEY') + `: ${starmoney}<br>`;
  3178. }
  3179.  
  3180. await popup.confirm(msg, [{ msg: I18N('BTN_OK'), result: 0 }]);
  3181. });
  3182. }
  3183. }
  3184. if (call.ident == callsIdent['clanDomination_getInfo']) {
  3185. clanDominationGetInfo = call.result.response;
  3186. }
  3187. if (call.ident == callsIdent['clanRaid_endBossBattle']) {
  3188. console.log(call.result.response);
  3189. const damage = Object.values(call.result.response.damage).reduce((a, e) => a + e);
  3190. if (call.result.response.result.afterInvalid) {
  3191. addProgress('<br>' + I18N('SERVER_NOT_ACCEPT'));
  3192. }
  3193. addProgress('<br>Server > ' + I18N('BOSS_DAMAGE') + damage.toLocaleString());
  3194. }
  3195. if (call.ident == callsIdent['invasion_getInfo']) {
  3196. const r = call.result.response;
  3197. if (r?.actions?.length) {
  3198. const { invasionInfo, invasionDataPacks } = HWHData;
  3199. const boss = r.actions.find((e) => e.payload.id === invasionInfo.id);
  3200. if (boss) {
  3201. invasionInfo.buff = r.buffAmount;
  3202. invasionInfo.bossLvl = boss.payload.level;
  3203. if (isChecked('tryFixIt_v2')) {
  3204. const pack = invasionDataPacks[invasionInfo.bossLvl];
  3205. if (pack) {
  3206. setProgress(
  3207. I18N('INVASION_BOSS_BUFF', {
  3208. bossLvl: invasionInfo.bossLvl,
  3209. needBuff: pack.buff,
  3210. haveBuff: invasionInfo.buff,
  3211. }),
  3212. false
  3213. );
  3214. }
  3215. }
  3216. }
  3217. }
  3218. }
  3219. if (call.ident == callsIdent['workshopBuff_create']) {
  3220. const r = call.result.response;
  3221. if (r.id == 1) {
  3222. const { invasionInfo, invasionDataPacks } = HWHData;
  3223. invasionInfo.buff = r.amount;
  3224. if (isChecked('tryFixIt_v2')) {
  3225. const pack = invasionDataPacks[invasionInfo.bossLvl];
  3226. if (pack) {
  3227. setProgress(
  3228. I18N('INVASION_BOSS_BUFF', {
  3229. bossLvl: invasionInfo.bossLvl,
  3230. needBuff: pack.buff,
  3231. haveBuff: invasionInfo.buff,
  3232. }),
  3233. false
  3234. );
  3235. }
  3236. }
  3237. }
  3238. }
  3239. /*
  3240. if (call.ident == callsIdent['chatGetAll'] && call.args.chatType == 'clanDomination' && !callsIdent['clanDomination_mapState']) {
  3241. this.onReadySuccess = async function () {
  3242. const result = await Send({
  3243. calls: [
  3244. {
  3245. name: 'clanDomination_mapState',
  3246. args: {},
  3247. ident: 'clanDomination_mapState',
  3248. },
  3249. ],
  3250. }).then((e) => e.results[0].result.response);
  3251. let townPositions = result.townPositions;
  3252. let positions = {};
  3253. for (let pos in townPositions) {
  3254. let townPosition = townPositions[pos];
  3255. positions[townPosition.position] = townPosition;
  3256. }
  3257. Object.assign(clanDominationGetInfo, {
  3258. townPositions: positions,
  3259. });
  3260. let userPositions = result.userPositions;
  3261. for (let pos in clanDominationGetInfo.townPositions) {
  3262. let townPosition = clanDominationGetInfo.townPositions[pos];
  3263. if (townPosition.status) {
  3264. userPositions[townPosition.userId] = +pos;
  3265. }
  3266. }
  3267. cheats.updateMap(result);
  3268. };
  3269. }
  3270. if (call.ident == callsIdent['clanDomination_mapState']) {
  3271. const townPositions = call.result.response.townPositions;
  3272. const userPositions = call.result.response.userPositions;
  3273. for (let pos in townPositions) {
  3274. let townPos = townPositions[pos];
  3275. if (townPos.status) {
  3276. userPositions[townPos.userId] = townPos.position;
  3277. }
  3278. }
  3279. isChange = true;
  3280. }
  3281. */
  3282. }
  3283.  
  3284. if (mainReward && artifactChestOpen) {
  3285. console.log(allReward);
  3286. mainReward[artifactChestOpenCallName == 'artifactChestOpen' ? 'chestReward' : 'reward'] = [allReward];
  3287. artifactChestOpen = false;
  3288. artifactChestOpenCallName = '';
  3289. isChange = true;
  3290. }
  3291. } catch(err) {
  3292. console.log("Request(response, " + this.uniqid + "):\n", "Error:\n", response, err);
  3293. }
  3294.  
  3295. if (isChange) {
  3296. Object.defineProperty(this, 'responseText', {
  3297. writable: true
  3298. });
  3299. this.responseText = JSON.stringify(respond);
  3300. }
  3301. }
  3302.  
  3303. /**
  3304. * Request an answer to a question
  3305. *
  3306. * Запрос ответа на вопрос
  3307. */
  3308. async function getAnswer(question) {
  3309. // c29tZSBzdHJhbmdlIHN5bWJvbHM=
  3310. const quizAPI = new ZingerYWebsiteAPI('getAnswer.php', arguments, { question });
  3311. return new Promise((resolve, reject) => {
  3312. quizAPI.request().then((data) => {
  3313. if (data.result) {
  3314. resolve(data.result);
  3315. } else {
  3316. resolve(false);
  3317. }
  3318. }).catch((error) => {
  3319. console.error(error);
  3320. resolve(false);
  3321. });
  3322. })
  3323. }
  3324.  
  3325. /**
  3326. * Submitting a question and answer to a database
  3327. *
  3328. * Отправка вопроса и ответа в базу данных
  3329. */
  3330. function sendAnswerInfo(answerInfo) {
  3331. // c29tZSBub25zZW5zZQ==
  3332. const quizAPI = new ZingerYWebsiteAPI('setAnswer.php', arguments, { answerInfo });
  3333. quizAPI.request().then((data) => {
  3334. if (data.result) {
  3335. console.log(I18N('SENT_QUESTION'));
  3336. }
  3337. });
  3338. }
  3339.  
  3340. /**
  3341. * Returns the battle type by preset type
  3342. *
  3343. * Возвращает тип боя по типу пресета
  3344. */
  3345. function getBattleType(strBattleType) {
  3346. if (!strBattleType) {
  3347. return null;
  3348. }
  3349. switch (strBattleType) {
  3350. case 'titan_pvp':
  3351. return 'get_titanPvp';
  3352. case 'titan_pvp_manual':
  3353. case 'titan_clan_pvp':
  3354. case 'clan_pvp_titan':
  3355. case 'clan_global_pvp_titan':
  3356. case 'brawl_titan':
  3357. case 'challenge_titan':
  3358. case 'titan_mission':
  3359. return 'get_titanPvpManual';
  3360. case 'clan_raid': // Asgard Boss // Босс асгарда
  3361. case 'adventure': // Adventures // Приключения
  3362. case 'clan_global_pvp':
  3363. case 'epic_brawl':
  3364. case 'clan_pvp':
  3365. return 'get_clanPvp';
  3366. case 'dungeon_titan':
  3367. case 'titan_tower':
  3368. return 'get_titan';
  3369. case 'tower':
  3370. case 'clan_dungeon':
  3371. return 'get_tower';
  3372. case 'pve':
  3373. case 'mission':
  3374. return 'get_pve';
  3375. case 'mission_boss':
  3376. return 'get_missionBoss';
  3377. case 'challenge':
  3378. case 'pvp_manual':
  3379. return 'get_pvpManual';
  3380. case 'grand':
  3381. case 'arena':
  3382. case 'pvp':
  3383. case 'clan_domination':
  3384. return 'get_pvp';
  3385. case 'core':
  3386. return 'get_core';
  3387. default: {
  3388. if (strBattleType.includes('invasion')) {
  3389. return 'get_invasion';
  3390. }
  3391. if (strBattleType.includes('boss')) {
  3392. return 'get_boss';
  3393. }
  3394. if (strBattleType.includes('titan_arena')) {
  3395. return 'get_titanPvpManual';
  3396. }
  3397. return 'get_clanPvp';
  3398. }
  3399. }
  3400. }
  3401. /**
  3402. * Returns the class name of the passed object
  3403. *
  3404. * Возвращает название класса переданного объекта
  3405. */
  3406. function getClass(obj) {
  3407. return {}.toString.call(obj).slice(8, -1);
  3408. }
  3409. /**
  3410. * Calculates the request signature
  3411. *
  3412. * Расчитывает сигнатуру запроса
  3413. */
  3414. this.getSignature = function(headers, data) {
  3415. const sign = {
  3416. signature: '',
  3417. length: 0,
  3418. add: function (text) {
  3419. this.signature += text;
  3420. if (this.length < this.signature.length) {
  3421. this.length = 3 * (this.signature.length + 1) >> 1;
  3422. }
  3423. },
  3424. }
  3425. sign.add(headers["X-Request-Id"]);
  3426. sign.add(':');
  3427. sign.add(headers["X-Auth-Token"]);
  3428. sign.add(':');
  3429. sign.add(headers["X-Auth-Session-Id"]);
  3430. sign.add(':');
  3431. sign.add(data);
  3432. sign.add(':');
  3433. sign.add('LIBRARY-VERSION=1');
  3434. sign.add('UNIQUE-SESSION-ID=' + headers["X-Env-Unique-Session-Id"]);
  3435.  
  3436. return md5(sign.signature);
  3437. }
  3438.  
  3439. class HotkeyManager {
  3440. constructor() {
  3441. if (HotkeyManager.instance) {
  3442. return HotkeyManager.instance;
  3443. }
  3444. this.hotkeys = [];
  3445. document.addEventListener('keydown', this.handleKeyDown.bind(this));
  3446. HotkeyManager.instance = this;
  3447. }
  3448.  
  3449. handleKeyDown(event) {
  3450. const key = event.key.toLowerCase();
  3451. const mods = {
  3452. ctrl: event.ctrlKey,
  3453. alt: event.altKey,
  3454. shift: event.shiftKey,
  3455. };
  3456.  
  3457. this.hotkeys.forEach((hotkey) => {
  3458. if (hotkey.key === key && hotkey.ctrl === mods.ctrl && hotkey.alt === mods.alt && hotkey.shift === mods.shift) {
  3459. hotkey.callback(hotkey);
  3460. }
  3461. });
  3462. }
  3463.  
  3464. add(key, opt = {}, callback) {
  3465. this.hotkeys.push({
  3466. key: key.toLowerCase(),
  3467. callback,
  3468. ctrl: opt.ctrl || false,
  3469. alt: opt.alt || false,
  3470. shift: opt.shift || false,
  3471. });
  3472. }
  3473.  
  3474. remove(key, opt = {}) {
  3475. this.hotkeys = this.hotkeys.filter((hotkey) => {
  3476. return !(
  3477. hotkey.key === key.toLowerCase() &&
  3478. hotkey.ctrl === (opt.ctrl || false) &&
  3479. hotkey.alt === (opt.alt || false) &&
  3480. hotkey.shift === (opt.shift || false)
  3481. );
  3482. });
  3483. }
  3484.  
  3485. static getInst() {
  3486. if (!HotkeyManager.instance) {
  3487. new HotkeyManager();
  3488. }
  3489. return HotkeyManager.instance;
  3490. }
  3491. }
  3492.  
  3493. class MouseClicker {
  3494. constructor(element) {
  3495. if (MouseClicker.instance) {
  3496. return MouseClicker.instance;
  3497. }
  3498. this.element = element;
  3499. this.mouse = {
  3500. bubbles: true,
  3501. cancelable: true,
  3502. clientX: 0,
  3503. clientY: 0,
  3504. };
  3505. this.element.addEventListener('mousemove', this.handleMouseMove.bind(this));
  3506. this.clickInfo = {};
  3507. this.nextTimeoutId = 1;
  3508. MouseClicker.instance = this;
  3509. }
  3510.  
  3511. handleMouseMove(event) {
  3512. this.mouse.clientX = event.clientX;
  3513. this.mouse.clientY = event.clientY;
  3514. }
  3515.  
  3516. click(options) {
  3517. options = options || this.mouse;
  3518. this.element.dispatchEvent(new MouseEvent('mousedown', options));
  3519. this.element.dispatchEvent(new MouseEvent('mouseup', options));
  3520. }
  3521.  
  3522. start(interval = 1000, clickCount = Infinity) {
  3523. const currentMouse = { ...this.mouse };
  3524. const timeoutId = this.nextTimeoutId++;
  3525. let count = 0;
  3526.  
  3527. const clickTimeout = () => {
  3528. this.click(currentMouse);
  3529. count++;
  3530. if (count < clickCount) {
  3531. this.clickInfo[timeoutId].timeout = setTimeout(clickTimeout, interval);
  3532. } else {
  3533. delete this.clickInfo[timeoutId];
  3534. }
  3535. };
  3536.  
  3537. this.clickInfo[timeoutId] = {
  3538. timeout: setTimeout(clickTimeout, interval),
  3539. count: clickCount,
  3540. };
  3541. return timeoutId;
  3542. }
  3543.  
  3544. stop(timeoutId) {
  3545. if (this.clickInfo[timeoutId]) {
  3546. clearTimeout(this.clickInfo[timeoutId].timeout);
  3547. delete this.clickInfo[timeoutId];
  3548. }
  3549. }
  3550.  
  3551. stopAll() {
  3552. for (const timeoutId in this.clickInfo) {
  3553. clearTimeout(this.clickInfo[timeoutId].timeout);
  3554. }
  3555. this.clickInfo = {};
  3556. }
  3557.  
  3558. static getInst(element) {
  3559. if (!MouseClicker.instance) {
  3560. new MouseClicker(element);
  3561. }
  3562. return MouseClicker.instance;
  3563. }
  3564. }
  3565.  
  3566. let extintionsList = [];
  3567. /**
  3568. * Creates an interface
  3569. *
  3570. * Создает интерфейс
  3571. */
  3572. function createInterface() {
  3573. popup.init();
  3574. const { ScriptMenu } = HWHClasses;
  3575. const scriptMenu = ScriptMenu.getInst();
  3576. scriptMenu.init();
  3577. scriptMenu.addHeader(GM_info.script.name, justInfo);
  3578. const versionHeader = scriptMenu.addHeader('v' + GM_info.script.version);
  3579. if (extintionsList.length) {
  3580. versionHeader.title = '';
  3581. versionHeader.style.color = 'red';
  3582. for (const extintion of extintionsList) {
  3583. const { name, ver, author } = extintion;
  3584. versionHeader.title += name + ', v' + ver + ' by ' + author + '\n';
  3585. }
  3586. }
  3587. // AutoClicker
  3588. const hkm = new HotkeyManager();
  3589. const fc = document.getElementById('flash-content') || document.getElementById('game');
  3590. const mc = new MouseClicker(fc);
  3591. function toggleClicker(self, timeout) {
  3592. if (self.onClick) {
  3593. console.log('Останавливаем клики');
  3594. mc.stop(self.onClick);
  3595. self.onClick = false;
  3596. } else {
  3597. console.log('Стартуем клики');
  3598. self.onClick = mc.start(timeout);
  3599. }
  3600. }
  3601. hkm.add('C', { ctrl: true, alt: true }, (self) => {
  3602. console.log('"Ctrl + Alt + C"');
  3603. toggleClicker(self, 20);
  3604. });
  3605. hkm.add('V', { ctrl: true, alt: true }, (self) => {
  3606. console.log('"Ctrl + Alt + V"');
  3607. toggleClicker(self, 100);
  3608. });
  3609. }
  3610.  
  3611. function addExtentionName(name, ver, author) {
  3612. extintionsList.push({
  3613. name,
  3614. ver,
  3615. author,
  3616. });
  3617. }
  3618.  
  3619. function addControls() {
  3620. createInterface();
  3621. const { ScriptMenu } = HWHClasses;
  3622. const scriptMenu = ScriptMenu.getInst();
  3623. const checkboxDetails = scriptMenu.addDetails(I18N('SETTINGS'), 'settings');
  3624. const { checkboxes } = HWHData;
  3625. for (let name in checkboxes) {
  3626. if (checkboxes[name].hide) {
  3627. continue;
  3628. }
  3629. checkboxes[name].cbox = scriptMenu.addCheckbox(checkboxes[name].label, checkboxes[name].title, checkboxDetails);
  3630. /**
  3631. * Getting the state of checkboxes from storage
  3632. * Получаем состояние чекбоксов из storage
  3633. */
  3634. let val = storage.get(name, null);
  3635. if (val != null) {
  3636. checkboxes[name].cbox.checked = val;
  3637. } else {
  3638. storage.set(name, checkboxes[name].default);
  3639. checkboxes[name].cbox.checked = checkboxes[name].default;
  3640. }
  3641. /**
  3642. * Tracing the change event of the checkbox for writing to storage
  3643. * Отсеживание события изменения чекбокса для записи в storage
  3644. */
  3645. checkboxes[name].cbox.dataset['name'] = name;
  3646. checkboxes[name].cbox.addEventListener('change', async function (event) {
  3647. const nameCheckbox = this.dataset['name'];
  3648. /*
  3649. if (this.checked && nameCheckbox == 'cancelBattle') {
  3650. this.checked = false;
  3651. if (await popup.confirm(I18N('MSG_BAN_ATTENTION'), [
  3652. { msg: I18N('BTN_NO_I_AM_AGAINST'), result: true },
  3653. { msg: I18N('BTN_YES_I_AGREE'), result: false },
  3654. ])) {
  3655. return;
  3656. }
  3657. this.checked = true;
  3658. }
  3659. */
  3660. storage.set(nameCheckbox, this.checked);
  3661. })
  3662. }
  3663.  
  3664. const inputDetails = scriptMenu.addDetails(I18N('VALUES'), 'values');
  3665. const { inputs } = HWHData;
  3666. for (let name in inputs) {
  3667. inputs[name].input = scriptMenu.addInputText(inputs[name].title, false, inputDetails);
  3668. /**
  3669. * Get inputText state from storage
  3670. * Получаем состояние inputText из storage
  3671. */
  3672. let val = storage.get(name, null);
  3673. if (val != null) {
  3674. inputs[name].input.value = val;
  3675. } else {
  3676. storage.set(name, inputs[name].default);
  3677. inputs[name].input.value = inputs[name].default;
  3678. }
  3679. /**
  3680. * Tracing a field change event for a record in storage
  3681. * Отсеживание события изменения поля для записи в storage
  3682. */
  3683. inputs[name].input.dataset['name'] = name;
  3684. inputs[name].input.addEventListener('input', function () {
  3685. const inputName = this.dataset['name'];
  3686. let value = +this.value;
  3687. if (!value || Number.isNaN(value)) {
  3688. value = storage.get(inputName, inputs[inputName].default);
  3689. inputs[name].input.value = value;
  3690. }
  3691. storage.set(inputName, value);
  3692. })
  3693. }
  3694. }
  3695.  
  3696. /**
  3697. * Sending a request
  3698. *
  3699. * Отправка запроса
  3700. */
  3701. function send(json, callback, pr) {
  3702. if (typeof json == 'string') {
  3703. json = JSON.parse(json);
  3704. }
  3705. for (const call of json.calls) {
  3706. if (!call?.context?.actionTs) {
  3707. call.context = {
  3708. actionTs: Math.floor(performance.now())
  3709. }
  3710. }
  3711. }
  3712. json = JSON.stringify(json);
  3713. /**
  3714. * We get the headlines of the previous intercepted request
  3715. * Получаем заголовки предыдущего перехваченого запроса
  3716. */
  3717. let headers = lastHeaders;
  3718. /**
  3719. * We increase the header of the query Certifier by 1
  3720. * Увеличиваем заголовок идетификатора запроса на 1
  3721. */
  3722. headers["X-Request-Id"]++;
  3723. /**
  3724. * We calculate the title with the signature
  3725. * Расчитываем заголовок с сигнатурой
  3726. */
  3727. headers["X-Auth-Signature"] = getSignature(headers, json);
  3728. /**
  3729. * Create a new ajax request
  3730. * Создаем новый AJAX запрос
  3731. */
  3732. let xhr = new XMLHttpRequest;
  3733. /**
  3734. * Indicate the previously saved URL for API queries
  3735. * Указываем ранее сохраненный URL для API запросов
  3736. */
  3737. xhr.open('POST', apiUrl, true);
  3738. /**
  3739. * Add the function to the event change event
  3740. * Добавляем функцию к событию смены статуса запроса
  3741. */
  3742. xhr.onreadystatechange = function() {
  3743. /**
  3744. * If the result of the request is obtained, we call the flask function
  3745. * Если результат запроса получен вызываем колбек функцию
  3746. */
  3747. if(xhr.readyState == 4) {
  3748. callback(xhr.response, pr);
  3749. }
  3750. };
  3751. /**
  3752. * Indicate the type of request
  3753. * Указываем тип запроса
  3754. */
  3755. xhr.responseType = 'json';
  3756. /**
  3757. * We set the request headers
  3758. * Задаем заголовки запроса
  3759. */
  3760. for(let nameHeader in headers) {
  3761. let head = headers[nameHeader];
  3762. xhr.setRequestHeader(nameHeader, head);
  3763. }
  3764. /**
  3765. * Sending a request
  3766. * Отправляем запрос
  3767. */
  3768. xhr.send(json);
  3769. }
  3770.  
  3771. let hideTimeoutProgress = 0;
  3772. /**
  3773. * Hide progress
  3774. *
  3775. * Скрыть прогресс
  3776. */
  3777. function hideProgress(timeout) {
  3778. const { ScriptMenu } = HWHClasses;
  3779. const scriptMenu = ScriptMenu.getInst();
  3780. timeout = timeout || 0;
  3781. clearTimeout(hideTimeoutProgress);
  3782. hideTimeoutProgress = setTimeout(function () {
  3783. scriptMenu.setStatus('');
  3784. }, timeout);
  3785. }
  3786. /**
  3787. * Progress display
  3788. *
  3789. * Отображение прогресса
  3790. */
  3791. function setProgress(text, hide, onclick) {
  3792. const { ScriptMenu } = HWHClasses;
  3793. const scriptMenu = ScriptMenu.getInst();
  3794. scriptMenu.setStatus(text, onclick);
  3795. hide = hide || false;
  3796. if (hide) {
  3797. hideProgress(3000);
  3798. }
  3799. }
  3800.  
  3801. /**
  3802. * Progress added
  3803. *
  3804. * Дополнение прогресса
  3805. */
  3806. function addProgress(text) {
  3807. const { ScriptMenu } = HWHClasses;
  3808. const scriptMenu = ScriptMenu.getInst();
  3809. scriptMenu.addStatus(text);
  3810. }
  3811.  
  3812. /**
  3813. * Returns the timer value depending on the subscription
  3814. *
  3815. * Возвращает значение таймера в зависимости от подписки
  3816. */
  3817. function getTimer(time, div) {
  3818. let speedDiv = 5;
  3819. if (subEndTime < Date.now()) {
  3820. speedDiv = div || 1.5;
  3821. }
  3822. return Math.max(Math.ceil(time / speedDiv + 1.5), 4);
  3823. }
  3824.  
  3825. function startSlave() {
  3826. const { slaveFixBattle } = HWHClasses;
  3827. const sFix = new slaveFixBattle();
  3828. sFix.wsStart();
  3829. }
  3830.  
  3831. this.testFuntions = {
  3832. hideProgress,
  3833. setProgress,
  3834. addProgress,
  3835. masterFix: false,
  3836. startSlave,
  3837. };
  3838.  
  3839. this.HWHFuncs = {
  3840. send,
  3841. I18N,
  3842. isChecked,
  3843. getInput,
  3844. copyText,
  3845. confShow,
  3846. hideProgress,
  3847. setProgress,
  3848. addProgress,
  3849. getTimer,
  3850. addExtentionName,
  3851. getUserInfo,
  3852. setIsCancalBattle,
  3853. random,
  3854. };
  3855.  
  3856. this.HWHClasses = {
  3857. checkChangeSend,
  3858. checkChangeResponse,
  3859. };
  3860.  
  3861. this.HWHData = {
  3862. i18nLangData,
  3863. checkboxes,
  3864. inputs,
  3865. buttons,
  3866. invasionInfo,
  3867. invasionDataPacks,
  3868. };
  3869.  
  3870. /**
  3871. * Calculates HASH MD5 from string
  3872. *
  3873. * Расчитывает HASH MD5 из строки
  3874. *
  3875. * [js-md5]{@link https://github.com/emn178/js-md5}
  3876. *
  3877. * @namespace md5
  3878. * @version 0.7.3
  3879. * @author Chen, Yi-Cyuan [emn178@gmail.com]
  3880. * @copyright Chen, Yi-Cyuan 2014-2017
  3881. * @license MIT
  3882. */
  3883. !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 _}))}();
  3884.  
  3885. class Caller {
  3886. static globalHooks = {
  3887. onError: null,
  3888. };
  3889.  
  3890. constructor(calls = null) {
  3891. this.calls = [];
  3892. this.results = {};
  3893. if (calls) {
  3894. this.add(calls);
  3895. }
  3896. }
  3897.  
  3898. static setGlobalHook(event, callback) {
  3899. if (this.globalHooks[event] !== undefined) {
  3900. this.globalHooks[event] = callback;
  3901. } else {
  3902. throw new Error(`Unknown event: ${event}`);
  3903. }
  3904. }
  3905.  
  3906. addCall(call) {
  3907. const { name = call, args = {} } = typeof call === 'object' ? call : { name: call };
  3908. this.calls.push({ name, args });
  3909. return this;
  3910. }
  3911.  
  3912. add(name) {
  3913. if (Array.isArray(name)) {
  3914. name.forEach((call) => this.addCall(call));
  3915. } else {
  3916. this.addCall(name);
  3917. }
  3918. return this;
  3919. }
  3920.  
  3921. handleError(error) {
  3922. const errorName = error.name;
  3923. const errorDescription = error.description;
  3924.  
  3925. if (Caller.globalHooks.onError) {
  3926. const shouldThrow = Caller.globalHooks.onError(error);
  3927. if (shouldThrow === false) {
  3928. return;
  3929. }
  3930. }
  3931.  
  3932. if (error.call) {
  3933. const callInfo = error.call;
  3934. throw new Error(`${errorName} in ${callInfo.name}: ${errorDescription}\n` + `Args: ${JSON.stringify(callInfo.args)}\n`);
  3935. } else if (errorName === 'common\\rpc\\exception\\InvalidRequest') {
  3936. throw new Error(`Invalid request: ${errorDescription}`);
  3937. } else {
  3938. throw new Error(`Unknown error: ${errorName} - ${errorDescription}`);
  3939. }
  3940. }
  3941.  
  3942. async send() {
  3943. if (!this.calls.length) {
  3944. throw new Error('No calls to send.');
  3945. }
  3946.  
  3947. const identToNameMap = {};
  3948. const callsWithIdent = this.calls.map((call, index) => {
  3949. const ident = this.calls.length === 1 ? 'body' : `group_${index}_body`;
  3950. identToNameMap[ident] = call.name;
  3951. return { ...call, ident };
  3952. });
  3953.  
  3954. try {
  3955. const response = await Send({ calls: callsWithIdent });
  3956.  
  3957. if (response.error) {
  3958. this.handleError(response.error);
  3959. }
  3960.  
  3961. if (!response.results) {
  3962. throw new Error('Invalid response format: missing "results" field');
  3963. }
  3964.  
  3965. response.results.forEach((result) => {
  3966. const name = identToNameMap[result.ident];
  3967. if (!this.results[name]) {
  3968. this.results[name] = [];
  3969. }
  3970. this.results[name].push(result.result.response);
  3971. });
  3972. } catch (error) {
  3973. throw error;
  3974. }
  3975. return this;
  3976. }
  3977.  
  3978. result(name, forceArray = false) {
  3979. const results = name ? this.results[name] || [] : Object.values(this.results).flat();
  3980. return forceArray || results.length !== 1 ? results : results[0];
  3981. }
  3982.  
  3983. async execute(name) {
  3984. try {
  3985. await this.send();
  3986. return this.result(name);
  3987. } catch (error) {
  3988. throw error;
  3989. }
  3990. }
  3991.  
  3992. clear() {
  3993. this.calls = [];
  3994. this.results = {};
  3995. return this;
  3996. }
  3997.  
  3998. isEmpty() {
  3999. return this.calls.length === 0 && Object.keys(this.results).length === 0;
  4000. }
  4001.  
  4002. static async send(calls) {
  4003. return new Caller(calls).execute();
  4004. }
  4005. }
  4006.  
  4007. this.Caller = Caller;
  4008.  
  4009. /*
  4010. // Примеры использования
  4011. (async () => {
  4012. // Короткий вызов
  4013. await new Caller('inventoryGet').execute();
  4014. // Простой вызов
  4015. let result = await new Caller().add('inventoryGet').execute();
  4016. console.log('Inventory Get Result:', result);
  4017.  
  4018. // Сложный вызов
  4019. let caller = new Caller();
  4020. await caller
  4021. .add([
  4022. {
  4023. name: 'inventoryGet',
  4024. args: {},
  4025. },
  4026. {
  4027. name: 'heroGetAll',
  4028. args: {},
  4029. },
  4030. ])
  4031. .send();
  4032. console.log('Inventory Get Result:', caller.result('inventoryGet'));
  4033. console.log('Hero Get All Result:', caller.result('heroGetAll'));
  4034.  
  4035. // Очистка всех данных
  4036. caller.clear();
  4037. })();
  4038. */
  4039.  
  4040. /**
  4041. * Script for beautiful dialog boxes
  4042. *
  4043. * Скрипт для красивых диалоговых окошек
  4044. */
  4045. const popup = new (function () {
  4046. this.popUp,
  4047. this.downer,
  4048. this.middle,
  4049. this.msgText,
  4050. this.buttons = [];
  4051. this.checkboxes = [];
  4052. this.dialogPromice = null;
  4053. this.isInit = false;
  4054.  
  4055. this.init = function () {
  4056. if (this.isInit) {
  4057. return;
  4058. }
  4059. addStyle();
  4060. addBlocks();
  4061. addEventListeners();
  4062. this.isInit = true;
  4063. }
  4064.  
  4065. const addEventListeners = () => {
  4066. document.addEventListener('keyup', (e) => {
  4067. if (e.key == 'Escape') {
  4068. if (this.dialogPromice) {
  4069. const { func, result } = this.dialogPromice;
  4070. this.dialogPromice = null;
  4071. popup.hide();
  4072. func(result);
  4073. }
  4074. }
  4075. });
  4076. }
  4077.  
  4078. const addStyle = () => {
  4079. let style = document.createElement('style');
  4080. style.innerText = `
  4081. .PopUp_ {
  4082. position: fixed;
  4083. left: 50%;
  4084. top: 50%;
  4085. transform: translate(-50%, -50%);
  4086. min-width: 300px;
  4087. max-width: 80%;
  4088. max-height: 80%;
  4089. background-color: #190e08e6;
  4090. z-index: 10001;
  4091. border: 3px #ce9767 solid;
  4092. border-radius: 10px;
  4093. display: flex;
  4094. flex-direction: column;
  4095. justify-content: space-around;
  4096. padding: 15px 9px;
  4097. box-sizing: border-box;
  4098. }
  4099.  
  4100. .PopUp_back {
  4101. position: absolute;
  4102. background-color: #00000066;
  4103. width: 100%;
  4104. height: 100%;
  4105. z-index: 10000;
  4106. top: 0;
  4107. left: 0;
  4108. }
  4109.  
  4110. .PopUp_close {
  4111. width: 40px;
  4112. height: 40px;
  4113. position: absolute;
  4114. right: -18px;
  4115. top: -18px;
  4116. border: 3px solid #c18550;
  4117. border-radius: 20px;
  4118. background: radial-gradient(circle, rgba(190,30,35,1) 0%, rgba(0,0,0,1) 100%);
  4119. background-position-y: 3px;
  4120. box-shadow: -1px 1px 3px black;
  4121. cursor: pointer;
  4122. box-sizing: border-box;
  4123. }
  4124.  
  4125. .PopUp_close:hover {
  4126. filter: brightness(1.2);
  4127. }
  4128.  
  4129. .PopUp_crossClose {
  4130. width: 100%;
  4131. height: 100%;
  4132. background-size: 65%;
  4133. background-position: center;
  4134. background-repeat: no-repeat;
  4135. 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")
  4136. }
  4137.  
  4138. .PopUp_blocks {
  4139. width: 100%;
  4140. height: 50%;
  4141. display: flex;
  4142. justify-content: space-evenly;
  4143. align-items: center;
  4144. flex-wrap: wrap;
  4145. justify-content: center;
  4146. }
  4147.  
  4148. .PopUp_blocks:last-child {
  4149. margin-top: 25px;
  4150. }
  4151.  
  4152. .PopUp_buttons {
  4153. display: flex;
  4154. margin: 7px 10px;
  4155. flex-direction: column;
  4156. }
  4157.  
  4158. .PopUp_button {
  4159. background-color: #52A81C;
  4160. border-radius: 5px;
  4161. box-shadow: inset 0px -4px 10px, inset 0px 3px 2px #99fe20, 0px 0px 4px, 0px -3px 1px #d7b275, 0px 0px 0px 3px #ce9767;
  4162. cursor: pointer;
  4163. padding: 4px 12px 6px;
  4164. }
  4165.  
  4166. .PopUp_input {
  4167. text-align: center;
  4168. font-size: 16px;
  4169. height: 27px;
  4170. border: 1px solid #cf9250;
  4171. border-radius: 9px 9px 0px 0px;
  4172. background: transparent;
  4173. color: #fce1ac;
  4174. padding: 1px 10px;
  4175. box-sizing: border-box;
  4176. box-shadow: 0px 0px 4px, 0px 0px 0px 3px #ce9767;
  4177. }
  4178.  
  4179. .PopUp_checkboxes {
  4180. display: flex;
  4181. flex-direction: column;
  4182. margin: 15px 15px -5px 15px;
  4183. align-items: flex-start;
  4184. }
  4185.  
  4186. .PopUp_ContCheckbox {
  4187. margin: 2px 0px;
  4188. }
  4189.  
  4190. .PopUp_checkbox {
  4191. position: absolute;
  4192. z-index: -1;
  4193. opacity: 0;
  4194. }
  4195. .PopUp_checkbox+label {
  4196. display: inline-flex;
  4197. align-items: center;
  4198. user-select: none;
  4199.  
  4200. font-size: 15px;
  4201. font-family: sans-serif;
  4202. font-weight: 600;
  4203. font-stretch: condensed;
  4204. letter-spacing: 1px;
  4205. color: #fce1ac;
  4206. text-shadow: 0px 0px 1px;
  4207. }
  4208. .PopUp_checkbox+label::before {
  4209. content: '';
  4210. display: inline-block;
  4211. width: 20px;
  4212. height: 20px;
  4213. border: 1px solid #cf9250;
  4214. border-radius: 7px;
  4215. margin-right: 7px;
  4216. }
  4217. .PopUp_checkbox:checked+label::before {
  4218. 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");
  4219. }
  4220.  
  4221. .PopUp_input::placeholder {
  4222. color: #fce1ac75;
  4223. }
  4224.  
  4225. .PopUp_input:focus {
  4226. outline: 0;
  4227. }
  4228.  
  4229. .PopUp_input + .PopUp_button {
  4230. border-radius: 0px 0px 5px 5px;
  4231. padding: 2px 18px 5px;
  4232. }
  4233.  
  4234. .PopUp_button:hover {
  4235. filter: brightness(1.2);
  4236. }
  4237.  
  4238. .PopUp_button:active {
  4239. box-shadow: inset 0px 5px 10px, inset 0px 1px 2px #99fe20, 0px 0px 4px, 0px -3px 1px #d7b275, 0px 0px 0px 3px #ce9767;
  4240. }
  4241.  
  4242. .PopUp_text {
  4243. font-size: 22px;
  4244. font-family: sans-serif;
  4245. font-weight: 600;
  4246. font-stretch: condensed;
  4247. letter-spacing: 1px;
  4248. text-align: center;
  4249. }
  4250.  
  4251. .PopUp_buttonText {
  4252. color: #E4FF4C;
  4253. text-shadow: 0px 1px 2px black;
  4254. }
  4255.  
  4256. .PopUp_msgText {
  4257. color: #FDE5B6;
  4258. text-shadow: 0px 0px 2px;
  4259. }
  4260.  
  4261. .PopUp_hideBlock {
  4262. display: none;
  4263. }
  4264. `;
  4265. document.head.appendChild(style);
  4266. }
  4267.  
  4268. const addBlocks = () => {
  4269. this.back = document.createElement('div');
  4270. this.back.classList.add('PopUp_back');
  4271. this.back.classList.add('PopUp_hideBlock');
  4272. document.body.append(this.back);
  4273.  
  4274. this.popUp = document.createElement('div');
  4275. this.popUp.classList.add('PopUp_');
  4276. this.back.append(this.popUp);
  4277.  
  4278. let upper = document.createElement('div')
  4279. upper.classList.add('PopUp_blocks');
  4280. this.popUp.append(upper);
  4281.  
  4282. this.middle = document.createElement('div')
  4283. this.middle.classList.add('PopUp_blocks');
  4284. this.middle.classList.add('PopUp_checkboxes');
  4285. this.popUp.append(this.middle);
  4286.  
  4287. this.downer = document.createElement('div')
  4288. this.downer.classList.add('PopUp_blocks');
  4289. this.popUp.append(this.downer);
  4290.  
  4291. this.msgText = document.createElement('div');
  4292. this.msgText.classList.add('PopUp_text', 'PopUp_msgText');
  4293. upper.append(this.msgText);
  4294. }
  4295.  
  4296. this.showBack = function () {
  4297. this.back.classList.remove('PopUp_hideBlock');
  4298. }
  4299.  
  4300. this.hideBack = function () {
  4301. this.back.classList.add('PopUp_hideBlock');
  4302. }
  4303.  
  4304. this.show = function () {
  4305. if (this.checkboxes.length) {
  4306. this.middle.classList.remove('PopUp_hideBlock');
  4307. }
  4308. this.showBack();
  4309. this.popUp.classList.remove('PopUp_hideBlock');
  4310. }
  4311.  
  4312. this.hide = function () {
  4313. this.hideBack();
  4314. this.popUp.classList.add('PopUp_hideBlock');
  4315. }
  4316.  
  4317. this.addAnyButton = (option) => {
  4318. const contButton = document.createElement('div');
  4319. contButton.classList.add('PopUp_buttons');
  4320. this.downer.append(contButton);
  4321.  
  4322. let inputField = {
  4323. value: option.result || option.default
  4324. }
  4325. if (option.isInput) {
  4326. inputField = document.createElement('input');
  4327. inputField.type = 'text';
  4328. if (option.placeholder) {
  4329. inputField.placeholder = option.placeholder;
  4330. }
  4331. if (option.default) {
  4332. inputField.value = option.default;
  4333. }
  4334. inputField.classList.add('PopUp_input');
  4335. contButton.append(inputField);
  4336. }
  4337.  
  4338. const button = document.createElement('div');
  4339. button.classList.add('PopUp_button');
  4340. button.title = option.title || '';
  4341. contButton.append(button);
  4342.  
  4343. const buttonText = document.createElement('div');
  4344. buttonText.classList.add('PopUp_text', 'PopUp_buttonText');
  4345. buttonText.innerHTML = option.msg;
  4346. button.append(buttonText);
  4347.  
  4348. return { button, contButton, inputField };
  4349. }
  4350.  
  4351. this.addCloseButton = () => {
  4352. let button = document.createElement('div')
  4353. button.classList.add('PopUp_close');
  4354. this.popUp.append(button);
  4355.  
  4356. let crossClose = document.createElement('div')
  4357. crossClose.classList.add('PopUp_crossClose');
  4358. button.append(crossClose);
  4359.  
  4360. return { button, contButton: button };
  4361. }
  4362.  
  4363. this.addButton = (option, buttonClick) => {
  4364.  
  4365. const { button, contButton, inputField } = option.isClose ? this.addCloseButton() : this.addAnyButton(option);
  4366. if (option.isClose) {
  4367. this.dialogPromice = { func: buttonClick, result: option.result };
  4368. }
  4369. button.addEventListener('click', () => {
  4370. let result = '';
  4371. if (option.isInput) {
  4372. result = inputField.value;
  4373. }
  4374. if (option.isClose || option.isCancel) {
  4375. this.dialogPromice = null;
  4376. }
  4377. buttonClick(result);
  4378. });
  4379.  
  4380. this.buttons.push(contButton);
  4381. }
  4382.  
  4383. this.clearButtons = () => {
  4384. while (this.buttons.length) {
  4385. this.buttons.pop().remove();
  4386. }
  4387. }
  4388.  
  4389. this.addCheckBox = (checkBox) => {
  4390. const contCheckbox = document.createElement('div');
  4391. contCheckbox.classList.add('PopUp_ContCheckbox');
  4392. this.middle.append(contCheckbox);
  4393.  
  4394. const checkbox = document.createElement('input');
  4395. checkbox.type = 'checkbox';
  4396. checkbox.id = 'PopUpCheckbox' + this.checkboxes.length;
  4397. checkbox.dataset.name = checkBox.name;
  4398. checkbox.checked = checkBox.checked;
  4399. checkbox.label = checkBox.label;
  4400. checkbox.title = checkBox.title || '';
  4401. checkbox.classList.add('PopUp_checkbox');
  4402. contCheckbox.appendChild(checkbox)
  4403.  
  4404. const checkboxLabel = document.createElement('label');
  4405. checkboxLabel.innerText = checkBox.label;
  4406. checkboxLabel.title = checkBox.title || '';
  4407. checkboxLabel.setAttribute('for', checkbox.id);
  4408. contCheckbox.appendChild(checkboxLabel);
  4409.  
  4410. this.checkboxes.push(checkbox);
  4411. }
  4412.  
  4413. this.clearCheckBox = () => {
  4414. this.middle.classList.add('PopUp_hideBlock');
  4415. while (this.checkboxes.length) {
  4416. this.checkboxes.pop().parentNode.remove();
  4417. }
  4418. }
  4419.  
  4420. this.setMsgText = (text) => {
  4421. this.msgText.innerHTML = text;
  4422. }
  4423.  
  4424. this.getCheckBoxes = () => {
  4425. const checkBoxes = [];
  4426.  
  4427. for (const checkBox of this.checkboxes) {
  4428. checkBoxes.push({
  4429. name: checkBox.dataset.name,
  4430. label: checkBox.label,
  4431. checked: checkBox.checked
  4432. });
  4433. }
  4434.  
  4435. return checkBoxes;
  4436. }
  4437.  
  4438. this.confirm = async (msg, buttOpt, checkBoxes = []) => {
  4439. if (!this.isInit) {
  4440. this.init();
  4441. }
  4442. this.clearButtons();
  4443. this.clearCheckBox();
  4444. return new Promise((complete, failed) => {
  4445. this.setMsgText(msg);
  4446. if (!buttOpt) {
  4447. buttOpt = [{ msg: 'Ok', result: true, isInput: false }];
  4448. }
  4449. for (const checkBox of checkBoxes) {
  4450. this.addCheckBox(checkBox);
  4451. }
  4452. for (let butt of buttOpt) {
  4453. this.addButton(butt, (result) => {
  4454. result = result || butt.result;
  4455. complete(result);
  4456. popup.hide();
  4457. });
  4458. if (butt.isCancel) {
  4459. this.dialogPromice = { func: complete, result: butt.result };
  4460. }
  4461. }
  4462. this.show();
  4463. });
  4464. }
  4465. });
  4466.  
  4467. this.HWHFuncs.popup = popup;
  4468.  
  4469. /**
  4470. * Миксин EventEmitter
  4471. * @param {Class} BaseClass Базовый класс (по умолчанию Object)
  4472. * @returns {Class} Класс с методами EventEmitter
  4473. */
  4474. const EventEmitterMixin = (BaseClass = Object) =>
  4475. class EventEmitter extends BaseClass {
  4476. constructor(...args) {
  4477. super(...args);
  4478. this._events = new Map();
  4479. }
  4480.  
  4481. /**
  4482. * Подписаться на событие
  4483. * @param {string} event Имя события
  4484. * @param {function} listener Функция-обработчик
  4485. * @returns {this} Возвращает экземпляр для чейнинга
  4486. */
  4487. on(event, listener) {
  4488. if (typeof listener !== 'function') {
  4489. throw new TypeError('Listener must be a function');
  4490. }
  4491.  
  4492. if (!this._events.has(event)) {
  4493. this._events.set(event, new Set());
  4494. }
  4495. this._events.get(event).add(listener);
  4496. return this;
  4497. }
  4498.  
  4499. /**
  4500. * Отписаться от события
  4501. * @param {string} event Имя события
  4502. * @param {function} listener Функция-обработчик
  4503. * @returns {this} Возвращает экземпляр для чейнинга
  4504. */
  4505. off(event, listener) {
  4506. if (this._events.has(event)) {
  4507. const listeners = this._events.get(event);
  4508. listeners.delete(listener);
  4509. if (listeners.size === 0) {
  4510. this._events.delete(event);
  4511. }
  4512. }
  4513. return this;
  4514. }
  4515.  
  4516. /**
  4517. * Вызвать событие
  4518. * @param {string} event Имя события
  4519. * @param {...any} args Аргументы для обработчиков
  4520. * @returns {boolean} Было ли событие обработано
  4521. */
  4522. emit(event, ...args) {
  4523. if (!this._events.has(event)) return false;
  4524. const listeners = new Set(this._events.get(event));
  4525. listeners.forEach((listener) => {
  4526. try {
  4527. listener.apply(this, args);
  4528. } catch (e) {
  4529. console.error(`Error in event handler for "${event}":`, e);
  4530. }
  4531. });
  4532.  
  4533. return true;
  4534. }
  4535.  
  4536. /**
  4537. * Подписаться на событие один раз
  4538. * @param {string} event Имя события
  4539. * @param {function} listener Функция-обработчик
  4540. * @returns {this} Возвращает экземпляр для чейнинга
  4541. */
  4542. once(event, listener) {
  4543. const onceWrapper = (...args) => {
  4544. this.off(event, onceWrapper);
  4545. listener.apply(this, args);
  4546. };
  4547. return this.on(event, onceWrapper);
  4548. }
  4549.  
  4550. /**
  4551. * Удалить все обработчики для события
  4552. * @param {string} [event] Имя события (если не указано - очистить все)
  4553. * @returns {this} Возвращает экземпляр для чейнинга
  4554. */
  4555. removeAllListeners(event) {
  4556. if (event) {
  4557. this._events.delete(event);
  4558. } else {
  4559. this._events.clear();
  4560. }
  4561. return this;
  4562. }
  4563.  
  4564. /**
  4565. * Получить количество обработчиков для события
  4566. * @param {string} event Имя события
  4567. * @returns {number} Количество обработчиков
  4568. */
  4569. listenerCount(event) {
  4570. return this._events.has(event) ? this._events.get(event).size : 0;
  4571. }
  4572. };
  4573.  
  4574. this.HWHFuncs.EventEmitterMixin = EventEmitterMixin;
  4575.  
  4576. /**
  4577. * Script control panel
  4578. *
  4579. * Панель управления скриптом
  4580. */
  4581. class ScriptMenu extends EventEmitterMixin() {
  4582. constructor() {
  4583. if (ScriptMenu.instance) {
  4584. return ScriptMenu.instance;
  4585. }
  4586. super();
  4587. this.mainMenu = null;
  4588. this.buttons = [];
  4589. this.checkboxes = [];
  4590. this.option = {
  4591. showMenu: true,
  4592. showDetails: {},
  4593. };
  4594. ScriptMenu.instance = this;
  4595. return this;
  4596. }
  4597.  
  4598. static getInst() {
  4599. if (!ScriptMenu.instance) {
  4600. new ScriptMenu();
  4601. }
  4602. return ScriptMenu.instance;
  4603. }
  4604.  
  4605. init(option = {}) {
  4606. this.emit('beforeInit', option);
  4607. this.option = Object.assign(this.option, option);
  4608. const saveOption = this.loadSaveOption();
  4609. this.option = Object.assign(this.option, saveOption);
  4610. this.addStyle();
  4611. this.addBlocks();
  4612. this.emit('afterInit', option);
  4613. }
  4614.  
  4615. addStyle() {
  4616. const style = document.createElement('style');
  4617. style.innerText = `
  4618. .scriptMenu_status {
  4619. position: absolute;
  4620. z-index: 10001;
  4621. top: -1px;
  4622. left: 30%;
  4623. cursor: pointer;
  4624. border-radius: 0px 0px 10px 10px;
  4625. background: #190e08e6;
  4626. border: 1px #ce9767 solid;
  4627. font-size: 18px;
  4628. font-family: sans-serif;
  4629. font-weight: 600;
  4630. font-stretch: condensed;
  4631. letter-spacing: 1px;
  4632. color: #fce1ac;
  4633. text-shadow: 0px 0px 1px;
  4634. transition: 0.5s;
  4635. padding: 2px 10px 3px;
  4636. }
  4637. .scriptMenu_statusHide {
  4638. top: -35px;
  4639. height: 30px;
  4640. overflow: hidden;
  4641. }
  4642. .scriptMenu_label {
  4643. position: absolute;
  4644. top: 30%;
  4645. left: -4px;
  4646. z-index: 9999;
  4647. cursor: pointer;
  4648. width: 30px;
  4649. height: 30px;
  4650. background: radial-gradient(circle, #47a41b 0%, #1a2f04 100%);
  4651. border: 1px solid #1a2f04;
  4652. border-radius: 5px;
  4653. box-shadow:
  4654. inset 0px 2px 4px #83ce26,
  4655. inset 0px -4px 6px #1a2f04,
  4656. 0px 0px 2px black,
  4657. 0px 0px 0px 2px #ce9767;
  4658. }
  4659. .scriptMenu_label:hover {
  4660. filter: brightness(1.2);
  4661. }
  4662. .scriptMenu_arrowLabel {
  4663. width: 100%;
  4664. height: 100%;
  4665. background-size: 75%;
  4666. background-position: center;
  4667. background-repeat: no-repeat;
  4668. 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");
  4669. box-shadow: 0px 1px 2px #000;
  4670. border-radius: 5px;
  4671. filter: drop-shadow(0px 1px 2px #000D);
  4672. }
  4673. .scriptMenu_main {
  4674. position: absolute;
  4675. max-width: 285px;
  4676. z-index: 9999;
  4677. top: 50%;
  4678. transform: translateY(-40%);
  4679. background: #190e08e6;
  4680. border: 1px #ce9767 solid;
  4681. border-radius: 0px 10px 10px 0px;
  4682. border-left: none;
  4683. box-sizing: border-box;
  4684. font-size: 15px;
  4685. font-family: sans-serif;
  4686. font-weight: 600;
  4687. font-stretch: condensed;
  4688. letter-spacing: 1px;
  4689. color: #fce1ac;
  4690. text-shadow: 0px 0px 1px;
  4691. transition: 1s;
  4692. }
  4693. .scriptMenu_conteiner {
  4694. max-height: 80vh;
  4695. overflow: scroll;
  4696. scrollbar-width: none; /* Для Firefox */
  4697. -ms-overflow-style: none; /* Для Internet Explorer и Edge */
  4698. display: flex;
  4699. flex-direction: column;
  4700. flex-wrap: nowrap;
  4701. padding: 5px 10px 5px 5px;
  4702. }
  4703. .scriptMenu_conteiner::-webkit-scrollbar {
  4704. display: none; /* Для Chrome, Safari и Opera */
  4705. }
  4706. .scriptMenu_showMenu {
  4707. display: none;
  4708. }
  4709. .scriptMenu_showMenu:checked~.scriptMenu_main {
  4710. left: 0px;
  4711. }
  4712. .scriptMenu_showMenu:not(:checked)~.scriptMenu_main {
  4713. left: -300px;
  4714. }
  4715. .scriptMenu_divInput {
  4716. margin: 2px;
  4717. }
  4718. .scriptMenu_divInputText {
  4719. margin: 2px;
  4720. align-self: center;
  4721. display: flex;
  4722. }
  4723. .scriptMenu_checkbox {
  4724. position: absolute;
  4725. z-index: -1;
  4726. opacity: 0;
  4727. }
  4728. .scriptMenu_checkbox+label {
  4729. display: inline-flex;
  4730. align-items: center;
  4731. user-select: none;
  4732. }
  4733. .scriptMenu_checkbox+label::before {
  4734. content: '';
  4735. display: inline-block;
  4736. width: 20px;
  4737. height: 20px;
  4738. border: 1px solid #cf9250;
  4739. border-radius: 7px;
  4740. margin-right: 7px;
  4741. }
  4742. .scriptMenu_checkbox:checked+label::before {
  4743. 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");
  4744. }
  4745. .scriptMenu_close {
  4746. width: 40px;
  4747. height: 40px;
  4748. position: absolute;
  4749. right: -18px;
  4750. top: -18px;
  4751. border: 3px solid #c18550;
  4752. border-radius: 20px;
  4753. background: radial-gradient(circle, rgba(190,30,35,1) 0%, rgba(0,0,0,1) 100%);
  4754. background-position-y: 3px;
  4755. box-shadow: -1px 1px 3px black;
  4756. cursor: pointer;
  4757. box-sizing: border-box;
  4758. }
  4759. .scriptMenu_close:hover {
  4760. filter: brightness(1.2);
  4761. }
  4762. .scriptMenu_crossClose {
  4763. width: 100%;
  4764. height: 100%;
  4765. background-size: 65%;
  4766. background-position: center;
  4767. background-repeat: no-repeat;
  4768. 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")
  4769. }
  4770. .scriptMenu_button {
  4771. user-select: none;
  4772. cursor: pointer;
  4773. padding: 5px 14px 8px;
  4774. }
  4775. .scriptMenu_button:hover {
  4776. filter: brightness(1.2);
  4777. }
  4778. .scriptMenu_buttonText {
  4779. color: #fce5b7;
  4780. text-shadow: 0px 1px 2px black;
  4781. text-align: center;
  4782. }
  4783. .scriptMenu_header {
  4784. text-align: center;
  4785. align-self: center;
  4786. font-size: 15px;
  4787. margin: 0px 15px;
  4788. }
  4789. .scriptMenu_header a {
  4790. color: #fce5b7;
  4791. text-decoration: none;
  4792. }
  4793. .scriptMenu_InputText {
  4794. text-align: center;
  4795. width: 130px;
  4796. height: 24px;
  4797. border: 1px solid #cf9250;
  4798. border-radius: 9px;
  4799. background: transparent;
  4800. color: #fce1ac;
  4801. padding: 0px 10px;
  4802. box-sizing: border-box;
  4803. }
  4804. .scriptMenu_InputText:focus {
  4805. filter: brightness(1.2);
  4806. outline: 0;
  4807. }
  4808. .scriptMenu_InputText::placeholder {
  4809. color: #fce1ac75;
  4810. }
  4811. .scriptMenu_Summary {
  4812. cursor: pointer;
  4813. margin-left: 7px;
  4814. }
  4815. .scriptMenu_Details {
  4816. align-self: center;
  4817. }
  4818. .scriptMenu_buttonGroup {
  4819. display: flex;
  4820. justify-content: center;
  4821. user-select: none;
  4822. cursor: pointer;
  4823. padding: 0;
  4824. margin: 3px 0;
  4825. }
  4826. .scriptMenu_buttonGroup .scriptMenu_button {
  4827. width: 100%;
  4828. padding: 5px 8px 8px;
  4829. }
  4830. .scriptMenu_mainButton {
  4831. border-radius: 5px;
  4832. margin: 3px 0;
  4833. }
  4834. .scriptMenu_combineButtonLeft {
  4835. border-top-left-radius: 5px;
  4836. border-bottom-left-radius: 5px;
  4837. margin-right: 2px;
  4838. }
  4839. .scriptMenu_combineButtonCenter {
  4840. border-radius: 0px;
  4841. margin-right: 2px;
  4842. }
  4843. .scriptMenu_combineButtonRight {
  4844. border-top-right-radius: 5px;
  4845. border-bottom-right-radius: 5px;
  4846. }
  4847. .scriptMenu_beigeButton {
  4848. border: 1px solid #442901;
  4849. background: radial-gradient(circle, rgba(165,120,56,1) 80%, rgba(0,0,0,1) 110%);
  4850. 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;
  4851. }
  4852. .scriptMenu_beigeButton:active {
  4853. box-shadow: inset 0px 4px 6px #442901, inset 0px 4px 6px #442901, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 1px #ce9767;
  4854. }
  4855. .scriptMenu_greenButton {
  4856. border: 1px solid #1a2f04;
  4857. background: radial-gradient(circle, #47a41b 0%, #1a2f04 150%);
  4858. box-shadow: inset 0px 2px 4px #83ce26, inset 0px -4px 6px #1a2f04, 0px 0px 2px black, 0px 0px 0px 1px #ce9767;
  4859. }
  4860. .scriptMenu_greenButton:active {
  4861. box-shadow: inset 0px 4px 6px #1a2f04, inset 0px 4px 6px #1a2f04, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 1px #ce9767;
  4862. }
  4863. .scriptMenu_redButton {
  4864. border: 1px solid #440101;
  4865. background: radial-gradient(circle, rgb(198, 34, 34) 80%, rgb(0, 0, 0) 110%);
  4866. 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;
  4867. }
  4868. .scriptMenu_redButton:active {
  4869. box-shadow: inset 0px 4px 6px #440101, inset 0px 4px 6px #440101, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 1px #ce9767;
  4870. }
  4871. .scriptMenu_attention {
  4872. position: relative;
  4873. }
  4874. .scriptMenu_attention .scriptMenu_dot {
  4875. display: flex;
  4876. justify-content: center;
  4877. align-items: center;
  4878. }
  4879. .scriptMenu_dot {
  4880. position: absolute;
  4881. top: -7px;
  4882. right: -7px;
  4883. width: 20px;
  4884. height: 20px;
  4885. border-radius: 50%;
  4886. border: 1px solid #c18550;
  4887. background: radial-gradient(circle, #f000 25%, black 100%);
  4888. box-shadow: 0px 0px 2px black;
  4889. background-position: 0px -1px;
  4890. font-size: 10px;
  4891. text-align: center;
  4892. color: white;
  4893. text-shadow: 1px 1px 1px black;
  4894. box-sizing: border-box;
  4895. display: none;
  4896. }
  4897. `;
  4898. document.head.appendChild(style);
  4899. }
  4900.  
  4901. addBlocks() {
  4902. const main = document.createElement('div');
  4903. document.body.appendChild(main);
  4904.  
  4905. this.status = document.createElement('div');
  4906. this.status.classList.add('scriptMenu_status');
  4907. this.setStatus('');
  4908. main.appendChild(this.status);
  4909.  
  4910. const label = document.createElement('label');
  4911. label.classList.add('scriptMenu_label');
  4912. label.setAttribute('for', 'checkbox_showMenu');
  4913. main.appendChild(label);
  4914.  
  4915. const arrowLabel = document.createElement('div');
  4916. arrowLabel.classList.add('scriptMenu_arrowLabel');
  4917. label.appendChild(arrowLabel);
  4918.  
  4919. const checkbox = document.createElement('input');
  4920. checkbox.type = 'checkbox';
  4921. checkbox.id = 'checkbox_showMenu';
  4922. checkbox.checked = this.option.showMenu;
  4923. checkbox.classList.add('scriptMenu_showMenu');
  4924. checkbox.addEventListener('change', () => {
  4925. this.option.showMenu = checkbox.checked;
  4926. this.saveSaveOption();
  4927. });
  4928. main.appendChild(checkbox);
  4929.  
  4930. const mainMenu = document.createElement('div');
  4931. mainMenu.classList.add('scriptMenu_main');
  4932. main.appendChild(mainMenu);
  4933.  
  4934. this.mainMenu = document.createElement('div');
  4935. this.mainMenu.classList.add('scriptMenu_conteiner');
  4936. mainMenu.appendChild(this.mainMenu);
  4937.  
  4938. const closeButton = document.createElement('label');
  4939. closeButton.classList.add('scriptMenu_close');
  4940. closeButton.setAttribute('for', 'checkbox_showMenu');
  4941. this.mainMenu.appendChild(closeButton);
  4942.  
  4943. const crossClose = document.createElement('div');
  4944. crossClose.classList.add('scriptMenu_crossClose');
  4945. closeButton.appendChild(crossClose);
  4946. }
  4947.  
  4948. getButtonColor(color) {
  4949. const buttonColors = {
  4950. green: 'scriptMenu_greenButton',
  4951. red: 'scriptMenu_redButton',
  4952. beige: 'scriptMenu_beigeButton',
  4953. };
  4954. return buttonColors[color] || buttonColors['beige'];
  4955. }
  4956.  
  4957. setStatus(text, onclick) {
  4958. if (this._currentStatusClickHandler) {
  4959. this.status.removeEventListener('click', this._currentStatusClickHandler);
  4960. this._currentStatusClickHandler = null;
  4961. }
  4962.  
  4963. if (!text) {
  4964. this.status.classList.add('scriptMenu_statusHide');
  4965. this.status.innerHTML = '';
  4966. } else {
  4967. this.status.classList.remove('scriptMenu_statusHide');
  4968. this.status.innerHTML = text;
  4969. }
  4970.  
  4971. if (typeof onclick === 'function') {
  4972. this.status.addEventListener('click', onclick, { once: true });
  4973. this._currentStatusClickHandler = onclick;
  4974. }
  4975. }
  4976.  
  4977. addStatus(text) {
  4978. if (!this.status.innerHTML) {
  4979. this.status.classList.remove('scriptMenu_statusHide');
  4980. }
  4981. this.status.innerHTML += text;
  4982. }
  4983.  
  4984. addHeader(text, onClick, main = this.mainMenu) {
  4985. this.emit('beforeAddHeader', text, onClick, main);
  4986. const header = document.createElement('div');
  4987. header.classList.add('scriptMenu_header');
  4988. header.innerHTML = text;
  4989. if (typeof onClick === 'function') {
  4990. header.addEventListener('click', onClick);
  4991. }
  4992. main.appendChild(header);
  4993. this.emit('afterAddHeader', text, onClick, main);
  4994. return header;
  4995. }
  4996.  
  4997. addButton(btn, main = this.mainMenu) {
  4998. this.emit('beforeAddButton', btn, main);
  4999. const { name, onClick, title, color, dot, classes = [], isCombine } = btn;
  5000. const button = document.createElement('div');
  5001. if (!isCombine) {
  5002. classes.push('scriptMenu_mainButton');
  5003. }
  5004. button.classList.add('scriptMenu_button', this.getButtonColor(color), ...classes);
  5005. button.title = title;
  5006. button.addEventListener('click', onClick);
  5007. main.appendChild(button);
  5008.  
  5009. const buttonText = document.createElement('div');
  5010. buttonText.classList.add('scriptMenu_buttonText');
  5011. buttonText.innerText = name;
  5012. button.appendChild(buttonText);
  5013.  
  5014. if (dot) {
  5015. const dotAtention = document.createElement('div');
  5016. dotAtention.classList.add('scriptMenu_dot');
  5017. dotAtention.title = dot;
  5018. button.appendChild(dotAtention);
  5019. }
  5020.  
  5021. this.buttons.push(button);
  5022. this.emit('afterAddButton', button, btn);
  5023. return button;
  5024. }
  5025.  
  5026. addCombinedButton(buttonList, main = this.mainMenu) {
  5027. this.emit('beforeAddCombinedButton', buttonList, main);
  5028. const buttonGroup = document.createElement('div');
  5029. buttonGroup.classList.add('scriptMenu_buttonGroup');
  5030. let count = 0;
  5031.  
  5032. for (const btn of buttonList) {
  5033. btn.isCombine = true;
  5034. btn.classes ??= [];
  5035. if (count === 0) {
  5036. btn.classes.push('scriptMenu_combineButtonLeft');
  5037. } else if (count === buttonList.length - 1) {
  5038. btn.classes.push('scriptMenu_combineButtonRight');
  5039. } else {
  5040. btn.classes.push('scriptMenu_combineButtonCenter');
  5041. }
  5042. this.addButton(btn, buttonGroup);
  5043. count++;
  5044. }
  5045.  
  5046. const dotAtention = document.createElement('div');
  5047. dotAtention.classList.add('scriptMenu_dot');
  5048. buttonGroup.appendChild(dotAtention);
  5049.  
  5050. main.appendChild(buttonGroup);
  5051. this.emit('afterAddCombinedButton', buttonGroup, buttonList);
  5052. return buttonGroup;
  5053. }
  5054.  
  5055. addCheckbox(label, title, main = this.mainMenu) {
  5056. this.emit('beforeAddCheckbox', label, title, main);
  5057. const divCheckbox = document.createElement('div');
  5058. divCheckbox.classList.add('scriptMenu_divInput');
  5059. divCheckbox.title = title;
  5060. main.appendChild(divCheckbox);
  5061.  
  5062. const checkbox = document.createElement('input');
  5063. checkbox.type = 'checkbox';
  5064. checkbox.id = 'scriptMenuCheckbox' + this.checkboxes.length;
  5065. checkbox.classList.add('scriptMenu_checkbox');
  5066. divCheckbox.appendChild(checkbox);
  5067.  
  5068. const checkboxLabel = document.createElement('label');
  5069. checkboxLabel.innerText = label;
  5070. checkboxLabel.setAttribute('for', checkbox.id);
  5071. divCheckbox.appendChild(checkboxLabel);
  5072.  
  5073. this.checkboxes.push(checkbox);
  5074. this.emit('afterAddCheckbox', label, title, main);
  5075. return checkbox;
  5076. }
  5077.  
  5078. addInputText(title, placeholder, main = this.mainMenu) {
  5079. this.emit('beforeAddCheckbox', title, placeholder, main);
  5080. const divInputText = document.createElement('div');
  5081. divInputText.classList.add('scriptMenu_divInputText');
  5082. divInputText.title = title;
  5083. main.appendChild(divInputText);
  5084.  
  5085. const newInputText = document.createElement('input');
  5086. newInputText.type = 'text';
  5087. if (placeholder) {
  5088. newInputText.placeholder = placeholder;
  5089. }
  5090. newInputText.classList.add('scriptMenu_InputText');
  5091. divInputText.appendChild(newInputText);
  5092. this.emit('afterAddCheckbox', title, placeholder, main);
  5093. return newInputText;
  5094. }
  5095.  
  5096. addDetails(summaryText, name = null) {
  5097. this.emit('beforeAddDetails', summaryText, name);
  5098. const details = document.createElement('details');
  5099. details.classList.add('scriptMenu_Details');
  5100. this.mainMenu.appendChild(details);
  5101.  
  5102. const summary = document.createElement('summary');
  5103. summary.classList.add('scriptMenu_Summary');
  5104. summary.innerText = summaryText;
  5105. if (name) {
  5106. details.open = this.option.showDetails[name] ?? false;
  5107. details.dataset.name = name;
  5108. details.addEventListener('toggle', () => {
  5109. this.option.showDetails[details.dataset.name] = details.open;
  5110. this.saveSaveOption();
  5111. });
  5112. }
  5113.  
  5114. details.appendChild(summary);
  5115. this.emit('afterAddDetails', summaryText, name);
  5116. return details;
  5117. }
  5118.  
  5119. saveSaveOption() {
  5120. try {
  5121. localStorage.setItem('scriptMenu_saveOption', JSON.stringify(this.option));
  5122. } catch (e) {
  5123. console.log('¯\\_(ツ)_/¯');
  5124. }
  5125. }
  5126.  
  5127. loadSaveOption() {
  5128. let saveOption = null;
  5129. try {
  5130. saveOption = localStorage.getItem('scriptMenu_saveOption');
  5131. } catch (e) {
  5132. console.log('¯\\_(ツ)_/¯');
  5133. }
  5134.  
  5135. if (!saveOption) {
  5136. return {};
  5137. }
  5138.  
  5139. try {
  5140. saveOption = JSON.parse(saveOption);
  5141. } catch (e) {
  5142. return {};
  5143. }
  5144.  
  5145. return saveOption;
  5146. }
  5147. }
  5148.  
  5149. this.HWHClasses.ScriptMenu = ScriptMenu;
  5150.  
  5151. //const scriptMenu = ScriptMenu.getInst();
  5152.  
  5153. /**
  5154. * Пример использования
  5155. const scriptMenu = ScriptMenu.getInst();
  5156. scriptMenu.init();
  5157. scriptMenu.addHeader('v1.508');
  5158. scriptMenu.addCheckbox('testHack', 'Тестовый взлом игры!');
  5159. scriptMenu.addButton({
  5160. text: 'Запуск!',
  5161. onClick: () => console.log('click'),
  5162. title: 'подсказака',
  5163. });
  5164. scriptMenu.addInputText('input подсказака');
  5165. scriptMenu.on('beforeInit', (option) => {
  5166. console.log('beforeInit', option);
  5167. })
  5168. scriptMenu.on('beforeAddHeader', (text, onClick, main) => {
  5169. console.log('beforeAddHeader', text, onClick, main);
  5170. });
  5171. scriptMenu.on('beforeAddButton', (btn, main) => {
  5172. console.log('beforeAddButton', btn, main);
  5173. });
  5174. scriptMenu.on('beforeAddCombinedButton', (buttonList, main) => {
  5175. console.log('beforeAddCombinedButton', buttonList, main);
  5176. });
  5177. scriptMenu.on('beforeAddCheckbox', (label, title, main) => {
  5178. console.log('beforeAddCheckbox', label, title, main);
  5179. });
  5180. scriptMenu.on('beforeAddDetails', (summaryText, name) => {
  5181. console.log('beforeAddDetails', summaryText, name);
  5182. });
  5183. */
  5184.  
  5185. /**
  5186. * Game Library
  5187. *
  5188. * Игровая библиотека
  5189. */
  5190. class Library {
  5191. defaultLibUrl = 'https://heroesru-a.akamaihd.net/vk/v1101/lib/lib.json';
  5192.  
  5193. constructor() {
  5194. if (!Library.instance) {
  5195. Library.instance = this;
  5196. }
  5197.  
  5198. return Library.instance;
  5199. }
  5200.  
  5201. async load() {
  5202. try {
  5203. await this.getUrlLib();
  5204. console.log(this.defaultLibUrl);
  5205. this.data = await fetch(this.defaultLibUrl).then(e => e.json())
  5206. } catch (error) {
  5207. console.error('Не удалось загрузить библиотеку', error)
  5208. }
  5209. }
  5210.  
  5211. async getUrlLib() {
  5212. try {
  5213. const db = new Database('hw_cache', 'cache');
  5214. await db.open();
  5215. const cacheLibFullUrl = await db.get('lib/lib.json.gz', false);
  5216. this.defaultLibUrl = cacheLibFullUrl.fullUrl.split('.gz').shift();
  5217. } catch(e) {}
  5218. }
  5219.  
  5220. getData(id) {
  5221. return this.data[id];
  5222. }
  5223.  
  5224. setData(data) {
  5225. this.data = data;
  5226. }
  5227. }
  5228.  
  5229. this.lib = new Library();
  5230. /**
  5231. * Database
  5232. *
  5233. * База данных
  5234. */
  5235. class Database {
  5236. constructor(dbName, storeName) {
  5237. this.dbName = dbName;
  5238. this.storeName = storeName;
  5239. this.db = null;
  5240. }
  5241.  
  5242. async open() {
  5243. return new Promise((resolve, reject) => {
  5244. const request = indexedDB.open(this.dbName);
  5245.  
  5246. request.onerror = () => {
  5247. reject(new Error(`Failed to open database ${this.dbName}`));
  5248. };
  5249.  
  5250. request.onsuccess = () => {
  5251. this.db = request.result;
  5252. resolve();
  5253. };
  5254.  
  5255. request.onupgradeneeded = (event) => {
  5256. const db = event.target.result;
  5257. if (!db.objectStoreNames.contains(this.storeName)) {
  5258. db.createObjectStore(this.storeName);
  5259. }
  5260. };
  5261. });
  5262. }
  5263.  
  5264. async set(key, value) {
  5265. return new Promise((resolve, reject) => {
  5266. const transaction = this.db.transaction([this.storeName], 'readwrite');
  5267. const store = transaction.objectStore(this.storeName);
  5268. const request = store.put(value, key);
  5269.  
  5270. request.onerror = () => {
  5271. reject(new Error(`Failed to save value with key ${key}`));
  5272. };
  5273.  
  5274. request.onsuccess = () => {
  5275. resolve();
  5276. };
  5277. });
  5278. }
  5279.  
  5280. async get(key, def) {
  5281. return new Promise((resolve, reject) => {
  5282. const transaction = this.db.transaction([this.storeName], 'readonly');
  5283. const store = transaction.objectStore(this.storeName);
  5284. const request = store.get(key);
  5285.  
  5286. request.onerror = () => {
  5287. resolve(def);
  5288. };
  5289.  
  5290. request.onsuccess = () => {
  5291. resolve(request.result);
  5292. };
  5293. });
  5294. }
  5295.  
  5296. async delete(key) {
  5297. return new Promise((resolve, reject) => {
  5298. const transaction = this.db.transaction([this.storeName], 'readwrite');
  5299. const store = transaction.objectStore(this.storeName);
  5300. const request = store.delete(key);
  5301.  
  5302. request.onerror = () => {
  5303. reject(new Error(`Failed to delete value with key ${key}`));
  5304. };
  5305.  
  5306. request.onsuccess = () => {
  5307. resolve();
  5308. };
  5309. });
  5310. }
  5311. }
  5312.  
  5313. /**
  5314. * Returns the stored value
  5315. *
  5316. * Возвращает сохраненное значение
  5317. */
  5318. function getSaveVal(saveName, def) {
  5319. const result = storage.get(saveName, def);
  5320. return result;
  5321. }
  5322. this.HWHFuncs.getSaveVal = getSaveVal;
  5323.  
  5324. /**
  5325. * Stores value
  5326. *
  5327. * Сохраняет значение
  5328. */
  5329. function setSaveVal(saveName, value) {
  5330. storage.set(saveName, value);
  5331. }
  5332. this.HWHFuncs.setSaveVal = setSaveVal;
  5333.  
  5334. /**
  5335. * Database initialization
  5336. *
  5337. * Инициализация базы данных
  5338. */
  5339. const db = new Database(GM_info.script.name, 'settings');
  5340.  
  5341. /**
  5342. * Data store
  5343. *
  5344. * Хранилище данных
  5345. */
  5346. const storage = {
  5347. userId: 0,
  5348. /**
  5349. * Default values
  5350. *
  5351. * Значения по умолчанию
  5352. */
  5353. values: {},
  5354. name: GM_info.script.name,
  5355. init: function () {
  5356. const { checkboxes, inputs } = HWHData;
  5357. this.values = [
  5358. ...Object.entries(checkboxes).map((e) => ({ [e[0]]: e[1].default })),
  5359. ...Object.entries(inputs).map((e) => ({ [e[0]]: e[1].default })),
  5360. ].reduce((acc, obj) => ({ ...acc, ...obj }), {});
  5361. },
  5362. get: function (key, def) {
  5363. if (key in this.values) {
  5364. return this.values[key];
  5365. }
  5366. return def;
  5367. },
  5368. set: function (key, value) {
  5369. this.values[key] = value;
  5370. db.set(this.userId, this.values).catch((e) => null);
  5371. localStorage[this.name + ':' + key] = value;
  5372. },
  5373. delete: function (key) {
  5374. delete this.values[key];
  5375. db.set(this.userId, this.values);
  5376. delete localStorage[this.name + ':' + key];
  5377. },
  5378. };
  5379.  
  5380. /**
  5381. * Returns all keys from localStorage that start with prefix (for migration)
  5382. *
  5383. * Возвращает все ключи из localStorage которые начинаются с prefix (для миграции)
  5384. */
  5385. function getAllValuesStartingWith(prefix) {
  5386. const values = [];
  5387. for (let i = 0; i < localStorage.length; i++) {
  5388. const key = localStorage.key(i);
  5389. if (key.startsWith(prefix)) {
  5390. const val = localStorage.getItem(key);
  5391. const keyValue = key.split(':')[1];
  5392. values.push({ key: keyValue, val });
  5393. }
  5394. }
  5395. return values;
  5396. }
  5397.  
  5398. /**
  5399. * Opens or migrates to a database
  5400. *
  5401. * Открывает или мигрирует в базу данных
  5402. */
  5403. async function openOrMigrateDatabase(userId) {
  5404. storage.init();
  5405. storage.userId = userId;
  5406. try {
  5407. await db.open();
  5408. } catch(e) {
  5409. return;
  5410. }
  5411. let settings = await db.get(userId, false);
  5412.  
  5413. if (settings) {
  5414. storage.values = settings;
  5415. return;
  5416. }
  5417.  
  5418. const values = getAllValuesStartingWith(GM_info.script.name);
  5419. for (const value of values) {
  5420. let val = null;
  5421. try {
  5422. val = JSON.parse(value.val);
  5423. } catch {
  5424. break;
  5425. }
  5426. storage.values[value.key] = val;
  5427. }
  5428. await db.set(userId, storage.values);
  5429. }
  5430.  
  5431. class ZingerYWebsiteAPI {
  5432. /**
  5433. * Class for interaction with the API of the zingery.ru website
  5434. * Intended only for use with the HeroWarsHelper script:
  5435. * https://greatest.deepsurf.us/ru/scripts/450693-herowarshelper
  5436. * Copyright ZingerY
  5437. */
  5438. url = 'https://zingery.ru/heroes/';
  5439. // YWJzb2x1dGVseSB1c2VsZXNzIGxpbmU=
  5440. constructor(urn, env, data = {}) {
  5441. this.urn = urn;
  5442. this.fd = {
  5443. now: Date.now(),
  5444. fp: this.constructor.toString().replaceAll(/\s/g, ''),
  5445. env: env.callee.toString().replaceAll(/\s/g, ''),
  5446. info: (({ name, version, author }) => [name, version, author])(GM_info.script),
  5447. ...data,
  5448. };
  5449. }
  5450.  
  5451. sign() {
  5452. return md5([...this.fd.info, ~(this.fd.now % 1e3), this.fd.fp].join('_'));
  5453. }
  5454.  
  5455. encode(data) {
  5456. return btoa(encodeURIComponent(JSON.stringify(data)));
  5457. }
  5458.  
  5459. decode(data) {
  5460. return JSON.parse(decodeURIComponent(atob(data)));
  5461. }
  5462.  
  5463. headers() {
  5464. return {
  5465. 'X-Request-Signature': this.sign(),
  5466. 'X-Script-Name': GM_info.script.name,
  5467. 'X-Script-Version': GM_info.script.version,
  5468. 'X-Script-Author': GM_info.script.author,
  5469. 'X-Script-ZingerY': 42,
  5470. };
  5471. }
  5472.  
  5473. async request() {
  5474. try {
  5475. const response = await fetch(this.url + this.urn, {
  5476. method: 'POST',
  5477. headers: this.headers(),
  5478. body: this.encode(this.fd),
  5479. });
  5480. const text = await response.text();
  5481. return this.decode(text);
  5482. } catch (e) {
  5483. console.error(e);
  5484. return [];
  5485. }
  5486. }
  5487. /**
  5488. * Класс для взаимодействия с API сайта zingery.ru
  5489. * Предназначен только для использования со скриптом HeroWarsHelper:
  5490. * https://greatest.deepsurf.us/ru/scripts/450693-herowarshelper
  5491. * Copyright ZingerY
  5492. */
  5493. }
  5494.  
  5495. /**
  5496. * Sending expeditions
  5497. *
  5498. * Отправка экспедиций
  5499. */
  5500. function checkExpedition() {
  5501. const { Expedition } = HWHClasses;
  5502. return new Promise((resolve, reject) => {
  5503. const expedition = new Expedition(resolve, reject);
  5504. expedition.start();
  5505. });
  5506. }
  5507.  
  5508. class Expedition {
  5509. checkExpedInfo = {
  5510. calls: [
  5511. {
  5512. name: 'expeditionGet',
  5513. args: {},
  5514. ident: 'expeditionGet',
  5515. },
  5516. {
  5517. name: 'heroGetAll',
  5518. args: {},
  5519. ident: 'heroGetAll',
  5520. },
  5521. ],
  5522. };
  5523.  
  5524. constructor(resolve, reject) {
  5525. this.resolve = resolve;
  5526. this.reject = reject;
  5527. }
  5528.  
  5529. async start() {
  5530. const data = await Send(JSON.stringify(this.checkExpedInfo));
  5531.  
  5532. const expedInfo = data.results[0].result.response;
  5533. const dataHeroes = data.results[1].result.response;
  5534. const dataExped = { useHeroes: [], exped: [] };
  5535. const calls = [];
  5536.  
  5537. /**
  5538. * Adding expeditions to collect
  5539. * Добавляем экспедиции для сбора
  5540. */
  5541. let countGet = 0;
  5542. for (var n in expedInfo) {
  5543. const exped = expedInfo[n];
  5544. const dateNow = Date.now() / 1000;
  5545. if (exped.status == 2 && exped.endTime != 0 && dateNow > exped.endTime) {
  5546. countGet++;
  5547. calls.push({
  5548. name: 'expeditionFarm',
  5549. args: { expeditionId: exped.id },
  5550. ident: 'expeditionFarm_' + exped.id,
  5551. });
  5552. } else {
  5553. dataExped.useHeroes = dataExped.useHeroes.concat(exped.heroes);
  5554. }
  5555. if (exped.status == 1) {
  5556. dataExped.exped.push({ id: exped.id, power: exped.power });
  5557. }
  5558. }
  5559. dataExped.exped = dataExped.exped.sort((a, b) => b.power - a.power);
  5560.  
  5561. /**
  5562. * Putting together a list of heroes
  5563. * Собираем список героев
  5564. */
  5565. const heroesArr = [];
  5566. for (let n in dataHeroes) {
  5567. const hero = dataHeroes[n];
  5568. if (hero.power > 0 && !dataExped.useHeroes.includes(hero.id)) {
  5569. let heroPower = hero.power;
  5570. // Лара Крофт * 3
  5571. if (hero.id == 63 && hero.color >= 16) {
  5572. heroPower *= 3;
  5573. }
  5574. heroesArr.push({ id: hero.id, power: heroPower });
  5575. }
  5576. }
  5577.  
  5578. /**
  5579. * Adding expeditions to send
  5580. * Добавляем экспедиции для отправки
  5581. */
  5582. let countSend = 0;
  5583. heroesArr.sort((a, b) => a.power - b.power);
  5584. for (const exped of dataExped.exped) {
  5585. let heroesIds = this.selectionHeroes(heroesArr, exped.power);
  5586. if (heroesIds && heroesIds.length > 4) {
  5587. for (let q in heroesArr) {
  5588. if (heroesIds.includes(heroesArr[q].id)) {
  5589. delete heroesArr[q];
  5590. }
  5591. }
  5592. countSend++;
  5593. calls.push({
  5594. name: 'expeditionSendHeroes',
  5595. args: {
  5596. expeditionId: exped.id,
  5597. heroes: heroesIds,
  5598. },
  5599. ident: 'expeditionSendHeroes_' + exped.id,
  5600. });
  5601. }
  5602. }
  5603.  
  5604. if (calls.length) {
  5605. await Send({ calls });
  5606. this.end(I18N('EXPEDITIONS_SENT', {countGet, countSend}));
  5607. return;
  5608. }
  5609.  
  5610. this.end(I18N('EXPEDITIONS_NOTHING'));
  5611. }
  5612.  
  5613. /**
  5614. * Selection of heroes for expeditions
  5615. *
  5616. * Подбор героев для экспедиций
  5617. */
  5618. selectionHeroes(heroes, power) {
  5619. const resultHeroers = [];
  5620. const heroesIds = [];
  5621. for (let q = 0; q < 5; q++) {
  5622. for (let i in heroes) {
  5623. let hero = heroes[i];
  5624. if (heroesIds.includes(hero.id)) {
  5625. continue;
  5626. }
  5627.  
  5628. const summ = resultHeroers.reduce((acc, hero) => acc + hero.power, 0);
  5629. const need = Math.round((power - summ) / (5 - resultHeroers.length));
  5630. if (hero.power > need) {
  5631. resultHeroers.push(hero);
  5632. heroesIds.push(hero.id);
  5633. break;
  5634. }
  5635. }
  5636. }
  5637.  
  5638. const summ = resultHeroers.reduce((acc, hero) => acc + hero.power, 0);
  5639. if (summ < power) {
  5640. return false;
  5641. }
  5642. return heroesIds;
  5643. }
  5644.  
  5645. /**
  5646. * Ends expedition script
  5647. *
  5648. * Завершает скрипт экспедиции
  5649. */
  5650. end(msg) {
  5651. setProgress(msg, true);
  5652. this.resolve();
  5653. }
  5654. }
  5655.  
  5656. this.HWHClasses.Expedition = Expedition;
  5657.  
  5658. /**
  5659. * Walkthrough of the dungeon
  5660. *
  5661. * Прохождение подземелья
  5662. */
  5663. function testDungeon() {
  5664. const { executeDungeon } = HWHClasses;
  5665. return new Promise((resolve, reject) => {
  5666. const dung = new executeDungeon(resolve, reject);
  5667. const titanit = getInput('countTitanit');
  5668. dung.start(titanit);
  5669. });
  5670. }
  5671.  
  5672. /**
  5673. * Walkthrough of the dungeon
  5674. *
  5675. * Прохождение подземелья
  5676. */
  5677. function executeDungeon(resolve, reject) {
  5678. dungeonActivity = 0;
  5679. maxDungeonActivity = 150;
  5680.  
  5681. titanGetAll = [];
  5682.  
  5683. teams = {
  5684. heroes: [],
  5685. earth: [],
  5686. fire: [],
  5687. neutral: [],
  5688. water: [],
  5689. }
  5690.  
  5691. titanStats = [];
  5692.  
  5693. titansStates = {};
  5694.  
  5695. let talentMsg = '';
  5696. let talentMsgReward = '';
  5697.  
  5698. callsExecuteDungeon = {
  5699. calls: [{
  5700. name: "dungeonGetInfo",
  5701. args: {},
  5702. ident: "dungeonGetInfo"
  5703. }, {
  5704. name: "teamGetAll",
  5705. args: {},
  5706. ident: "teamGetAll"
  5707. }, {
  5708. name: "teamGetFavor",
  5709. args: {},
  5710. ident: "teamGetFavor"
  5711. }, {
  5712. name: "clanGetInfo",
  5713. args: {},
  5714. ident: "clanGetInfo"
  5715. }, {
  5716. name: "titanGetAll",
  5717. args: {},
  5718. ident: "titanGetAll"
  5719. }, {
  5720. name: "inventoryGet",
  5721. args: {},
  5722. ident: "inventoryGet"
  5723. }]
  5724. }
  5725.  
  5726. this.start = function(titanit) {
  5727. maxDungeonActivity = titanit || getInput('countTitanit');
  5728. send(JSON.stringify(callsExecuteDungeon), startDungeon);
  5729. }
  5730.  
  5731. /**
  5732. * Getting data on the dungeon
  5733. *
  5734. * Получаем данные по подземелью
  5735. */
  5736. function startDungeon(e) {
  5737. res = e.results;
  5738. dungeonGetInfo = res[0].result.response;
  5739. if (!dungeonGetInfo) {
  5740. endDungeon('noDungeon', res);
  5741. return;
  5742. }
  5743. teamGetAll = res[1].result.response;
  5744. teamGetFavor = res[2].result.response;
  5745. dungeonActivity = res[3].result.response.stat.todayDungeonActivity;
  5746. titanGetAll = Object.values(res[4].result.response);
  5747. countPredictionCard = res[5].result.response.consumable[81];
  5748.  
  5749. teams.hero = {
  5750. favor: teamGetFavor.dungeon_hero,
  5751. heroes: teamGetAll.dungeon_hero.filter(id => id < 6000),
  5752. teamNum: 0,
  5753. }
  5754. heroPet = teamGetAll.dungeon_hero.filter(id => id >= 6000).pop();
  5755. if (heroPet) {
  5756. teams.hero.pet = heroPet;
  5757. }
  5758.  
  5759. teams.neutral = {
  5760. favor: {},
  5761. heroes: getTitanTeam(titanGetAll, 'neutral'),
  5762. teamNum: 0,
  5763. };
  5764. teams.water = {
  5765. favor: {},
  5766. heroes: getTitanTeam(titanGetAll, 'water'),
  5767. teamNum: 0,
  5768. };
  5769. teams.fire = {
  5770. favor: {},
  5771. heroes: getTitanTeam(titanGetAll, 'fire'),
  5772. teamNum: 0,
  5773. };
  5774. teams.earth = {
  5775. favor: {},
  5776. heroes: getTitanTeam(titanGetAll, 'earth'),
  5777. teamNum: 0,
  5778. };
  5779.  
  5780.  
  5781. checkFloor(dungeonGetInfo);
  5782. }
  5783.  
  5784. function getTitanTeam(titans, type) {
  5785. switch (type) {
  5786. case 'neutral':
  5787. return titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5788. case 'water':
  5789. return titans.filter(e => e.id.toString().slice(2, 3) == '0').map(e => e.id);
  5790. case 'fire':
  5791. return titans.filter(e => e.id.toString().slice(2, 3) == '1').map(e => e.id);
  5792. case 'earth':
  5793. return titans.filter(e => e.id.toString().slice(2, 3) == '2').map(e => e.id);
  5794. }
  5795. }
  5796.  
  5797. function getNeutralTeam() {
  5798. const titans = titanGetAll.filter(e => !titansStates[e.id]?.isDead)
  5799. return titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5800. }
  5801.  
  5802. function fixTitanTeam(titans) {
  5803. titans.heroes = titans.heroes.filter(e => !titansStates[e]?.isDead);
  5804. return titans;
  5805. }
  5806.  
  5807. /**
  5808. * Checking the floor
  5809. *
  5810. * Проверяем этаж
  5811. */
  5812. async function checkFloor(dungeonInfo) {
  5813. if (!('floor' in dungeonInfo) || dungeonInfo.floor?.state == 2) {
  5814. saveProgress();
  5815. return;
  5816. }
  5817. checkTalent(dungeonInfo);
  5818. // console.log(dungeonInfo, dungeonActivity);
  5819. setProgress(`${I18N('DUNGEON')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity} ${talentMsg}`);
  5820. if (dungeonActivity >= maxDungeonActivity) {
  5821. endDungeon('endDungeon', 'maxActive ' + dungeonActivity + '/' + maxDungeonActivity);
  5822. return;
  5823. }
  5824. titansStates = dungeonInfo.states.titans;
  5825. titanStats = titanObjToArray(titansStates);
  5826. const floorChoices = dungeonInfo.floor.userData;
  5827. const floorType = dungeonInfo.floorType;
  5828. //const primeElement = dungeonInfo.elements.prime;
  5829. if (floorType == "battle") {
  5830. const calls = [];
  5831. for (let teamNum in floorChoices) {
  5832. attackerType = floorChoices[teamNum].attackerType;
  5833. const args = fixTitanTeam(teams[attackerType]);
  5834. if (attackerType == 'neutral') {
  5835. args.heroes = getNeutralTeam();
  5836. }
  5837. if (!args.heroes.length) {
  5838. continue;
  5839. }
  5840. args.teamNum = teamNum;
  5841. calls.push({
  5842. name: "dungeonStartBattle",
  5843. args,
  5844. ident: "body_" + teamNum
  5845. })
  5846. }
  5847. if (!calls.length) {
  5848. endDungeon('endDungeon', 'All Dead');
  5849. return;
  5850. }
  5851. const battleDatas = await Send(JSON.stringify({ calls }))
  5852. .then(e => e.results.map(n => n.result.response))
  5853. const battleResults = [];
  5854. for (n in battleDatas) {
  5855. battleData = battleDatas[n]
  5856. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  5857. battleResults.push(await Calc(battleData).then(result => {
  5858. result.teamNum = n;
  5859. result.attackerType = floorChoices[n].attackerType;
  5860. return result;
  5861. }));
  5862. }
  5863. processingPromises(battleResults)
  5864. }
  5865. }
  5866.  
  5867. async function checkTalent(dungeonInfo) {
  5868. const talent = dungeonInfo.talent;
  5869. if (!talent) {
  5870. return;
  5871. }
  5872. const dungeonFloor = +dungeonInfo.floorNumber;
  5873. const talentFloor = +talent.floorRandValue;
  5874. let doorsAmount = 3 - talent.conditions.doorsAmount;
  5875.  
  5876. if (dungeonFloor === talentFloor && (!doorsAmount || !talent.conditions?.farmedDoors[dungeonFloor])) {
  5877. const reward = await Send({
  5878. calls: [
  5879. { name: 'heroTalent_getReward', args: { talentType: 'tmntDungeonTalent', reroll: false }, ident: 'group_0_body' },
  5880. { name: 'heroTalent_farmReward', args: { talentType: 'tmntDungeonTalent' }, ident: 'group_1_body' },
  5881. ],
  5882. }).then((e) => e.results[0].result.response);
  5883. const type = Object.keys(reward).pop();
  5884. const itemId = Object.keys(reward[type]).pop();
  5885. const count = reward[type][itemId];
  5886. const itemName = cheats.translate(`LIB_${type.toUpperCase()}_NAME_${itemId}`);
  5887. talentMsgReward += `<br> ${count} ${itemName}`;
  5888. doorsAmount++;
  5889. }
  5890. talentMsg = `<br>TMNT Talent: ${doorsAmount}/3 ${talentMsgReward}<br>`;
  5891. }
  5892.  
  5893. function processingPromises(results) {
  5894. let selectBattle = results[0];
  5895. if (results.length < 2) {
  5896. // console.log(selectBattle);
  5897. if (!selectBattle.result.win) {
  5898. endDungeon('dungeonEndBattle\n', selectBattle);
  5899. return;
  5900. }
  5901. endBattle(selectBattle);
  5902. return;
  5903. }
  5904.  
  5905. selectBattle = false;
  5906. let bestState = -1000;
  5907. for (const result of results) {
  5908. const recovery = getState(result);
  5909. if (recovery > bestState) {
  5910. bestState = recovery;
  5911. selectBattle = result
  5912. }
  5913. }
  5914. // console.log(selectBattle.teamNum, results);
  5915. if (!selectBattle || bestState <= -1000) {
  5916. endDungeon('dungeonEndBattle\n', results);
  5917. return;
  5918. }
  5919.  
  5920. startBattle(selectBattle.teamNum, selectBattle.attackerType)
  5921. .then(endBattle);
  5922. }
  5923.  
  5924. /**
  5925. * Let's start the fight
  5926. *
  5927. * Начинаем бой
  5928. */
  5929. function startBattle(teamNum, attackerType) {
  5930. return new Promise(function (resolve, reject) {
  5931. args = fixTitanTeam(teams[attackerType]);
  5932. args.teamNum = teamNum;
  5933. if (attackerType == 'neutral') {
  5934. const titans = titanGetAll.filter(e => !titansStates[e.id]?.isDead)
  5935. args.heroes = titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5936. }
  5937. startBattleCall = {
  5938. calls: [{
  5939. name: "dungeonStartBattle",
  5940. args,
  5941. ident: "body"
  5942. }]
  5943. }
  5944. send(JSON.stringify(startBattleCall), resultBattle, {
  5945. resolve,
  5946. teamNum,
  5947. attackerType
  5948. });
  5949. });
  5950. }
  5951. /**
  5952. * Returns the result of the battle in a promise
  5953. *
  5954. * Возращает резульат боя в промис
  5955. */
  5956. function resultBattle(resultBattles, args) {
  5957. battleData = resultBattles.results[0].result.response;
  5958. battleType = "get_tower";
  5959. if (battleData.type == "dungeon_titan") {
  5960. battleType = "get_titan";
  5961. }
  5962. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  5963. BattleCalc(battleData, battleType, function (result) {
  5964. result.teamNum = args.teamNum;
  5965. result.attackerType = args.attackerType;
  5966. args.resolve(result);
  5967. });
  5968. }
  5969. /**
  5970. * Finishing the fight
  5971. *
  5972. * Заканчиваем бой
  5973. */
  5974. async function endBattle(battleInfo) {
  5975. if (battleInfo.result.win) {
  5976. const args = {
  5977. result: battleInfo.result,
  5978. progress: battleInfo.progress,
  5979. }
  5980. if (countPredictionCard > 0) {
  5981. args.isRaid = true;
  5982. } else {
  5983. const timer = getTimer(battleInfo.battleTime);
  5984. console.log(timer);
  5985. await countdownTimer(timer, `${I18N('DUNGEON')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity} ${talentMsg}`);
  5986. }
  5987. const calls = [{
  5988. name: "dungeonEndBattle",
  5989. args,
  5990. ident: "body"
  5991. }];
  5992. lastDungeonBattleData = null;
  5993. send(JSON.stringify({ calls }), resultEndBattle);
  5994. } else {
  5995. endDungeon('dungeonEndBattle win: false\n', battleInfo);
  5996. }
  5997. }
  5998.  
  5999. /**
  6000. * Getting and processing battle results
  6001. *
  6002. * Получаем и обрабатываем результаты боя
  6003. */
  6004. function resultEndBattle(e) {
  6005. if ('error' in e) {
  6006. popup.confirm(I18N('ERROR_MSG', {
  6007. name: e.error.name,
  6008. description: e.error.description,
  6009. }));
  6010. endDungeon('errorRequest', e);
  6011. return;
  6012. }
  6013. battleResult = e.results[0].result.response;
  6014. if ('error' in battleResult) {
  6015. endDungeon('errorBattleResult', battleResult);
  6016. return;
  6017. }
  6018. dungeonGetInfo = battleResult.dungeon ?? battleResult;
  6019. dungeonActivity += battleResult.reward.dungeonActivity ?? 0;
  6020. checkFloor(dungeonGetInfo);
  6021. }
  6022.  
  6023. /**
  6024. * Returns the coefficient of condition of the
  6025. * difference in titanium before and after the battle
  6026. *
  6027. * Возвращает коэффициент состояния титанов после боя
  6028. */
  6029. function getState(result) {
  6030. if (!result.result.win) {
  6031. return -1000;
  6032. }
  6033.  
  6034. let beforeSumFactor = 0;
  6035. const beforeTitans = result.battleData.attackers;
  6036. for (let titanId in beforeTitans) {
  6037. const titan = beforeTitans[titanId];
  6038. const state = titan.state;
  6039. let factor = 1;
  6040. if (state) {
  6041. const hp = state.hp / titan.hp;
  6042. const energy = state.energy / 1e3;
  6043. factor = hp + energy / 20
  6044. }
  6045. beforeSumFactor += factor;
  6046. }
  6047.  
  6048. let afterSumFactor = 0;
  6049. const afterTitans = result.progress[0].attackers.heroes;
  6050. for (let titanId in afterTitans) {
  6051. const titan = afterTitans[titanId];
  6052. const hp = titan.hp / beforeTitans[titanId].hp;
  6053. const energy = titan.energy / 1e3;
  6054. const factor = hp + energy / 20;
  6055. afterSumFactor += factor;
  6056. }
  6057. return afterSumFactor - beforeSumFactor;
  6058. }
  6059.  
  6060. /**
  6061. * Converts an object with IDs to an array with IDs
  6062. *
  6063. * Преобразует объект с идетификаторами в массив с идетификаторами
  6064. */
  6065. function titanObjToArray(obj) {
  6066. let titans = [];
  6067. for (let id in obj) {
  6068. obj[id].id = id;
  6069. titans.push(obj[id]);
  6070. }
  6071. return titans;
  6072. }
  6073.  
  6074. function saveProgress() {
  6075. let saveProgressCall = {
  6076. calls: [{
  6077. name: "dungeonSaveProgress",
  6078. args: {},
  6079. ident: "body"
  6080. }]
  6081. }
  6082. send(JSON.stringify(saveProgressCall), resultEndBattle);
  6083. }
  6084.  
  6085. function endDungeon(reason, info) {
  6086. console.warn(reason, info);
  6087. setProgress(`${I18N('DUNGEON')} ${I18N('COMPLETED')}`, true);
  6088. resolve();
  6089. }
  6090. }
  6091.  
  6092. this.HWHClasses.executeDungeon = executeDungeon;
  6093.  
  6094. /**
  6095. * Passing the tower
  6096. *
  6097. * Прохождение башни
  6098. */
  6099. function testTower() {
  6100. const { executeTower } = HWHClasses;
  6101. return new Promise((resolve, reject) => {
  6102. tower = new executeTower(resolve, reject);
  6103. tower.start();
  6104. });
  6105. }
  6106.  
  6107. /**
  6108. * Passing the tower
  6109. *
  6110. * Прохождение башни
  6111. */
  6112. function executeTower(resolve, reject) {
  6113. lastTowerInfo = {};
  6114.  
  6115. scullCoin = 0;
  6116.  
  6117. heroGetAll = [];
  6118.  
  6119. heroesStates = {};
  6120.  
  6121. argsBattle = {
  6122. heroes: [],
  6123. favor: {},
  6124. };
  6125.  
  6126. callsExecuteTower = {
  6127. calls: [{
  6128. name: "towerGetInfo",
  6129. args: {},
  6130. ident: "towerGetInfo"
  6131. }, {
  6132. name: "teamGetAll",
  6133. args: {},
  6134. ident: "teamGetAll"
  6135. }, {
  6136. name: "teamGetFavor",
  6137. args: {},
  6138. ident: "teamGetFavor"
  6139. }, {
  6140. name: "inventoryGet",
  6141. args: {},
  6142. ident: "inventoryGet"
  6143. }, {
  6144. name: "heroGetAll",
  6145. args: {},
  6146. ident: "heroGetAll"
  6147. }]
  6148. }
  6149.  
  6150. buffIds = [
  6151. {id: 0, cost: 0, isBuy: false}, // plug // заглушка
  6152. {id: 1, cost: 1, isBuy: true}, // 3% attack // 3% атака
  6153. {id: 2, cost: 6, isBuy: true}, // 2% attack // 2% атака
  6154. {id: 3, cost: 16, isBuy: true}, // 4% attack // 4% атака
  6155. {id: 4, cost: 40, isBuy: true}, // 8% attack // 8% атака
  6156. {id: 5, cost: 1, isBuy: true}, // 10% armor // 10% броня
  6157. {id: 6, cost: 6, isBuy: true}, // 5% armor // 5% броня
  6158. {id: 7, cost: 16, isBuy: true}, // 10% armor // 10% броня
  6159. {id: 8, cost: 40, isBuy: true}, // 20% armor // 20% броня
  6160. { id: 9, cost: 1, isBuy: true }, // 10% protection from magic // 10% защита от магии
  6161. { id: 10, cost: 6, isBuy: true }, // 5% protection from magic // 5% защита от магии
  6162. { id: 11, cost: 16, isBuy: true }, // 10% protection from magic // 10% защита от магии
  6163. { id: 12, cost: 40, isBuy: true }, // 20% protection from magic // 20% защита от магии
  6164. { id: 13, cost: 1, isBuy: false }, // 40% health hero // 40% здоровья герою
  6165. { id: 14, cost: 6, isBuy: false }, // 40% health hero // 40% здоровья герою
  6166. { id: 15, cost: 16, isBuy: false }, // 80% health hero // 80% здоровья герою
  6167. { id: 16, cost: 40, isBuy: false }, // 40% health to all heroes // 40% здоровья всем героям
  6168. { id: 17, cost: 1, isBuy: false }, // 40% energy to the hero // 40% энергии герою
  6169. { id: 18, cost: 3, isBuy: false }, // 40% energy to the hero // 40% энергии герою
  6170. { id: 19, cost: 8, isBuy: false }, // 80% energy to the hero // 80% энергии герою
  6171. { id: 20, cost: 20, isBuy: false }, // 40% energy to all heroes // 40% энергии всем героям
  6172. { id: 21, cost: 40, isBuy: false }, // Hero Resurrection // Воскрешение героя
  6173. ]
  6174.  
  6175. this.start = function () {
  6176. send(JSON.stringify(callsExecuteTower), startTower);
  6177. }
  6178.  
  6179. /**
  6180. * Getting data on the Tower
  6181. *
  6182. * Получаем данные по башне
  6183. */
  6184. function startTower(e) {
  6185. res = e.results;
  6186. towerGetInfo = res[0].result.response;
  6187. if (!towerGetInfo) {
  6188. endTower('noTower', res);
  6189. return;
  6190. }
  6191. teamGetAll = res[1].result.response;
  6192. teamGetFavor = res[2].result.response;
  6193. inventoryGet = res[3].result.response;
  6194. heroGetAll = Object.values(res[4].result.response);
  6195.  
  6196. scullCoin = inventoryGet.coin[7] ?? 0;
  6197.  
  6198. argsBattle.favor = teamGetFavor.tower;
  6199. argsBattle.heroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  6200. pet = teamGetAll.tower.filter(id => id >= 6000).pop();
  6201. if (pet) {
  6202. argsBattle.pet = pet;
  6203. }
  6204.  
  6205. checkFloor(towerGetInfo);
  6206. }
  6207.  
  6208. function fixHeroesTeam(argsBattle) {
  6209. let fixHeroes = argsBattle.heroes.filter(e => !heroesStates[e]?.isDead);
  6210. if (fixHeroes.length < 5) {
  6211. heroGetAll = heroGetAll.filter(e => !heroesStates[e.id]?.isDead);
  6212. fixHeroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  6213. Object.keys(argsBattle.favor).forEach(e => {
  6214. if (!fixHeroes.includes(+e)) {
  6215. delete argsBattle.favor[e];
  6216. }
  6217. })
  6218. }
  6219. argsBattle.heroes = fixHeroes;
  6220. return argsBattle;
  6221. }
  6222.  
  6223. /**
  6224. * Check the floor
  6225. *
  6226. * Проверяем этаж
  6227. */
  6228. function checkFloor(towerInfo) {
  6229. lastTowerInfo = towerInfo;
  6230. maySkipFloor = +towerInfo.maySkipFloor;
  6231. floorNumber = +towerInfo.floorNumber;
  6232. heroesStates = towerInfo.states.heroes;
  6233. floorInfo = towerInfo.floor;
  6234.  
  6235. /**
  6236. * Is there at least one chest open on the floor
  6237. * Открыт ли на этаже хоть один сундук
  6238. */
  6239. isOpenChest = false;
  6240. if (towerInfo.floorType == "chest") {
  6241. isOpenChest = towerInfo.floor.chests.reduce((n, e) => n + e.opened, 0);
  6242. }
  6243.  
  6244. setProgress(`${I18N('TOWER')}: ${I18N('FLOOR')} ${floorNumber}`);
  6245. if (floorNumber > 49) {
  6246. if (isOpenChest) {
  6247. endTower('alreadyOpenChest 50 floor', floorNumber);
  6248. return;
  6249. }
  6250. }
  6251. /**
  6252. * If the chest is open and you can skip floors, then move on
  6253. * Если сундук открыт и можно скипать этажи, то переходим дальше
  6254. */
  6255. if (towerInfo.mayFullSkip && +towerInfo.teamLevel == 130) {
  6256. if (floorNumber == 1) {
  6257. fullSkipTower();
  6258. return;
  6259. }
  6260. if (isOpenChest) {
  6261. nextOpenChest(floorNumber);
  6262. } else {
  6263. nextChestOpen(floorNumber);
  6264. }
  6265. return;
  6266. }
  6267.  
  6268. // console.log(towerInfo, scullCoin);
  6269. switch (towerInfo.floorType) {
  6270. case "battle":
  6271. if (floorNumber <= maySkipFloor) {
  6272. skipFloor();
  6273. return;
  6274. }
  6275. if (floorInfo.state == 2) {
  6276. nextFloor();
  6277. return;
  6278. }
  6279. startBattle().then(endBattle);
  6280. return;
  6281. case "buff":
  6282. checkBuff(towerInfo);
  6283. return;
  6284. case "chest":
  6285. openChest(floorNumber);
  6286. return;
  6287. default:
  6288. console.log('!', towerInfo.floorType, towerInfo);
  6289. break;
  6290. }
  6291. }
  6292.  
  6293. /**
  6294. * Let's start the fight
  6295. *
  6296. * Начинаем бой
  6297. */
  6298. function startBattle() {
  6299. return new Promise(function (resolve, reject) {
  6300. towerStartBattle = {
  6301. calls: [{
  6302. name: "towerStartBattle",
  6303. args: fixHeroesTeam(argsBattle),
  6304. ident: "body"
  6305. }]
  6306. }
  6307. send(JSON.stringify(towerStartBattle), resultBattle, resolve);
  6308. });
  6309. }
  6310. /**
  6311. * Returns the result of the battle in a promise
  6312. *
  6313. * Возращает резульат боя в промис
  6314. */
  6315. function resultBattle(resultBattles, resolve) {
  6316. battleData = resultBattles.results[0].result.response;
  6317. battleType = "get_tower";
  6318. BattleCalc(battleData, battleType, function (result) {
  6319. resolve(result);
  6320. });
  6321. }
  6322. /**
  6323. * Finishing the fight
  6324. *
  6325. * Заканчиваем бой
  6326. */
  6327. function endBattle(battleInfo) {
  6328. if (battleInfo.result.stars >= 3) {
  6329. endBattleCall = {
  6330. calls: [{
  6331. name: "towerEndBattle",
  6332. args: {
  6333. result: battleInfo.result,
  6334. progress: battleInfo.progress,
  6335. },
  6336. ident: "body"
  6337. }]
  6338. }
  6339. send(JSON.stringify(endBattleCall), resultEndBattle);
  6340. } else {
  6341. endTower('towerEndBattle win: false\n', battleInfo);
  6342. }
  6343. }
  6344.  
  6345. /**
  6346. * Getting and processing battle results
  6347. *
  6348. * Получаем и обрабатываем результаты боя
  6349. */
  6350. function resultEndBattle(e) {
  6351. battleResult = e.results[0].result.response;
  6352. if ('error' in battleResult) {
  6353. endTower('errorBattleResult', battleResult);
  6354. return;
  6355. }
  6356. if ('reward' in battleResult) {
  6357. scullCoin += battleResult.reward?.coin[7] ?? 0;
  6358. }
  6359. nextFloor();
  6360. }
  6361.  
  6362. function nextFloor() {
  6363. nextFloorCall = {
  6364. calls: [{
  6365. name: "towerNextFloor",
  6366. args: {},
  6367. ident: "body"
  6368. }]
  6369. }
  6370. send(JSON.stringify(nextFloorCall), checkDataFloor);
  6371. }
  6372.  
  6373. function openChest(floorNumber) {
  6374. floorNumber = floorNumber || 0;
  6375. openChestCall = {
  6376. calls: [{
  6377. name: "towerOpenChest",
  6378. args: {
  6379. num: 2
  6380. },
  6381. ident: "body"
  6382. }]
  6383. }
  6384. send(JSON.stringify(openChestCall), floorNumber < 50 ? nextFloor : lastChest);
  6385. }
  6386.  
  6387. function lastChest() {
  6388. endTower('openChest 50 floor', floorNumber);
  6389. }
  6390.  
  6391. function skipFloor() {
  6392. skipFloorCall = {
  6393. calls: [{
  6394. name: "towerSkipFloor",
  6395. args: {},
  6396. ident: "body"
  6397. }]
  6398. }
  6399. send(JSON.stringify(skipFloorCall), checkDataFloor);
  6400. }
  6401.  
  6402. function checkBuff(towerInfo) {
  6403. buffArr = towerInfo.floor;
  6404. promises = [];
  6405. for (let buff of buffArr) {
  6406. buffInfo = buffIds[buff.id];
  6407. if (buffInfo.isBuy && buffInfo.cost <= scullCoin) {
  6408. scullCoin -= buffInfo.cost;
  6409. promises.push(buyBuff(buff.id));
  6410. }
  6411. }
  6412. Promise.all(promises).then(nextFloor);
  6413. }
  6414.  
  6415. function buyBuff(buffId) {
  6416. return new Promise(function (resolve, reject) {
  6417. buyBuffCall = {
  6418. calls: [{
  6419. name: "towerBuyBuff",
  6420. args: {
  6421. buffId
  6422. },
  6423. ident: "body"
  6424. }]
  6425. }
  6426. send(JSON.stringify(buyBuffCall), resolve);
  6427. });
  6428. }
  6429.  
  6430. function checkDataFloor(result) {
  6431. towerInfo = result.results[0].result.response;
  6432. if ('reward' in towerInfo && towerInfo.reward?.coin) {
  6433. scullCoin += towerInfo.reward?.coin[7] ?? 0;
  6434. }
  6435. if ('tower' in towerInfo) {
  6436. towerInfo = towerInfo.tower;
  6437. }
  6438. if ('skullReward' in towerInfo) {
  6439. scullCoin += towerInfo.skullReward?.coin[7] ?? 0;
  6440. }
  6441. checkFloor(towerInfo);
  6442. }
  6443. /**
  6444. * Getting tower rewards
  6445. *
  6446. * Получаем награды башни
  6447. */
  6448. function farmTowerRewards(reason) {
  6449. let { pointRewards, points } = lastTowerInfo;
  6450. let pointsAll = Object.getOwnPropertyNames(pointRewards);
  6451. let farmPoints = pointsAll.filter(e => +e <= +points && !pointRewards[e]);
  6452. if (!farmPoints.length) {
  6453. return;
  6454. }
  6455. let farmTowerRewardsCall = {
  6456. calls: [{
  6457. name: "tower_farmPointRewards",
  6458. args: {
  6459. points: farmPoints
  6460. },
  6461. ident: "tower_farmPointRewards"
  6462. }]
  6463. }
  6464.  
  6465. if (scullCoin > 0) {
  6466. farmTowerRewardsCall.calls.push({
  6467. name: "tower_farmSkullReward",
  6468. args: {},
  6469. ident: "tower_farmSkullReward"
  6470. });
  6471. }
  6472.  
  6473. send(JSON.stringify(farmTowerRewardsCall), () => { });
  6474. }
  6475.  
  6476. function fullSkipTower() {
  6477. /**
  6478. * Next chest
  6479. *
  6480. * Следующий сундук
  6481. */
  6482. function nextChest(n) {
  6483. return {
  6484. name: "towerNextChest",
  6485. args: {},
  6486. ident: "group_" + n + "_body"
  6487. }
  6488. }
  6489. /**
  6490. * Open chest
  6491. *
  6492. * Открыть сундук
  6493. */
  6494. function openChest(n) {
  6495. return {
  6496. name: "towerOpenChest",
  6497. args: {
  6498. "num": 2
  6499. },
  6500. ident: "group_" + n + "_body"
  6501. }
  6502. }
  6503.  
  6504. const fullSkipTowerCall = {
  6505. calls: []
  6506. }
  6507.  
  6508. let n = 0;
  6509. for (let i = 0; i < 15; i++) {
  6510. // 15 сундуков
  6511. fullSkipTowerCall.calls.push(nextChest(++n));
  6512. fullSkipTowerCall.calls.push(openChest(++n));
  6513. // +5 сундуков, 250 изюма // towerOpenChest
  6514. // if (i < 5) {
  6515. // fullSkipTowerCall.calls.push(openChest(++n, 2));
  6516. // }
  6517. }
  6518.  
  6519. fullSkipTowerCall.calls.push({
  6520. name: 'towerGetInfo',
  6521. args: {},
  6522. ident: 'group_' + ++n + '_body',
  6523. });
  6524.  
  6525. send(JSON.stringify(fullSkipTowerCall), data => {
  6526. for (const r of data.results) {
  6527. const towerInfo = r?.result?.response;
  6528. if (towerInfo && 'skullReward' in towerInfo) {
  6529. scullCoin += towerInfo.skullReward?.coin[7] ?? 0;
  6530. }
  6531. }
  6532. data.results[0] = data.results[data.results.length - 1];
  6533. checkDataFloor(data);
  6534. });
  6535. }
  6536.  
  6537. function nextChestOpen(floorNumber) {
  6538. const calls = [{
  6539. name: "towerOpenChest",
  6540. args: {
  6541. num: 2
  6542. },
  6543. ident: "towerOpenChest"
  6544. }];
  6545.  
  6546. Send(JSON.stringify({ calls })).then(e => {
  6547. nextOpenChest(floorNumber);
  6548. });
  6549. }
  6550.  
  6551. function nextOpenChest(floorNumber) {
  6552. if (floorNumber > 49) {
  6553. endTower('openChest 50 floor', floorNumber);
  6554. return;
  6555. }
  6556.  
  6557. let nextOpenChestCall = {
  6558. calls: [{
  6559. name: "towerNextChest",
  6560. args: {},
  6561. ident: "towerNextChest"
  6562. }, {
  6563. name: "towerOpenChest",
  6564. args: {
  6565. num: 2
  6566. },
  6567. ident: "towerOpenChest"
  6568. }]
  6569. }
  6570. send(JSON.stringify(nextOpenChestCall), checkDataFloor);
  6571. }
  6572.  
  6573. function endTower(reason, info) {
  6574. console.log(reason, info);
  6575. if (reason != 'noTower') {
  6576. farmTowerRewards(reason);
  6577. }
  6578. setProgress(`${I18N('TOWER')} ${I18N('COMPLETED')}!`, true);
  6579. resolve();
  6580. }
  6581. }
  6582.  
  6583. this.HWHClasses.executeTower = executeTower;
  6584.  
  6585. /**
  6586. * Passage of the arena of the titans
  6587. *
  6588. * Прохождение арены титанов
  6589. */
  6590. function testTitanArena() {
  6591. const { executeTitanArena } = HWHClasses;
  6592. return new Promise((resolve, reject) => {
  6593. titAren = new executeTitanArena(resolve, reject);
  6594. titAren.start();
  6595. });
  6596. }
  6597.  
  6598. /**
  6599. * Passage of the arena of the titans
  6600. *
  6601. * Прохождение арены титанов
  6602. */
  6603. function executeTitanArena(resolve, reject) {
  6604. let titan_arena = [];
  6605. let finishListBattle = [];
  6606. /**
  6607. * ID of the current batch
  6608. *
  6609. * Идетификатор текущей пачки
  6610. */
  6611. let currentRival = 0;
  6612. /**
  6613. * Number of attempts to finish off the pack
  6614. *
  6615. * Количество попыток добития пачки
  6616. */
  6617. let attempts = 0;
  6618. /**
  6619. * Was there an attempt to finish off the current shooting range
  6620. *
  6621. * Была ли попытка добития текущего тира
  6622. */
  6623. let isCheckCurrentTier = false;
  6624. /**
  6625. * Current shooting range
  6626. *
  6627. * Текущий тир
  6628. */
  6629. let currTier = 0;
  6630. /**
  6631. * Number of battles on the current dash
  6632. *
  6633. * Количество битв на текущем тире
  6634. */
  6635. let countRivalsTier = 0;
  6636.  
  6637. let callsStart = {
  6638. calls: [{
  6639. name: "titanArenaGetStatus",
  6640. args: {},
  6641. ident: "titanArenaGetStatus"
  6642. }, {
  6643. name: "teamGetAll",
  6644. args: {},
  6645. ident: "teamGetAll"
  6646. }]
  6647. }
  6648.  
  6649. this.start = function () {
  6650. send(JSON.stringify(callsStart), startTitanArena);
  6651. }
  6652.  
  6653. function startTitanArena(data) {
  6654. let titanArena = data.results[0].result.response;
  6655. if (titanArena.status == 'disabled') {
  6656. endTitanArena('disabled', titanArena);
  6657. return;
  6658. }
  6659.  
  6660. let teamGetAll = data.results[1].result.response;
  6661. titan_arena = teamGetAll.titan_arena;
  6662.  
  6663. checkTier(titanArena)
  6664. }
  6665.  
  6666. function checkTier(titanArena) {
  6667. if (titanArena.status == "peace_time") {
  6668. endTitanArena('Peace_time', titanArena);
  6669. return;
  6670. }
  6671. currTier = titanArena.tier;
  6672. if (currTier) {
  6673. setProgress(`${I18N('TITAN_ARENA')}: ${I18N('LEVEL')} ${currTier}`);
  6674. }
  6675.  
  6676. if (titanArena.status == "completed_tier") {
  6677. titanArenaCompleteTier();
  6678. return;
  6679. }
  6680. /**
  6681. * Checking for the possibility of a raid
  6682. * Проверка на возможность рейда
  6683. */
  6684. if (titanArena.canRaid) {
  6685. titanArenaStartRaid();
  6686. return;
  6687. }
  6688. /**
  6689. * Check was an attempt to achieve the current shooting range
  6690. * Проверка была ли попытка добития текущего тира
  6691. */
  6692. if (!isCheckCurrentTier) {
  6693. checkRivals(titanArena.rivals);
  6694. return;
  6695. }
  6696.  
  6697. endTitanArena('Done or not canRaid', titanArena);
  6698. }
  6699. /**
  6700. * Submit dash information for verification
  6701. *
  6702. * Отправка информации о тире на проверку
  6703. */
  6704. function checkResultInfo(data) {
  6705. let titanArena = data.results[0].result.response;
  6706. checkTier(titanArena);
  6707. }
  6708. /**
  6709. * Finish the current tier
  6710. *
  6711. * Завершить текущий тир
  6712. */
  6713. function titanArenaCompleteTier() {
  6714. isCheckCurrentTier = false;
  6715. let calls = [{
  6716. name: "titanArenaCompleteTier",
  6717. args: {},
  6718. ident: "body"
  6719. }];
  6720. send(JSON.stringify({calls}), checkResultInfo);
  6721. }
  6722. /**
  6723. * Gathering points to be completed
  6724. *
  6725. * Собираем точки которые нужно добить
  6726. */
  6727. function checkRivals(rivals) {
  6728. finishListBattle = [];
  6729. for (let n in rivals) {
  6730. if (rivals[n].attackScore < 250) {
  6731. finishListBattle.push(n);
  6732. }
  6733. }
  6734. console.log('checkRivals', finishListBattle);
  6735. countRivalsTier = finishListBattle.length;
  6736. roundRivals();
  6737. }
  6738. /**
  6739. * Selecting the next point to finish off
  6740. *
  6741. * Выбор следующей точки для добития
  6742. */
  6743. function roundRivals() {
  6744. let countRivals = finishListBattle.length;
  6745. if (!countRivals) {
  6746. /**
  6747. * Whole range checked
  6748. *
  6749. * Весь тир проверен
  6750. */
  6751. isCheckCurrentTier = true;
  6752. titanArenaGetStatus();
  6753. return;
  6754. }
  6755. // setProgress('TitanArena: Уровень ' + currTier + ' Бои: ' + (countRivalsTier - countRivals + 1) + '/' + countRivalsTier);
  6756. currentRival = finishListBattle.pop();
  6757. attempts = +currentRival;
  6758. // console.log('roundRivals', currentRival);
  6759. titanArenaStartBattle(currentRival);
  6760. }
  6761. /**
  6762. * The start of a solo battle
  6763. *
  6764. * Начало одиночной битвы
  6765. */
  6766. function titanArenaStartBattle(rivalId) {
  6767. let calls = [{
  6768. name: "titanArenaStartBattle",
  6769. args: {
  6770. rivalId: rivalId,
  6771. titans: titan_arena
  6772. },
  6773. ident: "body"
  6774. }];
  6775. send(JSON.stringify({calls}), calcResult);
  6776. }
  6777. /**
  6778. * Calculation of the results of the battle
  6779. *
  6780. * Расчет результатов боя
  6781. */
  6782. function calcResult(data) {
  6783. let battlesInfo = data.results[0].result.response.battle;
  6784. /**
  6785. * If attempts are equal to the current battle number we make
  6786. * Если попытки равны номеру текущего боя делаем прерасчет
  6787. */
  6788. if (attempts == currentRival) {
  6789. preCalcBattle(battlesInfo);
  6790. return;
  6791. }
  6792. /**
  6793. * If there are still attempts, we calculate a new battle
  6794. * Если попытки еще есть делаем расчет нового боя
  6795. */
  6796. if (attempts > 0) {
  6797. attempts--;
  6798. calcBattleResult(battlesInfo)
  6799. .then(resultCalcBattle);
  6800. return;
  6801. }
  6802. /**
  6803. * Otherwise, go to the next opponent
  6804. * Иначе переходим к следующему сопернику
  6805. */
  6806. roundRivals();
  6807. }
  6808. /**
  6809. * Processing the results of the battle calculation
  6810. *
  6811. * Обработка результатов расчета битвы
  6812. */
  6813. function resultCalcBattle(resultBattle) {
  6814. // console.log('resultCalcBattle', currentRival, attempts, resultBattle.result.win);
  6815. /**
  6816. * If the current calculation of victory is not a chance or the attempt ended with the finish the battle
  6817. * Если текущий расчет победа или шансов нет или попытки кончились завершаем бой
  6818. */
  6819. if (resultBattle.result.win || !attempts) {
  6820. titanArenaEndBattle({
  6821. progress: resultBattle.progress,
  6822. result: resultBattle.result,
  6823. rivalId: resultBattle.battleData.typeId
  6824. });
  6825. return;
  6826. }
  6827. /**
  6828. * If not victory and there are attempts we start a new battle
  6829. * Если не победа и есть попытки начинаем новый бой
  6830. */
  6831. titanArenaStartBattle(resultBattle.battleData.typeId);
  6832. }
  6833. /**
  6834. * Returns the promise of calculating the results of the battle
  6835. *
  6836. * Возращает промис расчета результатов битвы
  6837. */
  6838. function getBattleInfo(battle, isRandSeed) {
  6839. return new Promise(function (resolve) {
  6840. if (isRandSeed) {
  6841. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  6842. }
  6843. // console.log(battle.seed);
  6844. BattleCalc(battle, "get_titanClanPvp", e => resolve(e));
  6845. });
  6846. }
  6847. /**
  6848. * Recalculate battles
  6849. *
  6850. * Прерасчтет битвы
  6851. */
  6852. function preCalcBattle(battle) {
  6853. let actions = [getBattleInfo(battle, false)];
  6854. const countTestBattle = getInput('countTestBattle');
  6855. for (let i = 0; i < countTestBattle; i++) {
  6856. actions.push(getBattleInfo(battle, true));
  6857. }
  6858. Promise.all(actions)
  6859. .then(resultPreCalcBattle);
  6860. }
  6861. /**
  6862. * Processing the results of the battle recalculation
  6863. *
  6864. * Обработка результатов прерасчета битвы
  6865. */
  6866. function resultPreCalcBattle(e) {
  6867. let wins = e.map(n => n.result.win);
  6868. let firstBattle = e.shift();
  6869. let countWin = wins.reduce((w, s) => w + s);
  6870. const countTestBattle = getInput('countTestBattle');
  6871. console.log('resultPreCalcBattle', `${countWin}/${countTestBattle}`)
  6872. if (countWin > 0) {
  6873. attempts = getInput('countAutoBattle');
  6874. } else {
  6875. attempts = 0;
  6876. }
  6877. resultCalcBattle(firstBattle);
  6878. }
  6879.  
  6880. /**
  6881. * Complete an arena battle
  6882. *
  6883. * Завершить битву на арене
  6884. */
  6885. function titanArenaEndBattle(args) {
  6886. let calls = [{
  6887. name: "titanArenaEndBattle",
  6888. args,
  6889. ident: "body"
  6890. }];
  6891. send(JSON.stringify({calls}), resultTitanArenaEndBattle);
  6892. }
  6893.  
  6894. function resultTitanArenaEndBattle(e) {
  6895. let attackScore = e.results[0].result.response.attackScore;
  6896. let numReval = countRivalsTier - finishListBattle.length;
  6897. setProgress(`${I18N('TITAN_ARENA')}: ${I18N('LEVEL')} ${currTier} </br>${I18N('BATTLES')}: ${numReval}/${countRivalsTier} - ${attackScore}`);
  6898. /**
  6899. * TODO: Might need to improve the results.
  6900. * TODO: Возможно стоит сделать улучшение результатов
  6901. */
  6902. // console.log('resultTitanArenaEndBattle', e)
  6903. console.log('resultTitanArenaEndBattle', numReval + '/' + countRivalsTier, attempts)
  6904. roundRivals();
  6905. }
  6906. /**
  6907. * Arena State
  6908. *
  6909. * Состояние арены
  6910. */
  6911. function titanArenaGetStatus() {
  6912. let calls = [{
  6913. name: "titanArenaGetStatus",
  6914. args: {},
  6915. ident: "body"
  6916. }];
  6917. send(JSON.stringify({calls}), checkResultInfo);
  6918. }
  6919. /**
  6920. * Arena Raid Request
  6921. *
  6922. * Запрос рейда арены
  6923. */
  6924. function titanArenaStartRaid() {
  6925. let calls = [{
  6926. name: "titanArenaStartRaid",
  6927. args: {
  6928. titans: titan_arena
  6929. },
  6930. ident: "body"
  6931. }];
  6932. send(JSON.stringify({calls}), calcResults);
  6933. }
  6934.  
  6935. function calcResults(data) {
  6936. let battlesInfo = data.results[0].result.response;
  6937. let {attackers, rivals} = battlesInfo;
  6938.  
  6939. let promises = [];
  6940. for (let n in rivals) {
  6941. rival = rivals[n];
  6942. promises.push(calcBattleResult({
  6943. attackers: attackers,
  6944. defenders: [rival.team],
  6945. seed: rival.seed,
  6946. typeId: n,
  6947. }));
  6948. }
  6949.  
  6950. Promise.all(promises)
  6951. .then(results => {
  6952. const endResults = {};
  6953. for (let info of results) {
  6954. let id = info.battleData.typeId;
  6955. endResults[id] = {
  6956. progress: info.progress,
  6957. result: info.result,
  6958. }
  6959. }
  6960. titanArenaEndRaid(endResults);
  6961. });
  6962. }
  6963.  
  6964. function calcBattleResult(battleData) {
  6965. return new Promise(function (resolve, reject) {
  6966. BattleCalc(battleData, "get_titanClanPvp", resolve);
  6967. });
  6968. }
  6969.  
  6970. /**
  6971. * Sending Raid Results
  6972. *
  6973. * Отправка результатов рейда
  6974. */
  6975. function titanArenaEndRaid(results) {
  6976. titanArenaEndRaidCall = {
  6977. calls: [{
  6978. name: "titanArenaEndRaid",
  6979. args: {
  6980. results
  6981. },
  6982. ident: "body"
  6983. }]
  6984. }
  6985. send(JSON.stringify(titanArenaEndRaidCall), checkRaidResults);
  6986. }
  6987.  
  6988. function checkRaidResults(data) {
  6989. results = data.results[0].result.response.results;
  6990. isSucsesRaid = true;
  6991. for (let i in results) {
  6992. isSucsesRaid &&= (results[i].attackScore >= 250);
  6993. }
  6994.  
  6995. if (isSucsesRaid) {
  6996. titanArenaCompleteTier();
  6997. } else {
  6998. titanArenaGetStatus();
  6999. }
  7000. }
  7001.  
  7002. function titanArenaFarmDailyReward() {
  7003. titanArenaFarmDailyRewardCall = {
  7004. calls: [{
  7005. name: "titanArenaFarmDailyReward",
  7006. args: {},
  7007. ident: "body"
  7008. }]
  7009. }
  7010. send(JSON.stringify(titanArenaFarmDailyRewardCall), () => {console.log('Done farm daily reward')});
  7011. }
  7012.  
  7013. function endTitanArena(reason, info) {
  7014. if (!['Peace_time', 'disabled'].includes(reason)) {
  7015. titanArenaFarmDailyReward();
  7016. }
  7017. console.log(reason, info);
  7018. setProgress(`${I18N('TITAN_ARENA')} ${I18N('COMPLETED')}!`, true);
  7019. resolve();
  7020. }
  7021. }
  7022.  
  7023. this.HWHClasses.executeTitanArena = executeTitanArena;
  7024.  
  7025. function hackGame() {
  7026. const self = this;
  7027. selfGame = null;
  7028. bindId = 1e9;
  7029. this.libGame = null;
  7030. this.doneLibLoad = () => {};
  7031.  
  7032. /**
  7033. * List of correspondence of used classes to their names
  7034. *
  7035. * Список соответствия используемых классов их названиям
  7036. */
  7037. ObjectsList = [
  7038. { name: 'BattlePresets', prop: 'game.battle.controller.thread.BattlePresets' },
  7039. { name: 'DataStorage', prop: 'game.data.storage.DataStorage' },
  7040. { name: 'BattleConfigStorage', prop: 'game.data.storage.battle.BattleConfigStorage' },
  7041. { name: 'BattleInstantPlay', prop: 'game.battle.controller.instant.BattleInstantPlay' },
  7042. { name: 'MultiBattleInstantReplay', prop: 'game.battle.controller.instant.MultiBattleInstantReplay' },
  7043. { name: 'MultiBattleResult', prop: 'game.battle.controller.MultiBattleResult' },
  7044.  
  7045. { name: 'PlayerMissionData', prop: 'game.model.user.mission.PlayerMissionData' },
  7046. { name: 'PlayerMissionBattle', prop: 'game.model.user.mission.PlayerMissionBattle' },
  7047. { name: 'GameModel', prop: 'game.model.GameModel' },
  7048. { name: 'CommandManager', prop: 'game.command.CommandManager' },
  7049. { name: 'MissionCommandList', prop: 'game.command.rpc.mission.MissionCommandList' },
  7050. { name: 'RPCCommandBase', prop: 'game.command.rpc.RPCCommandBase' },
  7051. { name: 'PlayerTowerData', prop: 'game.model.user.tower.PlayerTowerData' },
  7052. { name: 'TowerCommandList', prop: 'game.command.tower.TowerCommandList' },
  7053. { name: 'PlayerHeroTeamResolver', prop: 'game.model.user.hero.PlayerHeroTeamResolver' },
  7054. { name: 'BattlePausePopup', prop: 'game.view.popup.battle.BattlePausePopup' },
  7055. { name: 'BattlePopup', prop: 'game.view.popup.battle.BattlePopup' },
  7056. { name: 'DisplayObjectContainer', prop: 'starling.display.DisplayObjectContainer' },
  7057. { name: 'GuiClipContainer', prop: 'engine.core.clipgui.GuiClipContainer' },
  7058. { name: 'BattlePausePopupClip', prop: 'game.view.popup.battle.BattlePausePopupClip' },
  7059. { name: 'ClipLabel', prop: 'game.view.gui.components.ClipLabel' },
  7060. { name: 'ClipLabelBase', prop: 'game.view.gui.components.ClipLabelBase' },
  7061. { name: 'Translate', prop: 'com.progrestar.common.lang.Translate' },
  7062. { name: 'ClipButtonLabeledCentered', prop: 'game.view.gui.components.ClipButtonLabeledCentered' },
  7063. { name: 'BattlePausePopupMediator', prop: 'game.mediator.gui.popup.battle.BattlePausePopupMediator' },
  7064. { name: 'SettingToggleButton', prop: 'game.mechanics.settings.popup.view.SettingToggleButton' },
  7065. { name: 'PlayerDungeonData', prop: 'game.mechanics.dungeon.model.PlayerDungeonData' },
  7066. { name: 'NextDayUpdatedManager', prop: 'game.model.user.NextDayUpdatedManager' },
  7067. { name: 'BattleController', prop: 'game.battle.controller.BattleController' },
  7068. { name: 'BattleSettingsModel', prop: 'game.battle.controller.BattleSettingsModel' },
  7069. { name: 'BooleanProperty', prop: 'engine.core.utils.property.BooleanProperty' },
  7070. { name: 'RuleStorage', prop: 'game.data.storage.rule.RuleStorage' },
  7071. { name: 'BattleConfig', prop: 'battle.BattleConfig' },
  7072. { name: 'BattleGuiMediator', prop: 'game.battle.gui.BattleGuiMediator' },
  7073. { name: 'BooleanPropertyWriteable', prop: 'engine.core.utils.property.BooleanPropertyWriteable' },
  7074. { name: 'BattleLogEncoder', prop: 'battle.log.BattleLogEncoder' },
  7075. { name: 'BattleLogReader', prop: 'battle.log.BattleLogReader' },
  7076. { name: 'PlayerSubscriptionInfoValueObject', prop: 'game.model.user.subscription.PlayerSubscriptionInfoValueObject' },
  7077. { name: 'AdventureMapCamera', prop: 'game.mechanics.adventure.popup.map.AdventureMapCamera' },
  7078. ];
  7079.  
  7080. /**
  7081. * Contains the game classes needed to write and override game methods
  7082. *
  7083. * Содержит классы игры необходимые для написания и подмены методов игры
  7084. */
  7085. Game = {
  7086. /**
  7087. * Function 'e'
  7088. * Функция 'e'
  7089. */
  7090. bindFunc: function (a, b) {
  7091. if (null == b) return null;
  7092. null == b.__id__ && (b.__id__ = bindId++);
  7093. var c;
  7094. null == a.hx__closures__ ? (a.hx__closures__ = {}) : (c = a.hx__closures__[b.__id__]);
  7095. null == c && ((c = b.bind(a)), (a.hx__closures__[b.__id__] = c));
  7096. return c;
  7097. },
  7098. };
  7099.  
  7100. /**
  7101. * Connects to game objects via the object creation event
  7102. *
  7103. * Подключается к объектам игры через событие создания объекта
  7104. */
  7105. function connectGame() {
  7106. for (let obj of ObjectsList) {
  7107. /**
  7108. * https: //stackoverflow.com/questions/42611719/how-to-intercept-and-modify-a-specific-property-for-any-object
  7109. */
  7110. Object.defineProperty(Object.prototype, obj.prop, {
  7111. set: function (value) {
  7112. if (!selfGame) {
  7113. selfGame = this;
  7114. }
  7115. if (!Game[obj.name]) {
  7116. Game[obj.name] = value;
  7117. }
  7118. // console.log('set ' + obj.prop, this, value);
  7119. this[obj.prop + '_'] = value;
  7120. },
  7121. get: function () {
  7122. // console.log('get ' + obj.prop, this);
  7123. return this[obj.prop + '_'];
  7124. },
  7125. });
  7126. }
  7127. }
  7128.  
  7129. /**
  7130. * Game.BattlePresets
  7131. * @param {bool} a isReplay
  7132. * @param {bool} b autoToggleable
  7133. * @param {bool} c auto On Start
  7134. * @param {object} d config
  7135. * @param {bool} f showBothTeams
  7136. */
  7137. /**
  7138. * Returns the results of the battle to the callback function
  7139. * Возвращает в функцию callback результаты боя
  7140. * @param {*} battleData battle data данные боя
  7141. * @param {*} battleConfig combat configuration type options:
  7142. *
  7143. * тип конфигурации боя варианты:
  7144. *
  7145. * "get_invasion", "get_titanPvpManual", "get_titanPvp",
  7146. * "get_titanClanPvp","get_clanPvp","get_titan","get_boss",
  7147. * "get_tower","get_pve","get_pvpManual","get_pvp","get_core"
  7148. *
  7149. * You can specify the xYc function in the game.assets.storage.BattleAssetStorage class
  7150. *
  7151. * Можно уточнить в классе game.assets.storage.BattleAssetStorage функция xYc
  7152. * @param {*} callback функция в которую вернуться результаты боя
  7153. */
  7154. this.BattleCalc = function (battleData, battleConfig, callback) {
  7155. // battleConfig = battleConfig || getBattleType(battleData.type)
  7156. if (!Game.BattlePresets) throw Error('Use connectGame');
  7157. battlePresets = new Game.BattlePresets(
  7158. battleData.progress,
  7159. !1,
  7160. !0,
  7161. Game.DataStorage[getFn(Game.DataStorage, 24)][getF(Game.BattleConfigStorage, battleConfig)](),
  7162. !1
  7163. );
  7164. let battleInstantPlay;
  7165. if (battleData.progress?.length > 1) {
  7166. battleInstantPlay = new Game.MultiBattleInstantReplay(battleData, battlePresets);
  7167. } else {
  7168. battleInstantPlay = new Game.BattleInstantPlay(battleData, battlePresets);
  7169. }
  7170. battleInstantPlay[getProtoFn(Game.BattleInstantPlay, 9)].add((battleInstant) => {
  7171. const MBR_2 = getProtoFn(Game.MultiBattleResult, 2);
  7172. const battleResults = battleInstant[getF(Game.BattleInstantPlay, 'get_result')]();
  7173. const battleData = battleInstant[getF(Game.BattleInstantPlay, 'get_rawBattleInfo')]();
  7174. const battleLogs = [];
  7175. const timeLimit = battlePresets[getF(Game.BattlePresets, 'get_timeLimit')]();
  7176. let battleTime = 0;
  7177. let battleTimer = 0;
  7178. for (const battleResult of battleResults[MBR_2]) {
  7179. const battleLog = Game.BattleLogEncoder.read(new Game.BattleLogReader(battleResult));
  7180. battleLogs.push(battleLog);
  7181. const maxTime = Math.max(...battleLog.map((e) => (e.time < timeLimit && e.time !== 168.8 ? e.time : 0)));
  7182. battleTimer += getTimer(maxTime);
  7183. battleTime += maxTime;
  7184. }
  7185. callback({
  7186. battleLogs,
  7187. battleTime,
  7188. battleTimer,
  7189. battleData,
  7190. progress: battleResults[getF(Game.MultiBattleResult, 'get_progress')](),
  7191. result: battleResults[getF(Game.MultiBattleResult, 'get_result')](),
  7192. });
  7193. });
  7194. battleInstantPlay.start();
  7195. };
  7196.  
  7197. /**
  7198. * Returns a function with the specified name from the class
  7199. *
  7200. * Возвращает из класса функцию с указанным именем
  7201. * @param {Object} classF Class // класс
  7202. * @param {String} nameF function name // имя функции
  7203. * @param {String} pos name and alias order // порядок имени и псевдонима
  7204. * @returns
  7205. */
  7206. function getF(classF, nameF, pos) {
  7207. pos = pos || false;
  7208. let prop = Object.entries(classF.prototype.__properties__);
  7209. if (!pos) {
  7210. return prop.filter((e) => e[1] == nameF).pop()[0];
  7211. } else {
  7212. return prop.filter((e) => e[0] == nameF).pop()[1];
  7213. }
  7214. }
  7215.  
  7216. /**
  7217. * Returns a function with the specified name from the class
  7218. *
  7219. * Возвращает из класса функцию с указанным именем
  7220. * @param {Object} classF Class // класс
  7221. * @param {String} nameF function name // имя функции
  7222. * @returns
  7223. */
  7224. function getFnP(classF, nameF) {
  7225. let prop = Object.entries(classF.__properties__);
  7226. return prop.filter((e) => e[1] == nameF).pop()[0];
  7227. }
  7228.  
  7229. /**
  7230. * Returns the function name with the specified ordinal from the class
  7231. *
  7232. * Возвращает имя функции с указаным порядковым номером из класса
  7233. * @param {Object} classF Class // класс
  7234. * @param {Number} nF Order number of function // порядковый номер функции
  7235. * @returns
  7236. */
  7237. function getFn(classF, nF) {
  7238. let prop = Object.keys(classF);
  7239. return prop[nF];
  7240. }
  7241.  
  7242. /**
  7243. * Returns the name of the function with the specified serial number from the prototype of the class
  7244. *
  7245. * Возвращает имя функции с указаным порядковым номером из прототипа класса
  7246. * @param {Object} classF Class // класс
  7247. * @param {Number} nF Order number of function // порядковый номер функции
  7248. * @returns
  7249. */
  7250. function getProtoFn(classF, nF) {
  7251. let prop = Object.keys(classF.prototype);
  7252. return prop[nF];
  7253. }
  7254.  
  7255. function findInstanceOf(obj, targetClass) {
  7256. const prototypeKeys = Object.keys(Object.getPrototypeOf(obj));
  7257. const matchingKey = prototypeKeys.find((key) => obj[key] instanceof targetClass);
  7258. return matchingKey ? obj[matchingKey] : null;
  7259. }
  7260. /**
  7261. * Description of replaced functions
  7262. *
  7263. * Описание подменяемых функций
  7264. */
  7265. replaceFunction = {
  7266. company: function () {
  7267. let PMD_12 = getProtoFn(Game.PlayerMissionData, 12);
  7268. let oldSkipMisson = Game.PlayerMissionData.prototype[PMD_12];
  7269. Game.PlayerMissionData.prototype[PMD_12] = function (a, b, c) {
  7270. if (!isChecked('passBattle')) {
  7271. oldSkipMisson.call(this, a, b, c);
  7272. return;
  7273. }
  7274.  
  7275. try {
  7276. this[getProtoFn(Game.PlayerMissionData, 9)] = new Game.PlayerMissionBattle(a, b, c);
  7277.  
  7278. var a = new Game.BattlePresets(
  7279. !1,
  7280. !1,
  7281. !0,
  7282. Game.DataStorage[getFn(Game.DataStorage, 24)][getProtoFn(Game.BattleConfigStorage, 20)](),
  7283. !1
  7284. );
  7285. a = new Game.BattleInstantPlay(c, a);
  7286. a[getProtoFn(Game.BattleInstantPlay, 9)].add(Game.bindFunc(this, this.P$h));
  7287. a.start();
  7288. } catch (error) {
  7289. console.error('company', error);
  7290. oldSkipMisson.call(this, a, b, c);
  7291. }
  7292. };
  7293.  
  7294. Game.PlayerMissionData.prototype.P$h = function (a) {
  7295. let GM_2 = getFn(Game.GameModel, 2);
  7296. let GM_P2 = getProtoFn(Game.GameModel, 2);
  7297. let CM_21 = getProtoFn(Game.CommandManager, 21);
  7298. let MCL_2 = getProtoFn(Game.MissionCommandList, 2);
  7299. let MBR_15 = getF(Game.MultiBattleResult, 'get_result');
  7300. let RPCCB_17 = getProtoFn(Game.RPCCommandBase, 17);
  7301. let PMD_34 = getProtoFn(Game.PlayerMissionData, 34);
  7302. Game.GameModel[GM_2]()[GM_P2][CM_21][MCL_2](a[MBR_15]())[RPCCB_17](Game.bindFunc(this, this[PMD_34]));
  7303. };
  7304. },
  7305. /*
  7306. tower: function () {
  7307. let PTD_67 = getProtoFn(Game.PlayerTowerData, 67);
  7308. let oldSkipTower = Game.PlayerTowerData.prototype[PTD_67];
  7309. Game.PlayerTowerData.prototype[PTD_67] = function (a) {
  7310. if (!isChecked('passBattle')) {
  7311. oldSkipTower.call(this, a);
  7312. return;
  7313. }
  7314. try {
  7315. var p = new Game.BattlePresets(
  7316. !1,
  7317. !1,
  7318. !0,
  7319. Game.DataStorage[getFn(Game.DataStorage, 24)][getProtoFn(Game.BattleConfigStorage, 20)](),
  7320. !1
  7321. );
  7322. a = new Game.BattleInstantPlay(a, p);
  7323. a[getProtoFn(Game.BattleInstantPlay, 9)].add(Game.bindFunc(this, this.P$h));
  7324. a.start();
  7325. } catch (error) {
  7326. console.error('tower', error);
  7327. oldSkipMisson.call(this, a, b, c);
  7328. }
  7329. };
  7330.  
  7331. Game.PlayerTowerData.prototype.P$h = function (a) {
  7332. const GM_2 = getFnP(Game.GameModel, 'get_instance');
  7333. const GM_P2 = getProtoFn(Game.GameModel, 2);
  7334. const CM_29 = getProtoFn(Game.CommandManager, 29);
  7335. const TCL_5 = getProtoFn(Game.TowerCommandList, 5);
  7336. const MBR_15 = getF(Game.MultiBattleResult, 'get_result');
  7337. const RPCCB_15 = getProtoFn(Game.RPCCommandBase, 17);
  7338. const PTD_78 = getProtoFn(Game.PlayerTowerData, 78);
  7339. Game.GameModel[GM_2]()[GM_P2][CM_29][TCL_5](a[MBR_15]())[RPCCB_15](Game.bindFunc(this, this[PTD_78]));
  7340. };
  7341. },
  7342. */
  7343. // skipSelectHero: function() {
  7344. // if (!HOST) throw Error('Use connectGame');
  7345. // Game.PlayerHeroTeamResolver.prototype[getProtoFn(Game.PlayerHeroTeamResolver, 3)] = () => false;
  7346. // },
  7347. passBattle: function () {
  7348. let BPP_4 = getProtoFn(Game.BattlePausePopup, 4);
  7349. let oldPassBattle = Game.BattlePausePopup.prototype[BPP_4];
  7350. Game.BattlePausePopup.prototype[BPP_4] = function (a) {
  7351. if (!isChecked('passBattle')) {
  7352. oldPassBattle.call(this, a);
  7353. return;
  7354. }
  7355. try {
  7356. Game.BattlePopup.prototype[getProtoFn(Game.BattlePausePopup, 4)].call(this, a);
  7357. this[getProtoFn(Game.BattlePausePopup, 3)]();
  7358. this[getProtoFn(Game.DisplayObjectContainer, 3)](this.clip[getProtoFn(Game.GuiClipContainer, 2)]());
  7359. this.clip[getProtoFn(Game.BattlePausePopupClip, 1)][getProtoFn(Game.ClipLabelBase, 9)](
  7360. Game.Translate.translate('UI_POPUP_BATTLE_PAUSE')
  7361. );
  7362.  
  7363. this.clip[getProtoFn(Game.BattlePausePopupClip, 2)][getProtoFn(Game.ClipButtonLabeledCentered, 2)](
  7364. Game.Translate.translate('UI_POPUP_BATTLE_RETREAT'),
  7365. ((q = this[getProtoFn(Game.BattlePausePopup, 1)]), Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 17)]))
  7366. );
  7367. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 2)](
  7368. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 14)](),
  7369. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 13)]()
  7370. ? ((q = this[getProtoFn(Game.BattlePausePopup, 1)]), Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 18)]))
  7371. : ((q = this[getProtoFn(Game.BattlePausePopup, 1)]), Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 18)]))
  7372. );
  7373.  
  7374. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 0)][
  7375. getProtoFn(Game.ClipLabelBase, 24)
  7376. ]();
  7377. this.clip[getProtoFn(Game.BattlePausePopupClip, 3)][getProtoFn(Game.SettingToggleButton, 3)](
  7378. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 9)]()
  7379. );
  7380. this.clip[getProtoFn(Game.BattlePausePopupClip, 4)][getProtoFn(Game.SettingToggleButton, 3)](
  7381. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 10)]()
  7382. );
  7383. this.clip[getProtoFn(Game.BattlePausePopupClip, 6)][getProtoFn(Game.SettingToggleButton, 3)](
  7384. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 11)]()
  7385. );
  7386. } catch (error) {
  7387. console.error('passBattle', error);
  7388. oldPassBattle.call(this, a);
  7389. }
  7390. };
  7391.  
  7392. let retreatButtonLabel = getF(Game.BattlePausePopupMediator, 'get_retreatButtonLabel');
  7393. let oldFunc = Game.BattlePausePopupMediator.prototype[retreatButtonLabel];
  7394. Game.BattlePausePopupMediator.prototype[retreatButtonLabel] = function () {
  7395. if (isChecked('passBattle')) {
  7396. return I18N('BTN_PASS');
  7397. } else {
  7398. return oldFunc.call(this);
  7399. }
  7400. };
  7401. },
  7402. endlessCards: function () {
  7403. let PDD_21 = getProtoFn(Game.PlayerDungeonData, 21);
  7404. let oldEndlessCards = Game.PlayerDungeonData.prototype[PDD_21];
  7405. Game.PlayerDungeonData.prototype[PDD_21] = function () {
  7406. if (countPredictionCard <= 0) {
  7407. return true;
  7408. } else {
  7409. return oldEndlessCards.call(this);
  7410. }
  7411. };
  7412. },
  7413. speedBattle: function () {
  7414. const get_timeScale = getF(Game.BattleController, 'get_timeScale');
  7415. const oldSpeedBattle = Game.BattleController.prototype[get_timeScale];
  7416. Game.BattleController.prototype[get_timeScale] = function () {
  7417. const speedBattle = Number.parseFloat(getInput('speedBattle'));
  7418. if (!speedBattle) {
  7419. return oldSpeedBattle.call(this);
  7420. }
  7421. try {
  7422. const BC_12 = getProtoFn(Game.BattleController, 12);
  7423. const BSM_12 = getProtoFn(Game.BattleSettingsModel, 12);
  7424. const BP_get_value = getF(Game.BooleanProperty, 'get_value');
  7425. if (this[BC_12][BSM_12][BP_get_value]()) {
  7426. return 0;
  7427. }
  7428. const BSM_2 = getProtoFn(Game.BattleSettingsModel, 2);
  7429. const BC_49 = getProtoFn(Game.BattleController, 49);
  7430. const BSM_1 = getProtoFn(Game.BattleSettingsModel, 1);
  7431. const BC_14 = getProtoFn(Game.BattleController, 14);
  7432. const BC_3 = getFn(Game.BattleController, 3);
  7433. if (this[BC_12][BSM_2][BP_get_value]()) {
  7434. var a = speedBattle * this[BC_49]();
  7435. } else {
  7436. a = this[BC_12][BSM_1][BP_get_value]();
  7437. const maxSpeed = Math.max(...this[BC_14]);
  7438. const multiple = a == this[BC_14].indexOf(maxSpeed) ? (maxSpeed >= 4 ? speedBattle : this[BC_14][a]) : this[BC_14][a];
  7439. a = multiple * Game.BattleController[BC_3][BP_get_value]() * this[BC_49]();
  7440. }
  7441. const BSM_24 = getProtoFn(Game.BattleSettingsModel, 24);
  7442. a > this[BC_12][BSM_24][BP_get_value]() && (a = this[BC_12][BSM_24][BP_get_value]());
  7443. const DS_23 = getFn(Game.DataStorage, 23);
  7444. const get_battleSpeedMultiplier = getF(Game.RuleStorage, 'get_battleSpeedMultiplier', true);
  7445. var b = Game.DataStorage[DS_23][get_battleSpeedMultiplier]();
  7446. const R_1 = getFn(selfGame.Reflect, 1);
  7447. const BC_1 = getFn(Game.BattleController, 1);
  7448. const get_config = getF(Game.BattlePresets, 'get_config');
  7449. null != b &&
  7450. (a = selfGame.Reflect[R_1](b, this[BC_1][get_config]().ident)
  7451. ? a * selfGame.Reflect[R_1](b, this[BC_1][get_config]().ident)
  7452. : a * selfGame.Reflect[R_1](b, 'default'));
  7453. return a;
  7454. } catch (error) {
  7455. console.error('passBatspeedBattletle', error);
  7456. return oldSpeedBattle.call(this);
  7457. }
  7458. };
  7459. },
  7460.  
  7461. /**
  7462. * Acceleration button without Valkyries favor
  7463. *
  7464. * Кнопка ускорения без Покровительства Валькирий
  7465. */
  7466. battleFastKey: function () {
  7467. const BGM_44 = getProtoFn(Game.BattleGuiMediator, 44);
  7468. const oldBattleFastKey = Game.BattleGuiMediator.prototype[BGM_44];
  7469. Game.BattleGuiMediator.prototype[BGM_44] = function () {
  7470. let flag = true;
  7471. //console.log(flag)
  7472. if (!flag) {
  7473. return oldBattleFastKey.call(this);
  7474. }
  7475. try {
  7476. const BGM_9 = getProtoFn(Game.BattleGuiMediator, 9);
  7477. const BGM_10 = getProtoFn(Game.BattleGuiMediator, 10);
  7478. const BPW_0 = getProtoFn(Game.BooleanPropertyWriteable, 0);
  7479. this[BGM_9][BPW_0](true);
  7480. this[BGM_10][BPW_0](true);
  7481. } catch (error) {
  7482. console.error(error);
  7483. return oldBattleFastKey.call(this);
  7484. }
  7485. };
  7486. },
  7487. fastSeason: function () {
  7488. const GameNavigator = selfGame['game.screen.navigator.GameNavigator'];
  7489. const oldFuncName = getProtoFn(GameNavigator, 18);
  7490. const newFuncName = getProtoFn(GameNavigator, 16);
  7491. const oldFastSeason = GameNavigator.prototype[oldFuncName];
  7492. const newFastSeason = GameNavigator.prototype[newFuncName];
  7493. GameNavigator.prototype[oldFuncName] = function (a, b) {
  7494. if (isChecked('fastSeason')) {
  7495. return newFastSeason.apply(this, [a]);
  7496. } else {
  7497. return oldFastSeason.apply(this, [a, b]);
  7498. }
  7499. };
  7500. },
  7501. ShowChestReward: function () {
  7502. const TitanArtifactChest = selfGame['game.mechanics.titan_arena.mediator.chest.TitanArtifactChestRewardPopupMediator'];
  7503. const getOpenAmountTitan = getF(TitanArtifactChest, 'get_openAmount');
  7504. const oldGetOpenAmountTitan = TitanArtifactChest.prototype[getOpenAmountTitan];
  7505. TitanArtifactChest.prototype[getOpenAmountTitan] = function () {
  7506. if (correctShowOpenArtifact) {
  7507. correctShowOpenArtifact--;
  7508. return 100;
  7509. }
  7510. return oldGetOpenAmountTitan.call(this);
  7511. };
  7512.  
  7513. const ArtifactChest = selfGame['game.view.popup.artifactchest.rewardpopup.ArtifactChestRewardPopupMediator'];
  7514. const getOpenAmount = getF(ArtifactChest, 'get_openAmount');
  7515. const oldGetOpenAmount = ArtifactChest.prototype[getOpenAmount];
  7516. ArtifactChest.prototype[getOpenAmount] = function () {
  7517. if (correctShowOpenArtifact) {
  7518. correctShowOpenArtifact--;
  7519. return 100;
  7520. }
  7521. return oldGetOpenAmount.call(this);
  7522. };
  7523. },
  7524. fixCompany: function () {
  7525. const GameBattleView = selfGame['game.mediator.gui.popup.battle.GameBattleView'];
  7526. const BattleThread = selfGame['game.battle.controller.thread.BattleThread'];
  7527. const getOnViewDisposed = getF(BattleThread, 'get_onViewDisposed');
  7528. const getThread = getF(GameBattleView, 'get_thread');
  7529. const oldFunc = GameBattleView.prototype[getThread];
  7530. GameBattleView.prototype[getThread] = function () {
  7531. return (
  7532. oldFunc.call(this) || {
  7533. [getOnViewDisposed]: async () => {},
  7534. }
  7535. );
  7536. };
  7537. },
  7538. BuyTitanArtifact: function () {
  7539. const BIP_4 = getProtoFn(selfGame['game.view.popup.shop.buy.BuyItemPopup'], 4);
  7540. const BuyItemPopup = selfGame['game.view.popup.shop.buy.BuyItemPopup'];
  7541. const oldFunc = BuyItemPopup.prototype[BIP_4];
  7542. BuyItemPopup.prototype[BIP_4] = function () {
  7543. if (isChecked('countControl')) {
  7544. const BuyTitanArtifactItemPopup = selfGame['game.view.popup.shop.buy.BuyTitanArtifactItemPopup'];
  7545. const BTAP_0 = getProtoFn(BuyTitanArtifactItemPopup, 0);
  7546. if (this[BTAP_0]) {
  7547. const BuyTitanArtifactPopupMediator = selfGame['game.mediator.gui.popup.shop.buy.BuyTitanArtifactItemPopupMediator'];
  7548. const BTAM_1 = getProtoFn(BuyTitanArtifactPopupMediator, 1);
  7549. const BuyItemPopupMediator = selfGame['game.mediator.gui.popup.shop.buy.BuyItemPopupMediator'];
  7550. const BIPM_5 = getProtoFn(BuyItemPopupMediator, 5);
  7551. const BIPM_7 = getProtoFn(BuyItemPopupMediator, 7);
  7552. const BIPM_9 = getProtoFn(BuyItemPopupMediator, 9);
  7553.  
  7554. let need = Math.min(this[BTAP_0][BTAM_1](), this[BTAP_0][BIPM_7]);
  7555. need = need ? need : 60;
  7556. this[BTAP_0][BIPM_9] = need;
  7557. this[BTAP_0][BIPM_5] = 10;
  7558. }
  7559. }
  7560. oldFunc.call(this);
  7561. };
  7562. },
  7563. ClanQuestsFastFarm: function () {
  7564. const VipRuleValueObject = selfGame['game.data.storage.rule.VipRuleValueObject'];
  7565. const getClanQuestsFastFarm = getF(VipRuleValueObject, 'get_clanQuestsFastFarm', 1);
  7566. VipRuleValueObject.prototype[getClanQuestsFastFarm] = function () {
  7567. return 0;
  7568. };
  7569. },
  7570. adventureCamera: function () {
  7571. const AMC_40 = getProtoFn(Game.AdventureMapCamera, 40);
  7572. const AMC_5 = getProtoFn(Game.AdventureMapCamera, 5);
  7573. const oldFunc = Game.AdventureMapCamera.prototype[AMC_40];
  7574. Game.AdventureMapCamera.prototype[AMC_40] = function (a) {
  7575. this[AMC_5] = 0.4;
  7576. oldFunc.bind(this)(a);
  7577. };
  7578. },
  7579. unlockMission: function () {
  7580. const WorldMapStoryDrommerHelper = selfGame['game.mediator.gui.worldmap.WorldMapStoryDrommerHelper'];
  7581. const WMSDH_4 = getFn(WorldMapStoryDrommerHelper, 4);
  7582. const WMSDH_7 = getFn(WorldMapStoryDrommerHelper, 7);
  7583. WorldMapStoryDrommerHelper[WMSDH_4] = function () {
  7584. return true;
  7585. };
  7586. WorldMapStoryDrommerHelper[WMSDH_7] = function () {
  7587. return true;
  7588. };
  7589. },
  7590. };
  7591.  
  7592. /**
  7593. * Starts replacing recorded functions
  7594. *
  7595. * Запускает замену записанных функций
  7596. */
  7597. this.activateHacks = function () {
  7598. if (!selfGame) throw Error('Use connectGame');
  7599. for (let func in replaceFunction) {
  7600. try {
  7601. replaceFunction[func]();
  7602. } catch (error) {
  7603. console.error(error);
  7604. }
  7605. }
  7606. };
  7607.  
  7608. /**
  7609. * Returns the game object
  7610. *
  7611. * Возвращает объект игры
  7612. */
  7613. this.getSelfGame = function () {
  7614. return selfGame;
  7615. };
  7616.  
  7617. /**
  7618. * Updates game data
  7619. *
  7620. * Обновляет данные игры
  7621. */
  7622. this.refreshGame = function () {
  7623. new Game.NextDayUpdatedManager()[getProtoFn(Game.NextDayUpdatedManager, 5)]();
  7624. try {
  7625. cheats.refreshInventory();
  7626. } catch (e) {}
  7627. };
  7628.  
  7629. /**
  7630. * Update inventory
  7631. *
  7632. * Обновляет инвентарь
  7633. */
  7634. this.refreshInventory = async function () {
  7635. const GM_INST = getFnP(Game.GameModel, 'get_instance');
  7636. const GM_0 = getProtoFn(Game.GameModel, 0);
  7637. const P_24 = getProtoFn(selfGame['game.model.user.Player'], 24);
  7638. const Player = Game.GameModel[GM_INST]()[GM_0];
  7639. Player[P_24] = new selfGame['game.model.user.inventory.PlayerInventory']();
  7640. Player[P_24].init(await Send({ calls: [{ name: 'inventoryGet', args: {}, ident: 'body' }] }).then((e) => e.results[0].result.response));
  7641. };
  7642. this.updateInventory = function (reward) {
  7643. const GM_INST = getFnP(Game.GameModel, 'get_instance');
  7644. const GM_0 = getProtoFn(Game.GameModel, 0);
  7645. const P_24 = getProtoFn(selfGame['game.model.user.Player'], 24);
  7646. const Player = Game.GameModel[GM_INST]()[GM_0];
  7647. Player[P_24].init(reward);
  7648. };
  7649.  
  7650. this.updateMap = function (data) {
  7651. const PCDD_21 = getProtoFn(selfGame['game.mechanics.clanDomination.model.PlayerClanDominationData'], 21);
  7652. const P_60 = getProtoFn(selfGame['game.model.user.Player'], 60);
  7653. const GM_0 = getProtoFn(Game.GameModel, 0);
  7654. const getInstance = getFnP(selfGame['Game'], 'get_instance');
  7655. const PlayerClanDominationData = Game.GameModel[getInstance]()[GM_0];
  7656. PlayerClanDominationData[P_60][PCDD_21].update(data);
  7657. };
  7658.  
  7659. /**
  7660. * Change the play screen on windowName
  7661. *
  7662. * Сменить экран игры на windowName
  7663. *
  7664. * Possible options:
  7665. *
  7666. * Возможные варианты:
  7667. *
  7668. * 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
  7669. */
  7670. this.goNavigtor = function (windowName) {
  7671. let mechanicStorage = selfGame['game.data.storage.mechanic.MechanicStorage'];
  7672. let window = mechanicStorage[windowName];
  7673. let event = new selfGame['game.mediator.gui.popup.PopupStashEventParams']();
  7674. let Game = selfGame['Game'];
  7675. let navigator = getF(Game, 'get_navigator');
  7676. let navigate = getProtoFn(selfGame['game.screen.navigator.GameNavigator'], 20);
  7677. let instance = getFnP(Game, 'get_instance');
  7678. Game[instance]()[navigator]()[navigate](window, event);
  7679. };
  7680.  
  7681. /**
  7682. * Move to the sanctuary cheats.goSanctuary()
  7683. *
  7684. * Переместиться в святилище cheats.goSanctuary()
  7685. */
  7686. this.goSanctuary = () => {
  7687. this.goNavigtor('SANCTUARY');
  7688. };
  7689.  
  7690. /** Перейти в Долину титанов */
  7691. this.goTitanValley = () => {
  7692. this.goNavigtor('TITAN_VALLEY');
  7693. };
  7694.  
  7695. /**
  7696. * Go to Guild War
  7697. *
  7698. * Перейти к Войне Гильдий
  7699. */
  7700. this.goClanWar = function () {
  7701. let instance = getFnP(Game.GameModel, 'get_instance');
  7702. let player = Game.GameModel[instance]().A;
  7703. let clanWarSelect = selfGame['game.mechanics.cross_clan_war.popup.selectMode.CrossClanWarSelectModeMediator'];
  7704. new clanWarSelect(player).open();
  7705. };
  7706.  
  7707. /** Перейти к Острову гильдии */
  7708. this.goClanIsland = function () {
  7709. let instance = getFnP(Game.GameModel, 'get_instance');
  7710. let player = Game.GameModel[instance]().A;
  7711. let clanIslandSelect = selfGame['game.view.gui.ClanIslandPopupMediator'];
  7712. new clanIslandSelect(player).open();
  7713. };
  7714.  
  7715. /**
  7716. * Go to BrawlShop
  7717. *
  7718. * Переместиться в BrawlShop
  7719. */
  7720. this.goBrawlShop = () => {
  7721. const instance = getFnP(Game.GameModel, 'get_instance');
  7722. const P_36 = getProtoFn(selfGame['game.model.user.Player'], 36);
  7723. const PSD_0 = getProtoFn(selfGame['game.model.user.shop.PlayerShopData'], 0);
  7724. const IM_0 = getProtoFn(selfGame['haxe.ds.IntMap'], 0);
  7725. const PSDE_4 = getProtoFn(selfGame['game.model.user.shop.PlayerShopDataEntry'], 4);
  7726.  
  7727. const player = Game.GameModel[instance]().A;
  7728. const shop = player[P_36][PSD_0][IM_0][1038][PSDE_4];
  7729. const shopPopup = new selfGame['game.mechanics.brawl.mediator.BrawlShopPopupMediator'](player, shop);
  7730. shopPopup.open(new selfGame['game.mediator.gui.popup.PopupStashEventParams']());
  7731. };
  7732.  
  7733. /**
  7734. * Returns all stores from game data
  7735. *
  7736. * Возвращает все магазины из данных игры
  7737. */
  7738. this.getShops = () => {
  7739. const instance = getFnP(Game.GameModel, 'get_instance');
  7740. const P_36 = getProtoFn(selfGame['game.model.user.Player'], 36);
  7741. const PSD_0 = getProtoFn(selfGame['game.model.user.shop.PlayerShopData'], 0);
  7742. const IM_0 = getProtoFn(selfGame['haxe.ds.IntMap'], 0);
  7743.  
  7744. const player = Game.GameModel[instance]().A;
  7745. return player[P_36][PSD_0][IM_0];
  7746. };
  7747.  
  7748. /**
  7749. * Returns the store from the game data by ID
  7750. *
  7751. * Возвращает магазин из данных игры по идетификатору
  7752. */
  7753. this.getShop = (id) => {
  7754. const PSDE_4 = getProtoFn(selfGame['game.model.user.shop.PlayerShopDataEntry'], 4);
  7755. const shops = this.getShops();
  7756. const shop = shops[id]?.[PSDE_4];
  7757. return shop;
  7758. };
  7759.  
  7760. /**
  7761. * Change island map
  7762. *
  7763. * Сменить карту острова
  7764. */
  7765. this.changeIslandMap = (mapId = 2) => {
  7766. const GameInst = getFnP(selfGame['Game'], 'get_instance');
  7767. const GM_0 = getProtoFn(Game.GameModel, 0);
  7768. const PSAD_31 = getProtoFn(selfGame['game.mechanics.season_adventure.model.PlayerSeasonAdventureData'], 31);
  7769. const Player = Game.GameModel[GameInst]()[GM_0];
  7770. const PlayerSeasonAdventureData = findInstanceOf(Player, selfGame['game.mechanics.season_adventure.model.PlayerSeasonAdventureData']);
  7771. PlayerSeasonAdventureData[PSAD_31]({ id: mapId, seasonAdventure: { id: mapId, startDate: 1701914400, endDate: 1709690400, closed: false } });
  7772.  
  7773. const GN_15 = getProtoFn(selfGame['game.screen.navigator.GameNavigator'], 17);
  7774. const navigator = getF(selfGame['Game'], 'get_navigator');
  7775. selfGame['Game'][GameInst]()[navigator]()[GN_15](new selfGame['game.mediator.gui.popup.PopupStashEventParams']());
  7776. };
  7777.  
  7778. /**
  7779. * Game library availability tracker
  7780. *
  7781. * Отслеживание доступности игровой библиотеки
  7782. */
  7783. function checkLibLoad() {
  7784. timeout = setTimeout(() => {
  7785. if (Game.GameModel) {
  7786. changeLib();
  7787. } else {
  7788. checkLibLoad();
  7789. }
  7790. }, 100);
  7791. }
  7792.  
  7793. /**
  7794. * Game library data spoofing
  7795. *
  7796. * Подмена данных игровой библиотеки
  7797. */
  7798. function changeLib() {
  7799. console.log('lib connect');
  7800. const originalStartFunc = Game.GameModel.prototype.start;
  7801. Game.GameModel.prototype.start = function (a, b, c) {
  7802. self.libGame = b.raw;
  7803. self.doneLibLoad(self.libGame);
  7804. try {
  7805. const levels = b.raw.seasonAdventure.level;
  7806. for (const id in levels) {
  7807. const level = levels[id];
  7808. level.clientData.graphics.fogged = level.clientData.graphics.visible;
  7809. }
  7810. const adv = b.raw.seasonAdventure.list[1];
  7811. adv.clientData.asset = 'dialog_season_adventure_tiles';
  7812. } catch (e) {
  7813. console.warn(e);
  7814. }
  7815. originalStartFunc.call(this, a, b, c);
  7816. };
  7817. }
  7818.  
  7819. this.LibLoad = function () {
  7820. return new Promise((e) => {
  7821. this.doneLibLoad = e;
  7822. });
  7823. };
  7824.  
  7825. /**
  7826. * Returns the value of a language constant
  7827. *
  7828. * Возвращает значение языковой константы
  7829. * @param {*} langConst language constant // языковая константа
  7830. * @returns
  7831. */
  7832. this.translate = function (langConst) {
  7833. return Game.Translate.translate(langConst);
  7834. };
  7835.  
  7836. connectGame();
  7837. checkLibLoad();
  7838. }
  7839.  
  7840. /**
  7841. * Auto collection of gifts
  7842. *
  7843. * Автосбор подарков
  7844. */
  7845. function getAutoGifts() {
  7846. // c3ltYm9scyB0aGF0IG1lYW4gbm90aGluZw==
  7847. let valName = 'giftSendIds_' + userInfo.id;
  7848.  
  7849. if (!localStorage['clearGift' + userInfo.id]) {
  7850. localStorage[valName] = '';
  7851. localStorage['clearGift' + userInfo.id] = '+';
  7852. }
  7853.  
  7854. if (!localStorage[valName]) {
  7855. localStorage[valName] = '';
  7856. }
  7857.  
  7858. const giftsAPI = new ZingerYWebsiteAPI('getGifts.php', arguments);
  7859. /**
  7860. * Submit a request to receive gift codes
  7861. *
  7862. * Отправка запроса для получения кодов подарков
  7863. */
  7864. giftsAPI.request().then((data) => {
  7865. let freebieCheckCalls = {
  7866. calls: [],
  7867. };
  7868. data.forEach((giftId, n) => {
  7869. if (localStorage[valName].includes(giftId)) return;
  7870. freebieCheckCalls.calls.push({
  7871. name: 'registration',
  7872. args: {
  7873. user: { referrer: {} },
  7874. giftId,
  7875. },
  7876. context: {
  7877. actionTs: Math.floor(performance.now()),
  7878. cookie: window?.NXAppInfo?.session_id || null,
  7879. },
  7880. ident: giftId,
  7881. });
  7882. });
  7883.  
  7884. if (!freebieCheckCalls.calls.length) {
  7885. return;
  7886. }
  7887.  
  7888. send(JSON.stringify(freebieCheckCalls), (e) => {
  7889. let countGetGifts = 0;
  7890. const gifts = [];
  7891. for (check of e.results) {
  7892. gifts.push(check.ident);
  7893. if (check.result.response != null) {
  7894. countGetGifts++;
  7895. }
  7896. }
  7897. const saveGifts = localStorage[valName].split(';');
  7898. localStorage[valName] = [...saveGifts, ...gifts].slice(-50).join(';');
  7899. console.log(`${I18N('GIFTS')}: ${countGetGifts}`);
  7900. });
  7901. });
  7902. }
  7903.  
  7904. /**
  7905. * To fill the kills in the Forge of Souls
  7906. *
  7907. * Набить килов в горниле душ
  7908. */
  7909. async function bossRatingEvent() {
  7910. const topGet = await Send(JSON.stringify({ calls: [{ name: "topGet", args: { type: "bossRatingTop", extraId: 0 }, ident: "body" }] }));
  7911. if (!topGet || !topGet.results[0].result.response[0]) {
  7912. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  7913. return;
  7914. }
  7915. const replayId = topGet.results[0].result.response[0].userData.replayId;
  7916. const result = await Send(JSON.stringify({
  7917. calls: [
  7918. { name: "battleGetReplay", args: { id: replayId }, ident: "battleGetReplay" },
  7919. { name: "heroGetAll", args: {}, ident: "heroGetAll" },
  7920. { name: "pet_getAll", args: {}, ident: "pet_getAll" },
  7921. { name: "offerGetAll", args: {}, ident: "offerGetAll" }
  7922. ]
  7923. }));
  7924. const bossEventInfo = result.results[3].result.response.find(e => e.offerType == "bossEvent");
  7925. if (!bossEventInfo) {
  7926. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  7927. return;
  7928. }
  7929. const usedHeroes = bossEventInfo.progress.usedHeroes;
  7930. const party = Object.values(result.results[0].result.response.replay.attackers);
  7931. const availableHeroes = Object.values(result.results[1].result.response).map(e => e.id);
  7932. const availablePets = Object.values(result.results[2].result.response).map(e => e.id);
  7933. const calls = [];
  7934. /**
  7935. * First pack
  7936. *
  7937. * Первая пачка
  7938. */
  7939. const args = {
  7940. heroes: [],
  7941. favor: {}
  7942. }
  7943. for (let hero of party) {
  7944. if (hero.id >= 6000 && availablePets.includes(hero.id)) {
  7945. args.pet = hero.id;
  7946. continue;
  7947. }
  7948. if (!availableHeroes.includes(hero.id) || usedHeroes.includes(hero.id)) {
  7949. continue;
  7950. }
  7951. args.heroes.push(hero.id);
  7952. if (hero.favorPetId) {
  7953. args.favor[hero.id] = hero.favorPetId;
  7954. }
  7955. }
  7956. if (args.heroes.length) {
  7957. calls.push({
  7958. name: 'bossRating_startBattle',
  7959. args,
  7960. ident: 'body_0',
  7961. });
  7962. }
  7963. /**
  7964. * Other packs
  7965. *
  7966. * Другие пачки
  7967. */
  7968. let heroes = [];
  7969. let count = 1;
  7970. while (heroId = availableHeroes.pop()) {
  7971. if (args.heroes.includes(heroId) || usedHeroes.includes(heroId)) {
  7972. continue;
  7973. }
  7974. heroes.push(heroId);
  7975. if (heroes.length == 5) {
  7976. calls.push({
  7977. name: 'bossRating_startBattle',
  7978. args: {
  7979. heroes: [...heroes],
  7980. pet: availablePets[Math.floor(Math.random() * availablePets.length)],
  7981. },
  7982. ident: 'body_' + count,
  7983. });
  7984. heroes = [];
  7985. count++;
  7986. }
  7987. }
  7988.  
  7989. if (!calls.length) {
  7990. setProgress(`${I18N('NO_HEROES')}`, true);
  7991. return;
  7992. }
  7993.  
  7994. const resultBattles = await Send(JSON.stringify({ calls }));
  7995. console.log(resultBattles);
  7996. rewardBossRatingEvent();
  7997. }
  7998.  
  7999. /**
  8000. * Collecting Rewards from the Forge of Souls
  8001. *
  8002. * Сбор награды из Горнила Душ
  8003. */
  8004. function rewardBossRatingEvent() {
  8005. let rewardBossRatingCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  8006. send(rewardBossRatingCall, function (data) {
  8007. let bossEventInfo = data.results[0].result.response.find(e => e.offerType == "bossEvent");
  8008. if (!bossEventInfo) {
  8009. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  8010. return;
  8011. }
  8012.  
  8013. let farmedChests = bossEventInfo.progress.farmedChests;
  8014. let score = bossEventInfo.progress.score;
  8015. setProgress(`${I18N('DAMAGE_AMOUNT')}: ${score}`);
  8016. let revard = bossEventInfo.reward;
  8017.  
  8018. let getRewardCall = {
  8019. calls: []
  8020. }
  8021.  
  8022. let count = 0;
  8023. for (let i = 1; i < 10; i++) {
  8024. if (farmedChests.includes(i)) {
  8025. continue;
  8026. }
  8027. if (score < revard[i].score) {
  8028. break;
  8029. }
  8030. getRewardCall.calls.push({
  8031. name: 'bossRating_getReward',
  8032. args: {
  8033. rewardId: i,
  8034. },
  8035. ident: 'body_' + i,
  8036. });
  8037. count++;
  8038. }
  8039. if (!count) {
  8040. setProgress(`${I18N('NOTHING_TO_COLLECT')}`, true);
  8041. return;
  8042. }
  8043.  
  8044. send(JSON.stringify(getRewardCall), e => {
  8045. console.log(e);
  8046. setProgress(`${I18N('COLLECTED')} ${e?.results?.length} ${I18N('REWARD')}`, true);
  8047. });
  8048. });
  8049. }
  8050.  
  8051. /**
  8052. * Collect Easter eggs and event rewards
  8053. *
  8054. * Собрать пасхалки и награды событий
  8055. */
  8056. function offerFarmAllReward() {
  8057. const offerGetAllCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  8058. return Send(offerGetAllCall).then((data) => {
  8059. const offerGetAll = data.results[0].result.response.filter(e => e.type == "reward" && !e?.freeRewardObtained && e.reward);
  8060. if (!offerGetAll.length) {
  8061. setProgress(`${I18N('NOTHING_TO_COLLECT')}`, true);
  8062. return;
  8063. }
  8064.  
  8065. const calls = [];
  8066. for (let reward of offerGetAll) {
  8067. calls.push({
  8068. name: "offerFarmReward",
  8069. args: {
  8070. offerId: reward.id
  8071. },
  8072. ident: "offerFarmReward_" + reward.id
  8073. });
  8074. }
  8075.  
  8076. return Send(JSON.stringify({ calls })).then(e => {
  8077. console.log(e);
  8078. setProgress(`${I18N('COLLECTED')} ${e?.results?.length} ${I18N('REWARD')}`, true);
  8079. });
  8080. });
  8081. }
  8082.  
  8083. /**
  8084. * Assemble Outland
  8085. *
  8086. * Собрать запределье
  8087. */
  8088. function getOutland() {
  8089. return new Promise(function (resolve, reject) {
  8090. send('{"calls":[{"name":"bossGetAll","args":{},"ident":"bossGetAll"}]}', e => {
  8091. let bosses = e.results[0].result.response;
  8092.  
  8093. let bossRaidOpenChestCall = {
  8094. calls: []
  8095. };
  8096.  
  8097. for (let boss of bosses) {
  8098. if (boss.mayRaid) {
  8099. bossRaidOpenChestCall.calls.push({
  8100. name: "bossRaid",
  8101. args: {
  8102. bossId: boss.id
  8103. },
  8104. ident: "bossRaid_" + boss.id
  8105. });
  8106. bossRaidOpenChestCall.calls.push({
  8107. name: "bossOpenChest",
  8108. args: {
  8109. bossId: boss.id,
  8110. amount: 1,
  8111. starmoney: 0
  8112. },
  8113. ident: "bossOpenChest_" + boss.id
  8114. });
  8115. } else if (boss.chestId == 1) {
  8116. bossRaidOpenChestCall.calls.push({
  8117. name: "bossOpenChest",
  8118. args: {
  8119. bossId: boss.id,
  8120. amount: 1,
  8121. starmoney: 0
  8122. },
  8123. ident: "bossOpenChest_" + boss.id
  8124. });
  8125. }
  8126. }
  8127.  
  8128. if (!bossRaidOpenChestCall.calls.length) {
  8129. setProgress(`${I18N('OUTLAND')} ${I18N('NOTHING_TO_COLLECT')}`, true);
  8130. resolve();
  8131. return;
  8132. }
  8133.  
  8134. send(JSON.stringify(bossRaidOpenChestCall), e => {
  8135. setProgress(`${I18N('OUTLAND')} ${I18N('COLLECTED')}`, true);
  8136. resolve();
  8137. });
  8138. });
  8139. });
  8140. }
  8141.  
  8142. /**
  8143. * Collect all rewards
  8144. *
  8145. * Собрать все награды
  8146. */
  8147. function questAllFarm() {
  8148. return new Promise(function (resolve, reject) {
  8149. let questGetAllCall = {
  8150. calls: [{
  8151. name: "questGetAll",
  8152. args: {},
  8153. ident: "body"
  8154. }]
  8155. }
  8156. send(JSON.stringify(questGetAllCall), function (data) {
  8157. let questGetAll = data.results[0].result.response;
  8158. const questAllFarmCall = {
  8159. calls: []
  8160. }
  8161. let number = 0;
  8162. for (let quest of questGetAll) {
  8163. if (quest.id < 1e6 && quest.state == 2) {
  8164. questAllFarmCall.calls.push({
  8165. name: "questFarm",
  8166. args: {
  8167. questId: quest.id
  8168. },
  8169. ident: `group_${number}_body`
  8170. });
  8171. number++;
  8172. }
  8173. }
  8174.  
  8175. if (!questAllFarmCall.calls.length) {
  8176. setProgress(`${I18N('COLLECTED')} ${number} ${I18N('REWARD')}`, true);
  8177. resolve();
  8178. return;
  8179. }
  8180.  
  8181. send(JSON.stringify(questAllFarmCall), function (res) {
  8182. console.log(res);
  8183. setProgress(`${I18N('COLLECTED')} ${number} ${I18N('REWARD')}`, true);
  8184. resolve();
  8185. });
  8186. });
  8187. })
  8188. }
  8189.  
  8190. /**
  8191. * Mission auto repeat
  8192. *
  8193. * Автоповтор миссии
  8194. * isStopSendMission = false;
  8195. * isSendsMission = true;
  8196. **/
  8197. this.sendsMission = async function (param) {
  8198. async function stopMission() {
  8199. isSendsMission = false;
  8200. console.log(I18N('STOPPED'));
  8201. setProgress('');
  8202. await popup.confirm(`${I18N('STOPPED')}<br>${I18N('REPETITIONS')}: ${param.count}`, [{
  8203. msg: 'Ok',
  8204. result: true
  8205. }, ])
  8206. }
  8207. if (isStopSendMission) {
  8208. stopMission();
  8209. return;
  8210. }
  8211. lastMissionBattleStart = Date.now();
  8212. let missionStartCall = {
  8213. "calls": [{
  8214. "name": "missionStart",
  8215. "args": lastMissionStart,
  8216. "ident": "body"
  8217. }]
  8218. }
  8219. /**
  8220. * Mission Request
  8221. *
  8222. * Запрос на выполнение мисии
  8223. */
  8224. SendRequest(JSON.stringify(missionStartCall), async e => {
  8225. if (e['error']) {
  8226. isSendsMission = false;
  8227. console.log(e['error']);
  8228. setProgress('');
  8229. let msg = e['error'].name + ' ' + e['error'].description + `<br>${I18N('REPETITIONS')}: ${param.count}`;
  8230. await popup.confirm(msg, [
  8231. {msg: 'Ok', result: true},
  8232. ])
  8233. return;
  8234. }
  8235. /**
  8236. * Mission data calculation
  8237. *
  8238. * Расчет данных мисии
  8239. */
  8240. BattleCalc(e.results[0].result.response, 'get_tower', async r => {
  8241. /** missionTimer */
  8242. let timer = getTimer(r.battleTime) + 5;
  8243. const period = Math.ceil((Date.now() - lastMissionBattleStart) / 1000);
  8244. if (period < timer) {
  8245. timer = timer - period;
  8246. const isSuccess = await countdownTimer(timer, `${I18N('MISSIONS_PASSED')}: ${param.count}`, () => {
  8247. isStopSendMission = true;
  8248. });
  8249. if (!isSuccess) {
  8250. stopMission();
  8251. return;
  8252. }
  8253. }
  8254.  
  8255. let missionEndCall = {
  8256. "calls": [{
  8257. "name": "missionEnd",
  8258. "args": {
  8259. "id": param.id,
  8260. "result": r.result,
  8261. "progress": r.progress
  8262. },
  8263. "ident": "body"
  8264. }]
  8265. }
  8266. /**
  8267. * Mission Completion Request
  8268. *
  8269. * Запрос на завершение миссии
  8270. */
  8271. SendRequest(JSON.stringify(missionEndCall), async (e) => {
  8272. if (e['error']) {
  8273. isSendsMission = false;
  8274. console.log(e['error']);
  8275. setProgress('');
  8276. let msg = e['error'].name + ' ' + e['error'].description + `<br>${I18N('REPETITIONS')}: ${param.count}`;
  8277. await popup.confirm(msg, [
  8278. {msg: 'Ok', result: true},
  8279. ])
  8280. return;
  8281. }
  8282. r = e.results[0].result.response;
  8283. if (r['error']) {
  8284. isSendsMission = false;
  8285. console.log(r['error']);
  8286. setProgress('');
  8287. await popup.confirm(`<br>${I18N('REPETITIONS')}: ${param.count}` + ' 3 ' + r['error'], [
  8288. {msg: 'Ok', result: true},
  8289. ])
  8290. return;
  8291. }
  8292.  
  8293. param.count++;
  8294. setProgress(`${I18N('MISSIONS_PASSED')}: ${param.count} (${I18N('STOP')})`, false, () => {
  8295. isStopSendMission = true;
  8296. });
  8297. setTimeout(sendsMission, 1, param);
  8298. });
  8299. })
  8300. });
  8301. }
  8302.  
  8303. /**
  8304. * Opening of russian dolls
  8305. *
  8306. * Открытие матрешек
  8307. */
  8308. async function openRussianDolls(libId, amount) {
  8309. let sum = 0;
  8310. const sumResult = {};
  8311. let count = 0;
  8312.  
  8313. while (amount) {
  8314. sum += amount;
  8315. setProgress(`${I18N('TOTAL_OPEN')} ${sum}`);
  8316. const calls = [
  8317. {
  8318. name: 'consumableUseLootBox',
  8319. args: { libId, amount },
  8320. ident: 'body',
  8321. },
  8322. ];
  8323. const response = await Send(JSON.stringify({ calls })).then((e) => e.results[0].result.response);
  8324. let [countLootBox, result] = Object.entries(response).pop();
  8325. count += +countLootBox;
  8326. let newCount = 0;
  8327.  
  8328. if (result?.consumable && result.consumable[libId]) {
  8329. newCount = result.consumable[libId];
  8330. delete result.consumable[libId];
  8331. }
  8332.  
  8333. mergeItemsObj(sumResult, result);
  8334. amount = newCount;
  8335. }
  8336.  
  8337. setProgress(`${I18N('TOTAL_OPEN')} ${sum}`, 5000);
  8338. return [count, sumResult];
  8339. }
  8340.  
  8341. function mergeItemsObj(obj1, obj2) {
  8342. for (const key in obj2) {
  8343. if (obj1[key]) {
  8344. if (typeof obj1[key] == 'object') {
  8345. for (const innerKey in obj2[key]) {
  8346. obj1[key][innerKey] = (obj1[key][innerKey] || 0) + obj2[key][innerKey];
  8347. }
  8348. } else {
  8349. obj1[key] += obj2[key] || 0;
  8350. }
  8351. } else {
  8352. obj1[key] = obj2[key];
  8353. }
  8354. }
  8355.  
  8356. return obj1;
  8357. }
  8358.  
  8359. /**
  8360. * Collect all mail, except letters with energy and charges of the portal
  8361. *
  8362. * Собрать всю почту, кроме писем с энергией и зарядами портала
  8363. */
  8364. function mailGetAll() {
  8365. const getMailInfo = '{"calls":[{"name":"mailGetAll","args":{},"ident":"body"}]}';
  8366.  
  8367. return Send(getMailInfo).then(dataMail => {
  8368. const letters = dataMail.results[0].result.response.letters;
  8369. const letterIds = lettersFilter(letters);
  8370. if (!letterIds.length) {
  8371. setProgress(I18N('NOTHING_TO_COLLECT'), true);
  8372. return;
  8373. }
  8374.  
  8375. const calls = [
  8376. { name: "mailFarm", args: { letterIds }, ident: "body" }
  8377. ];
  8378.  
  8379. return Send(JSON.stringify({ calls })).then(res => {
  8380. const lettersIds = res.results[0].result.response;
  8381. if (lettersIds) {
  8382. const countLetters = Object.keys(lettersIds).length;
  8383. setProgress(`${I18N('RECEIVED')} ${countLetters} ${I18N('LETTERS')}`, true);
  8384. }
  8385. });
  8386. });
  8387. }
  8388.  
  8389. /**
  8390. * Filters received emails
  8391. *
  8392. * Фильтрует получаемые письма
  8393. */
  8394. function lettersFilter(letters) {
  8395. const lettersIds = [];
  8396. for (let l in letters) {
  8397. letter = letters[l];
  8398. const reward = letter?.reward;
  8399. if (!reward || !Object.keys(reward).length) {
  8400. continue;
  8401. }
  8402. /**
  8403. * Mail Collection Exceptions
  8404. *
  8405. * Исключения на сбор писем
  8406. */
  8407. const isFarmLetter = !(
  8408. /** Portals // сферы портала */
  8409. (reward?.refillable ? reward.refillable[45] : false) ||
  8410. /** Energy // энергия */
  8411. (reward?.stamina ? reward.stamina : false) ||
  8412. /** accelerating energy gain // ускорение набора энергии */
  8413. (reward?.buff ? true : false) ||
  8414. /** VIP Points // вип очки */
  8415. (reward?.vipPoints ? reward.vipPoints : false) ||
  8416. /** souls of heroes // душы героев */
  8417. (reward?.fragmentHero ? true : false) ||
  8418. /** heroes // герои */
  8419. (reward?.bundleHeroReward ? true : false)
  8420. );
  8421. if (isFarmLetter) {
  8422. lettersIds.push(~~letter.id);
  8423. continue;
  8424. }
  8425. /**
  8426. * Если до окончания годности письма менее 24 часов,
  8427. * то оно собирается не смотря на исключения
  8428. */
  8429. const availableUntil = +letter?.availableUntil;
  8430. if (availableUntil) {
  8431. const maxTimeLeft = 24 * 60 * 60 * 1000;
  8432. const timeLeft = (new Date(availableUntil * 1000) - new Date())
  8433. console.log('Time left:', timeLeft)
  8434. if (timeLeft < maxTimeLeft) {
  8435. lettersIds.push(~~letter.id);
  8436. continue;
  8437. }
  8438. }
  8439. }
  8440. return lettersIds;
  8441. }
  8442.  
  8443. /**
  8444. * Displaying information about the areas of the portal and attempts on the VG
  8445. *
  8446. * Отображение информации о сферах портала и попытках на ВГ
  8447. */
  8448. async function justInfo() {
  8449. return new Promise(async (resolve, reject) => {
  8450. const calls = [
  8451. {
  8452. name: 'userGetInfo',
  8453. args: {},
  8454. ident: 'userGetInfo',
  8455. },
  8456. {
  8457. name: 'clanWarGetInfo',
  8458. args: {},
  8459. ident: 'clanWarGetInfo',
  8460. },
  8461. {
  8462. name: 'titanArenaGetStatus',
  8463. args: {},
  8464. ident: 'titanArenaGetStatus',
  8465. },
  8466. {
  8467. name: 'quest_completeEasterEggQuest',
  8468. args: {},
  8469. ident: 'quest_completeEasterEggQuest',
  8470. },
  8471. ];
  8472. const result = await Send(JSON.stringify({ calls }));
  8473. const infos = result.results;
  8474. const portalSphere = infos[0].result.response.refillable.find(n => n.id == 45);
  8475. const clanWarMyTries = infos[1].result.response?.myTries ?? 0;
  8476. const arePointsMax = infos[1].result.response?.arePointsMax;
  8477. const titansLevel = +(infos[2].result.response?.tier ?? 0);
  8478. const titansStatus = infos[2].result.response?.status; //peace_time || battle
  8479.  
  8480. const { buttons } = HWHData;
  8481. const sanctuaryButton = buttons['testAdventure'].button;
  8482. const sanctuaryDot = sanctuaryButton.querySelector('.scriptMenu_dot');
  8483. const clanWarButton = buttons['goToClanWar'].button;
  8484. const clanWarDot = clanWarButton.querySelector('.scriptMenu_dot');
  8485. const titansArenaButton = buttons['testTitanArena'].button;
  8486. const titansArenaDot = titansArenaButton.querySelector('.scriptMenu_dot');
  8487.  
  8488. if (portalSphere.amount) {
  8489. sanctuaryButton.classList.add('scriptMenu_attention');
  8490. sanctuaryDot.title = `${portalSphere.amount} ${I18N('PORTALS')}`;
  8491. sanctuaryDot.innerText = portalSphere.amount;
  8492. sanctuaryDot.style.backgroundColor = 'red';
  8493. } else {
  8494. sanctuaryButton.classList.remove('scriptMenu_attention');
  8495. }
  8496. if (clanWarMyTries && !arePointsMax) {
  8497. clanWarButton.classList.add('scriptMenu_attention');
  8498. clanWarDot.title = `${clanWarMyTries} ${I18N('ATTEMPTS')}`;
  8499. clanWarDot.innerText = clanWarMyTries;
  8500. clanWarDot.style.backgroundColor = 'red';
  8501. } else {
  8502. clanWarButton.classList.remove('scriptMenu_attention');
  8503. }
  8504.  
  8505. if (titansLevel < 7 && titansStatus == 'battle') { ;
  8506. titansArenaButton.classList.add('scriptMenu_attention');
  8507. titansArenaDot.title = `${titansLevel} ${I18N('LEVEL')}`;
  8508. titansArenaDot.innerText = titansLevel;
  8509. titansArenaDot.style.backgroundColor = 'red';
  8510. } else {
  8511. titansArenaButton.classList.remove('scriptMenu_attention');
  8512. }
  8513.  
  8514. const imgPortal =
  8515. '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';
  8516.  
  8517. setProgress('<img src="' + imgPortal + '" style="height: 25px;position: relative;top: 5px;"> ' + `${portalSphere.amount} </br> ${I18N('GUILD_WAR')}: ${clanWarMyTries}`, true);
  8518. resolve();
  8519. });
  8520. }
  8521.  
  8522. async function getDailyBonus() {
  8523. const dailyBonusInfo = await Send(JSON.stringify({
  8524. calls: [{
  8525. name: "dailyBonusGetInfo",
  8526. args: {},
  8527. ident: "body"
  8528. }]
  8529. })).then(e => e.results[0].result.response);
  8530. const { availableToday, availableVip, currentDay } = dailyBonusInfo;
  8531.  
  8532. if (!availableToday) {
  8533. console.log('Уже собрано');
  8534. return;
  8535. }
  8536.  
  8537. const currentVipPoints = +userInfo.vipPoints;
  8538. const dailyBonusStat = lib.getData('dailyBonusStatic');
  8539. const vipInfo = lib.getData('level').vip;
  8540. let currentVipLevel = 0;
  8541. for (let i in vipInfo) {
  8542. vipLvl = vipInfo[i];
  8543. if (currentVipPoints >= vipLvl.vipPoints) {
  8544. currentVipLevel = vipLvl.level;
  8545. }
  8546. }
  8547. const vipLevelDouble = dailyBonusStat[`${currentDay}_0_0`].vipLevelDouble;
  8548.  
  8549. const calls = [{
  8550. name: "dailyBonusFarm",
  8551. args: {
  8552. vip: availableVip && currentVipLevel >= vipLevelDouble ? 1 : 0
  8553. },
  8554. ident: "body"
  8555. }];
  8556.  
  8557. const result = await Send(JSON.stringify({ calls }));
  8558. if (result.error) {
  8559. console.error(result.error);
  8560. return;
  8561. }
  8562.  
  8563. const reward = result.results[0].result.response;
  8564. const type = Object.keys(reward).pop();
  8565. const itemId = Object.keys(reward[type]).pop();
  8566. const count = reward[type][itemId];
  8567. const itemName = cheats.translate(`LIB_${type.toUpperCase()}_NAME_${itemId}`);
  8568.  
  8569. console.log(`Ежедневная награда: Получено ${count} ${itemName}`, reward);
  8570. }
  8571.  
  8572. async function farmStamina(lootBoxId = 148) {
  8573. const lootBox = await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"}]}')
  8574. .then(e => e.results[0].result.response.consumable[148]);
  8575.  
  8576. /** Добавить другие ящики */
  8577. /**
  8578. * 144 - медная шкатулка
  8579. * 145 - бронзовая шкатулка
  8580. * 148 - платиновая шкатулка
  8581. */
  8582. if (!lootBox) {
  8583. setProgress(I18N('NO_BOXES'), true);
  8584. return;
  8585. }
  8586.  
  8587. let maxFarmEnergy = getSaveVal('maxFarmEnergy', 100);
  8588. const result = await popup.confirm(I18N('OPEN_LOOTBOX', { lootBox }), [
  8589. { result: false, isClose: true },
  8590. { msg: I18N('BTN_YES'), result: true },
  8591. { msg: I18N('STAMINA'), isInput: true, default: maxFarmEnergy },
  8592. ]);
  8593. if (!+result) {
  8594. return;
  8595. }
  8596.  
  8597. if ((typeof result) !== 'boolean' && Number.parseInt(result)) {
  8598. maxFarmEnergy = +result;
  8599. setSaveVal('maxFarmEnergy', maxFarmEnergy);
  8600. } else {
  8601. maxFarmEnergy = 0;
  8602. }
  8603.  
  8604. let collectEnergy = 0;
  8605. for (let count = lootBox; count > 0; count--) {
  8606. const response = await Send('{"calls":[{"name":"consumableUseLootBox","args":{"libId":148,"amount":1},"ident":"body"}]}').then(
  8607. (e) => e.results[0].result.response
  8608. );
  8609. const result = Object.values(response).pop();
  8610. if ('stamina' in result) {
  8611. setProgress(`${I18N('OPEN')}: ${lootBox - count}/${lootBox} ${I18N('STAMINA')} +${result.stamina}<br>${I18N('STAMINA')}: ${collectEnergy}`, false);
  8612. console.log(`${ I18N('STAMINA') } + ${ result.stamina }`);
  8613. if (!maxFarmEnergy) {
  8614. return;
  8615. }
  8616. collectEnergy += +result.stamina;
  8617. if (collectEnergy >= maxFarmEnergy) {
  8618. console.log(`${I18N('STAMINA')} + ${ collectEnergy }`);
  8619. setProgress(`${I18N('STAMINA')} + ${ collectEnergy }`, false);
  8620. return;
  8621. }
  8622. } else {
  8623. setProgress(`${I18N('OPEN')}: ${lootBox - count}/${lootBox}<br>${I18N('STAMINA')}: ${collectEnergy}`, false);
  8624. console.log(result);
  8625. }
  8626. }
  8627.  
  8628. setProgress(I18N('BOXES_OVER'), true);
  8629. }
  8630.  
  8631. async function fillActive() {
  8632. const data = await Send(JSON.stringify({
  8633. calls: [{
  8634. name: "questGetAll",
  8635. args: {},
  8636. ident: "questGetAll"
  8637. }, {
  8638. name: "inventoryGet",
  8639. args: {},
  8640. ident: "inventoryGet"
  8641. }, {
  8642. name: "clanGetInfo",
  8643. args: {},
  8644. ident: "clanGetInfo"
  8645. }
  8646. ]
  8647. })).then(e => e.results.map(n => n.result.response));
  8648.  
  8649. const quests = data[0];
  8650. const inv = data[1];
  8651. const stat = data[2].stat;
  8652. const maxActive = 2000 - stat.todayItemsActivity;
  8653. if (maxActive <= 0) {
  8654. setProgress(I18N('NO_MORE_ACTIVITY'), true);
  8655. return;
  8656. }
  8657. let countGetActive = 0;
  8658. const quest = quests.find(e => e.id > 10046 && e.id < 10051);
  8659. if (quest) {
  8660. countGetActive = 1750 - quest.progress;
  8661. }
  8662. if (countGetActive <= 0) {
  8663. countGetActive = maxActive;
  8664. }
  8665. console.log(countGetActive);
  8666.  
  8667. countGetActive = +(await popup.confirm(I18N('EXCHANGE_ITEMS', { maxActive }), [
  8668. { result: false, isClose: true },
  8669. { msg: I18N('GET_ACTIVITY'), isInput: true, default: countGetActive.toString() },
  8670. ]));
  8671.  
  8672. if (!countGetActive) {
  8673. return;
  8674. }
  8675.  
  8676. if (countGetActive > maxActive) {
  8677. countGetActive = maxActive;
  8678. }
  8679.  
  8680. const items = lib.getData('inventoryItem');
  8681.  
  8682. let itemsInfo = [];
  8683. for (let type of ['gear', 'scroll']) {
  8684. for (let i in inv[type]) {
  8685. const v = items[type][i]?.enchantValue || 0;
  8686. itemsInfo.push({
  8687. id: i,
  8688. count: inv[type][i],
  8689. v,
  8690. type
  8691. })
  8692. }
  8693. const invType = 'fragment' + type.toLowerCase().charAt(0).toUpperCase() + type.slice(1);
  8694. for (let i in inv[invType]) {
  8695. const v = items[type][i]?.fragmentEnchantValue || 0;
  8696. itemsInfo.push({
  8697. id: i,
  8698. count: inv[invType][i],
  8699. v,
  8700. type: invType
  8701. })
  8702. }
  8703. }
  8704. itemsInfo = itemsInfo.filter(e => e.v < 4 && e.count > 200);
  8705. itemsInfo = itemsInfo.sort((a, b) => b.count - a.count);
  8706. console.log(itemsInfo);
  8707. const activeItem = itemsInfo.shift();
  8708. console.log(activeItem);
  8709. const countItem = Math.ceil(countGetActive / activeItem.v);
  8710. if (countItem > activeItem.count) {
  8711. setProgress(I18N('NOT_ENOUGH_ITEMS'), true);
  8712. console.log(activeItem);
  8713. return;
  8714. }
  8715.  
  8716. await Send(JSON.stringify({
  8717. calls: [{
  8718. name: "clanItemsForActivity",
  8719. args: {
  8720. items: {
  8721. [activeItem.type]: {
  8722. [activeItem.id]: countItem
  8723. }
  8724. }
  8725. },
  8726. ident: "body"
  8727. }]
  8728. })).then(e => {
  8729. /** TODO: Вывести потраченые предметы */
  8730. console.log(e);
  8731. setProgress(`${I18N('ACTIVITY_RECEIVED')}: ` + e.results[0].result.response, true);
  8732. });
  8733. }
  8734.  
  8735. async function buyHeroFragments() {
  8736. const result = await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"},{"name":"shopGetAll","args":{},"ident":"shopGetAll"}]}')
  8737. .then(e => e.results.map(n => n.result.response));
  8738. const inv = result[0];
  8739. const shops = Object.values(result[1]).filter(shop => [4, 5, 6, 8, 9, 10, 17].includes(shop.id));
  8740. const calls = [];
  8741.  
  8742. for (let shop of shops) {
  8743. const slots = Object.values(shop.slots);
  8744. for (const slot of slots) {
  8745. /* Уже куплено */
  8746. if (slot.bought) {
  8747. continue;
  8748. }
  8749. /* Не душа героя */
  8750. if (!('fragmentHero' in slot.reward)) {
  8751. continue;
  8752. }
  8753. const coin = Object.keys(slot.cost).pop();
  8754. const coinId = Object.keys(slot.cost[coin]).pop();
  8755. const stock = inv[coin][coinId] || 0;
  8756. /* Не хватает на покупку */
  8757. if (slot.cost[coin][coinId] > stock) {
  8758. continue;
  8759. }
  8760. inv[coin][coinId] -= slot.cost[coin][coinId];
  8761. calls.push({
  8762. name: "shopBuy",
  8763. args: {
  8764. shopId: shop.id,
  8765. slot: slot.id,
  8766. cost: slot.cost,
  8767. reward: slot.reward,
  8768. },
  8769. ident: `shopBuy_${shop.id}_${slot.id}`,
  8770. })
  8771. }
  8772. }
  8773.  
  8774. if (!calls.length) {
  8775. setProgress(I18N('NO_PURCHASABLE_HERO_SOULS'), true);
  8776. return;
  8777. }
  8778.  
  8779. const bought = await Send(JSON.stringify({ calls })).then(e => e.results.map(n => n.result.response));
  8780. if (!bought) {
  8781. console.log('что-то пошло не так')
  8782. return;
  8783. }
  8784.  
  8785. let countHeroSouls = 0;
  8786. for (const buy of bought) {
  8787. countHeroSouls += +Object.values(Object.values(buy).pop()).pop();
  8788. }
  8789. console.log(countHeroSouls, bought, calls);
  8790. setProgress(I18N('PURCHASED_HERO_SOULS', { countHeroSouls }), true);
  8791. }
  8792.  
  8793. /** Открыть платные сундуки в Запределье за 90 */
  8794. async function bossOpenChestPay() {
  8795. const callsNames = ['userGetInfo', 'bossGetAll', 'specialOffer_getAll', 'getTime'];
  8796. const info = await Send({ calls: callsNames.map((name) => ({ name, args: {}, ident: name })) }).then((e) =>
  8797. e.results.map((n) => n.result.response)
  8798. );
  8799.  
  8800. const user = info[0];
  8801. const boses = info[1];
  8802. const offers = info[2];
  8803. const time = info[3];
  8804.  
  8805. const discountOffer = offers.find((e) => e.offerType == 'costReplaceOutlandChest');
  8806.  
  8807. let discount = 1;
  8808. if (discountOffer && discountOffer.endTime > time) {
  8809. discount = 1 - discountOffer.offerData.outlandChest.discountPercent / 100;
  8810. }
  8811.  
  8812. cost9chests = 540 * discount;
  8813. cost18chests = 1740 * discount;
  8814. costFirstChest = 90 * discount;
  8815. costSecondChest = 200 * discount;
  8816.  
  8817. const currentStarMoney = user.starMoney;
  8818. if (currentStarMoney < cost9chests) {
  8819. setProgress('Недостаточно изюма, нужно ' + cost9chests + ' у Вас ' + currentStarMoney, true);
  8820. return;
  8821. }
  8822.  
  8823. const imgEmerald =
  8824. "<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='>";
  8825.  
  8826. if (currentStarMoney < cost9chests) {
  8827. setProgress(I18N('NOT_ENOUGH_EMERALDS_540', { currentStarMoney, imgEmerald }), true);
  8828. return;
  8829. }
  8830.  
  8831. const buttons = [{ result: false, isClose: true }];
  8832.  
  8833. if (currentStarMoney >= cost9chests) {
  8834. buttons.push({
  8835. msg: I18N('BUY_OUTLAND_BTN', { count: 9, countEmerald: cost9chests, imgEmerald }),
  8836. result: [costFirstChest, costFirstChest, 0],
  8837. });
  8838. }
  8839.  
  8840. if (currentStarMoney >= cost18chests) {
  8841. buttons.push({
  8842. msg: I18N('BUY_OUTLAND_BTN', { count: 18, countEmerald: cost18chests, imgEmerald }),
  8843. result: [costFirstChest, costFirstChest, 0, costSecondChest, costSecondChest, 0],
  8844. });
  8845. }
  8846.  
  8847. const answer = await popup.confirm(`<div style="margin-bottom: 15px;">${I18N('BUY_OUTLAND')}</div>`, buttons);
  8848.  
  8849. if (!answer) {
  8850. return;
  8851. }
  8852.  
  8853. const callBoss = [];
  8854. let n = 0;
  8855. for (let boss of boses) {
  8856. const bossId = boss.id;
  8857. if (boss.chestNum != 2) {
  8858. continue;
  8859. }
  8860. const calls = [];
  8861. for (const starmoney of answer) {
  8862. calls.push({
  8863. name: 'bossOpenChest',
  8864. args: {
  8865. amount: 1,
  8866. bossId,
  8867. starmoney,
  8868. },
  8869. ident: 'bossOpenChest_' + ++n,
  8870. });
  8871. }
  8872. callBoss.push(calls);
  8873. }
  8874.  
  8875. if (!callBoss.length) {
  8876. setProgress(I18N('CHESTS_NOT_AVAILABLE'), true);
  8877. return;
  8878. }
  8879.  
  8880. let count = 0;
  8881. let errors = 0;
  8882. for (const calls of callBoss) {
  8883. const result = await Send({ calls });
  8884. console.log(result);
  8885. if (result?.results) {
  8886. count += result.results.length;
  8887. } else {
  8888. errors++;
  8889. }
  8890. }
  8891.  
  8892. setProgress(`${I18N('OUTLAND_CHESTS_RECEIVED')}: ${count}`, true);
  8893. }
  8894.  
  8895. async function autoRaidAdventure() {
  8896. const calls = [
  8897. {
  8898. name: "userGetInfo",
  8899. args: {},
  8900. ident: "userGetInfo"
  8901. },
  8902. {
  8903. name: "adventure_raidGetInfo",
  8904. args: {},
  8905. ident: "adventure_raidGetInfo"
  8906. }
  8907. ];
  8908. const result = await Send(JSON.stringify({ calls }))
  8909. .then(e => e.results.map(n => n.result.response));
  8910.  
  8911. const portalSphere = result[0].refillable.find(n => n.id == 45);
  8912. const adventureRaid = Object.entries(result[1].raid).filter(e => e[1]).pop()
  8913. const adventureId = adventureRaid ? adventureRaid[0] : 0;
  8914.  
  8915. if (!portalSphere.amount || !adventureId) {
  8916. setProgress(I18N('RAID_NOT_AVAILABLE'), true);
  8917. return;
  8918. }
  8919.  
  8920. const countRaid = +(await popup.confirm(I18N('RAID_ADVENTURE', { adventureId }), [
  8921. { result: false, isClose: true },
  8922. { msg: I18N('RAID'), isInput: true, default: portalSphere.amount },
  8923. ]));
  8924.  
  8925. if (!countRaid) {
  8926. return;
  8927. }
  8928.  
  8929. if (countRaid > portalSphere.amount) {
  8930. countRaid = portalSphere.amount;
  8931. }
  8932.  
  8933. const resultRaid = await Send(JSON.stringify({
  8934. calls: [...Array(countRaid)].map((e, i) => ({
  8935. name: "adventure_raid",
  8936. args: {
  8937. adventureId
  8938. },
  8939. ident: `body_${i}`
  8940. }))
  8941. })).then(e => e.results.map(n => n.result.response));
  8942.  
  8943. if (!resultRaid.length) {
  8944. console.log(resultRaid);
  8945. setProgress(I18N('SOMETHING_WENT_WRONG'), true);
  8946. return;
  8947. }
  8948.  
  8949. console.log(resultRaid, adventureId, portalSphere.amount);
  8950. setProgress(I18N('ADVENTURE_COMPLETED', { adventureId, times: resultRaid.length }), true);
  8951. }
  8952.  
  8953. /** Вывести всю клановую статистику в консоль браузера */
  8954. async function clanStatistic() {
  8955. const copy = function (text) {
  8956. const copyTextarea = document.createElement("textarea");
  8957. copyTextarea.style.opacity = "0";
  8958. copyTextarea.textContent = text;
  8959. document.body.appendChild(copyTextarea);
  8960. copyTextarea.select();
  8961. document.execCommand("copy");
  8962. document.body.removeChild(copyTextarea);
  8963. delete copyTextarea;
  8964. }
  8965. const calls = [
  8966. { name: "clanGetInfo", args: {}, ident: "clanGetInfo" },
  8967. { name: "clanGetWeeklyStat", args: {}, ident: "clanGetWeeklyStat" },
  8968. { name: "clanGetLog", args: {}, ident: "clanGetLog" },
  8969. ];
  8970.  
  8971. const result = await Send(JSON.stringify({ calls }));
  8972.  
  8973. const dataClanInfo = result.results[0].result.response;
  8974. const dataClanStat = result.results[1].result.response;
  8975. const dataClanLog = result.results[2].result.response;
  8976.  
  8977. const membersStat = {};
  8978. for (let i = 0; i < dataClanStat.stat.length; i++) {
  8979. membersStat[dataClanStat.stat[i].id] = dataClanStat.stat[i];
  8980. }
  8981.  
  8982. const joinStat = {};
  8983. historyLog = dataClanLog.history;
  8984. for (let j in historyLog) {
  8985. his = historyLog[j];
  8986. if (his.event == 'join') {
  8987. joinStat[his.userId] = his.ctime;
  8988. }
  8989. }
  8990.  
  8991. const infoArr = [];
  8992. const members = dataClanInfo.clan.members;
  8993. for (let n in members) {
  8994. var member = [
  8995. n,
  8996. members[n].name,
  8997. members[n].level,
  8998. dataClanInfo.clan.warriors.includes(+n) ? 1 : 0,
  8999. (new Date(members[n].lastLoginTime * 1000)).toLocaleString().replace(',', ''),
  9000. joinStat[n] ? (new Date(joinStat[n] * 1000)).toLocaleString().replace(',', '') : '',
  9001. membersStat[n].activity.reverse().join('\t'),
  9002. membersStat[n].adventureStat.reverse().join('\t'),
  9003. membersStat[n].clanGifts.reverse().join('\t'),
  9004. membersStat[n].clanWarStat.reverse().join('\t'),
  9005. membersStat[n].dungeonActivity.reverse().join('\t'),
  9006. ];
  9007. infoArr.push(member);
  9008. }
  9009. const info = infoArr.sort((a, b) => (b[2] - a[2])).map((e) => e.join('\t')).join('\n');
  9010. console.log(info);
  9011. copy(info);
  9012. setProgress(I18N('CLAN_STAT_COPY'), true);
  9013. }
  9014.  
  9015. async function buyInStoreForGold() {
  9016. const result = await Send('{"calls":[{"name":"shopGetAll","args":{},"ident":"body"},{"name":"userGetInfo","args":{},"ident":"userGetInfo"}]}').then(e => e.results.map(n => n.result.response));
  9017. const shops = result[0];
  9018. const user = result[1];
  9019. let gold = user.gold;
  9020. const calls = [];
  9021. if (shops[17]) {
  9022. const slots = shops[17].slots;
  9023. for (let i = 1; i <= 2; i++) {
  9024. if (!slots[i].bought) {
  9025. const costGold = slots[i].cost.gold;
  9026. if ((gold - costGold) < 0) {
  9027. continue;
  9028. }
  9029. gold -= costGold;
  9030. calls.push({
  9031. name: "shopBuy",
  9032. args: {
  9033. shopId: 17,
  9034. slot: i,
  9035. cost: slots[i].cost,
  9036. reward: slots[i].reward,
  9037. },
  9038. ident: 'body_' + i,
  9039. })
  9040. }
  9041. }
  9042. }
  9043. const slots = shops[1].slots;
  9044. for (let i = 4; i <= 6; i++) {
  9045. if (!slots[i].bought && slots[i]?.cost?.gold) {
  9046. const costGold = slots[i].cost.gold;
  9047. if ((gold - costGold) < 0) {
  9048. continue;
  9049. }
  9050. gold -= costGold;
  9051. calls.push({
  9052. name: "shopBuy",
  9053. args: {
  9054. shopId: 1,
  9055. slot: i,
  9056. cost: slots[i].cost,
  9057. reward: slots[i].reward,
  9058. },
  9059. ident: 'body_' + i,
  9060. })
  9061. }
  9062. }
  9063.  
  9064. if (!calls.length) {
  9065. setProgress(I18N('NOTHING_BUY'), true);
  9066. return;
  9067. }
  9068.  
  9069. const resultBuy = await Send(JSON.stringify({ calls })).then(e => e.results.map(n => n.result.response));
  9070. console.log(resultBuy);
  9071. const countBuy = resultBuy.length;
  9072. setProgress(I18N('LOTS_BOUGHT', { countBuy }), true);
  9073. }
  9074.  
  9075. function rewardsAndMailFarm() {
  9076. return new Promise(function (resolve, reject) {
  9077. let questGetAllCall = {
  9078. calls: [{
  9079. name: "questGetAll",
  9080. args: {},
  9081. ident: "questGetAll"
  9082. }, {
  9083. name: "mailGetAll",
  9084. args: {},
  9085. ident: "mailGetAll"
  9086. }]
  9087. }
  9088. send(JSON.stringify(questGetAllCall), function (data) {
  9089. if (!data) return;
  9090. const questGetAll = data.results[0].result.response.filter((e) => e.state == 2);
  9091. const questBattlePass = lib.getData('quest').battlePass;
  9092. const questChainBPass = lib.getData('battlePass').questChain;
  9093. const listBattlePass = lib.getData('battlePass').list;
  9094.  
  9095. const questAllFarmCall = {
  9096. calls: [],
  9097. };
  9098. const questIds = [];
  9099. for (let quest of questGetAll) {
  9100. if (quest.id >= 2001e4) {
  9101. continue;
  9102. }
  9103. if (quest.id > 1e6 && quest.id < 2e7) {
  9104. const questInfo = questBattlePass[quest.id];
  9105. const chain = questChainBPass[questInfo.chain];
  9106. if (chain.requirement?.battlePassTicket) {
  9107. continue;
  9108. }
  9109. const battlePass = listBattlePass[chain.battlePass];
  9110. const startTime = battlePass.startCondition.time.value * 1e3
  9111. const endTime = new Date(startTime + battlePass.duration * 1e3);
  9112. if (startTime > Date.now() || endTime < Date.now()) {
  9113. continue;
  9114. }
  9115. }
  9116. if (quest.id >= 2e7) {
  9117. questIds.push(quest.id);
  9118. continue;
  9119. }
  9120. questAllFarmCall.calls.push({
  9121. name: 'questFarm',
  9122. args: {
  9123. questId: quest.id,
  9124. },
  9125. ident: `questFarm_${quest.id}`,
  9126. });
  9127. }
  9128.  
  9129. if (questIds.length) {
  9130. questAllFarmCall.calls.push({
  9131. name: 'quest_questsFarm',
  9132. args: { questIds },
  9133. ident: 'quest_questsFarm',
  9134. });
  9135. }
  9136.  
  9137. let letters = data?.results[1]?.result?.response?.letters;
  9138. letterIds = lettersFilter(letters);
  9139.  
  9140. if (letterIds.length) {
  9141. questAllFarmCall.calls.push({
  9142. name: 'mailFarm',
  9143. args: { letterIds },
  9144. ident: 'mailFarm',
  9145. });
  9146. }
  9147.  
  9148. if (!questAllFarmCall.calls.length) {
  9149. setProgress(I18N('NOTHING_TO_COLLECT'), true);
  9150. resolve();
  9151. return;
  9152. }
  9153.  
  9154. send(JSON.stringify(questAllFarmCall), async function (res) {
  9155. let countQuests = 0;
  9156. let countMail = 0;
  9157. let questsIds = [];
  9158. for (let call of res.results) {
  9159. if (call.ident.includes('questFarm')) {
  9160. countQuests++;
  9161. } else if (call.ident.includes('questsFarm')) {
  9162. countQuests += Object.keys(call.result.response).length;
  9163. } else if (call.ident.includes('mailFarm')) {
  9164. countMail = Object.keys(call.result.response).length;
  9165. }
  9166.  
  9167. const newQuests = call.result.newQuests;
  9168. if (newQuests) {
  9169. for (let quest of newQuests) {
  9170. if ((quest.id < 1e6 || (quest.id >= 2e7 && quest.id < 2001e4)) && quest.state == 2) {
  9171. questsIds.push(quest.id);
  9172. }
  9173. }
  9174. }
  9175. }
  9176.  
  9177. while (questsIds.length) {
  9178. const questIds = [];
  9179. const calls = [];
  9180. for (let questId of questsIds) {
  9181. if (questId < 1e6) {
  9182. calls.push({
  9183. name: 'questFarm',
  9184. args: {
  9185. questId,
  9186. },
  9187. ident: `questFarm_${questId}`,
  9188. });
  9189. countQuests++;
  9190. } else if (questId >= 2e7 && questId < 2001e4) {
  9191. questIds.push(questId);
  9192. countQuests++;
  9193. }
  9194. }
  9195. calls.push({
  9196. name: 'quest_questsFarm',
  9197. args: { questIds },
  9198. ident: 'body',
  9199. });
  9200. const results = await Send({ calls }).then((e) => e.results.map((e) => e.result));
  9201. questsIds = [];
  9202. for (const result of results) {
  9203. const newQuests = result.newQuests;
  9204. if (newQuests) {
  9205. for (let quest of newQuests) {
  9206. if (quest.state == 2) {
  9207. questsIds.push(quest.id);
  9208. }
  9209. }
  9210. }
  9211. }
  9212. }
  9213.  
  9214. setProgress(I18N('COLLECT_REWARDS_AND_MAIL', { countQuests, countMail }), true);
  9215. resolve();
  9216. });
  9217. });
  9218. })
  9219. }
  9220.  
  9221. class epicBrawl {
  9222. timeout = null;
  9223. time = null;
  9224.  
  9225. constructor() {
  9226. if (epicBrawl.inst) {
  9227. return epicBrawl.inst;
  9228. }
  9229. epicBrawl.inst = this;
  9230. return this;
  9231. }
  9232.  
  9233. runTimeout(func, timeDiff) {
  9234. const worker = new Worker(URL.createObjectURL(new Blob([`
  9235. self.onmessage = function(e) {
  9236. const timeDiff = e.data;
  9237.  
  9238. if (timeDiff > 0) {
  9239. setTimeout(() => {
  9240. self.postMessage(1);
  9241. self.close();
  9242. }, timeDiff);
  9243. }
  9244. };
  9245. `])));
  9246. worker.postMessage(timeDiff);
  9247. worker.onmessage = () => {
  9248. func();
  9249. };
  9250. return true;
  9251. }
  9252.  
  9253. timeDiff(date1, date2) {
  9254. const date1Obj = new Date(date1);
  9255. const date2Obj = new Date(date2);
  9256.  
  9257. const timeDiff = Math.abs(date2Obj - date1Obj);
  9258.  
  9259. const totalSeconds = timeDiff / 1000;
  9260. const minutes = Math.floor(totalSeconds / 60);
  9261. const seconds = Math.floor(totalSeconds % 60);
  9262.  
  9263. const formattedMinutes = String(minutes).padStart(2, '0');
  9264. const formattedSeconds = String(seconds).padStart(2, '0');
  9265.  
  9266. return `${formattedMinutes}:${formattedSeconds}`;
  9267. }
  9268.  
  9269. check() {
  9270. console.log(new Date(this.time))
  9271. if (Date.now() > this.time) {
  9272. this.timeout = null;
  9273. this.start()
  9274. return;
  9275. }
  9276. this.timeout = this.runTimeout(() => this.check(), 6e4);
  9277. return this.timeDiff(this.time, Date.now())
  9278. }
  9279.  
  9280. async start() {
  9281. if (this.timeout) {
  9282. const time = this.timeDiff(this.time, Date.now());
  9283. console.log(new Date(this.time))
  9284. setProgress(I18N('TIMER_ALREADY', { time }), false, hideProgress);
  9285. return;
  9286. }
  9287. setProgress(I18N('EPIC_BRAWL'), false, hideProgress);
  9288. 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));
  9289. const refill = teamInfo[2].refillable.find(n => n.id == 52)
  9290. this.time = (refill.lastRefill + 3600) * 1000
  9291. const attempts = refill.amount;
  9292. if (!attempts) {
  9293. console.log(new Date(this.time));
  9294. const time = this.check();
  9295. setProgress(I18N('NO_ATTEMPTS_TIMER_START', { time }), false, hideProgress);
  9296. return;
  9297. }
  9298.  
  9299. if (!teamInfo[0].epic_brawl) {
  9300. setProgress(I18N('NO_HEROES_PACK'), false, hideProgress);
  9301. return;
  9302. }
  9303.  
  9304. const args = {
  9305. heroes: teamInfo[0].epic_brawl.filter(e => e < 1000),
  9306. pet: teamInfo[0].epic_brawl.filter(e => e > 6000).pop(),
  9307. favor: teamInfo[1].epic_brawl,
  9308. }
  9309.  
  9310. let wins = 0;
  9311. let coins = 0;
  9312. let streak = { progress: 0, nextStage: 0 };
  9313. for (let i = attempts; i > 0; i--) {
  9314. const info = await Send(JSON.stringify({
  9315. calls: [
  9316. { name: "epicBrawl_getEnemy", args: {}, ident: "epicBrawl_getEnemy" }, { name: "epicBrawl_startBattle", args, ident: "epicBrawl_startBattle" }
  9317. ]
  9318. })).then(e => e.results.map(n => n.result.response));
  9319.  
  9320. const { progress, result } = await Calc(info[1].battle);
  9321. 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));
  9322.  
  9323. const resultInfo = endResult[0].result;
  9324. streak = endResult[1];
  9325.  
  9326. wins += resultInfo.win;
  9327. coins += resultInfo.reward ? resultInfo.reward.coin[39] : 0;
  9328.  
  9329. console.log(endResult[0].result)
  9330. if (endResult[1].progress == endResult[1].nextStage) {
  9331. const farm = await Send('{"calls":[{"name":"epicBrawl_farmWinStreak","args":{},"ident":"body"}]}').then(e => e.results[0].result.response);
  9332. coins += farm.coin[39];
  9333. }
  9334.  
  9335. setProgress(I18N('EPIC_BRAWL_RESULT', {
  9336. i, wins, attempts, coins,
  9337. progress: streak.progress,
  9338. nextStage: streak.nextStage,
  9339. end: '',
  9340. }), false, hideProgress);
  9341. }
  9342.  
  9343. console.log(new Date(this.time));
  9344. const time = this.check();
  9345. setProgress(I18N('EPIC_BRAWL_RESULT', {
  9346. wins, attempts, coins,
  9347. i: '',
  9348. progress: streak.progress,
  9349. nextStage: streak.nextStage,
  9350. end: I18N('ATTEMPT_ENDED', { time }),
  9351. }), false, hideProgress);
  9352. }
  9353. }
  9354.  
  9355. function countdownTimer(seconds, message, onClick = null) {
  9356. message = message || I18N('TIMER');
  9357. const stopTimer = Date.now() + seconds * 1e3;
  9358. const isOnClick = typeof onClick === 'function';
  9359. return new Promise((resolve) => {
  9360. const interval = setInterval(async () => {
  9361. const now = Date.now();
  9362. const remaining = (stopTimer - now) / 1000;
  9363. const clickHandler = isOnClick
  9364. ? () => {
  9365. onClick();
  9366. clearInterval(interval);
  9367. setProgress('', true);
  9368. resolve(false);
  9369. }
  9370. : undefined;
  9371.  
  9372. setProgress(`${message} ${remaining.toFixed(2)}`, false, clickHandler);
  9373. if (now > stopTimer) {
  9374. clearInterval(interval);
  9375. setProgress('', true);
  9376. resolve(true);
  9377. }
  9378. }, 100);
  9379. });
  9380. }
  9381.  
  9382. this.HWHFuncs.countdownTimer = countdownTimer;
  9383.  
  9384. /** Набить килов в горниле душк */
  9385. async function bossRatingEventSouls() {
  9386. const data = await Send({
  9387. calls: [
  9388. { name: "heroGetAll", args: {}, ident: "teamGetAll" },
  9389. { name: "offerGetAll", args: {}, ident: "offerGetAll" },
  9390. { name: "pet_getAll", args: {}, ident: "pet_getAll" },
  9391. ]
  9392. });
  9393. const bossEventInfo = data.results[1].result.response.find(e => e.offerType == "bossEvent");
  9394. if (!bossEventInfo) {
  9395. setProgress('Эвент завершен', true);
  9396. return;
  9397. }
  9398.  
  9399. if (bossEventInfo.progress.score > 250) {
  9400. setProgress('Уже убито больше 250 врагов');
  9401. rewardBossRatingEventSouls();
  9402. return;
  9403. }
  9404. const availablePets = Object.values(data.results[2].result.response).map(e => e.id);
  9405. const heroGetAllList = data.results[0].result.response;
  9406. const usedHeroes = bossEventInfo.progress.usedHeroes;
  9407. const heroList = [];
  9408.  
  9409. for (let heroId in heroGetAllList) {
  9410. let hero = heroGetAllList[heroId];
  9411. if (usedHeroes.includes(hero.id)) {
  9412. continue;
  9413. }
  9414. heroList.push(hero.id);
  9415. }
  9416.  
  9417. if (!heroList.length) {
  9418. setProgress('Нет героев', true);
  9419. return;
  9420. }
  9421.  
  9422. const pet = availablePets.includes(6005) ? 6005 : availablePets[Math.floor(Math.random() * availablePets.length)];
  9423. const petLib = lib.getData('pet');
  9424. let count = 1;
  9425.  
  9426. for (const heroId of heroList) {
  9427. const args = {
  9428. heroes: [heroId],
  9429. pet
  9430. }
  9431. /** Поиск питомца для героя */
  9432. for (const petId of availablePets) {
  9433. if (petLib[petId].favorHeroes.includes(heroId)) {
  9434. args.favor = {
  9435. [heroId]: petId
  9436. }
  9437. break;
  9438. }
  9439. }
  9440.  
  9441. const calls = [{
  9442. name: "bossRatingEvent_startBattle",
  9443. args,
  9444. ident: "body"
  9445. }, {
  9446. name: "offerGetAll",
  9447. args: {},
  9448. ident: "offerGetAll"
  9449. }];
  9450.  
  9451. const res = await Send({ calls });
  9452. count++;
  9453.  
  9454. if ('error' in res) {
  9455. console.error(res.error);
  9456. setProgress('Перезагрузите игру и попробуйте позже', true);
  9457. return;
  9458. }
  9459.  
  9460. const eventInfo = res.results[1].result.response.find(e => e.offerType == "bossEvent");
  9461. if (eventInfo.progress.score > 250) {
  9462. break;
  9463. }
  9464. setProgress('Количество убитых врагов: ' + eventInfo.progress.score + '<br>Использовано ' + count + ' героев');
  9465. }
  9466.  
  9467. rewardBossRatingEventSouls();
  9468. }
  9469. /** Сбор награды из Горнила Душ */
  9470. async function rewardBossRatingEventSouls() {
  9471. const data = await Send({
  9472. calls: [
  9473. { name: "offerGetAll", args: {}, ident: "offerGetAll" }
  9474. ]
  9475. });
  9476.  
  9477. const bossEventInfo = data.results[0].result.response.find(e => e.offerType == "bossEvent");
  9478. if (!bossEventInfo) {
  9479. setProgress('Эвент завершен', true);
  9480. return;
  9481. }
  9482.  
  9483. const farmedChests = bossEventInfo.progress.farmedChests;
  9484. const score = bossEventInfo.progress.score;
  9485. // setProgress('Количество убитых врагов: ' + score);
  9486. const revard = bossEventInfo.reward;
  9487. const calls = [];
  9488.  
  9489. let count = 0;
  9490. for (let i = 1; i < 10; i++) {
  9491. if (farmedChests.includes(i)) {
  9492. continue;
  9493. }
  9494. if (score < revard[i].score) {
  9495. break;
  9496. }
  9497. calls.push({
  9498. name: "bossRatingEvent_getReward",
  9499. args: {
  9500. rewardId: i
  9501. },
  9502. ident: "body_" + i
  9503. });
  9504. count++;
  9505. }
  9506. if (!count) {
  9507. setProgress('Нечего собирать', true);
  9508. return;
  9509. }
  9510.  
  9511. Send({ calls }).then(e => {
  9512. console.log(e);
  9513. setProgress('Собрано ' + e?.results?.length + ' наград', true);
  9514. })
  9515. }
  9516. /**
  9517. * Spin the Seer
  9518. *
  9519. * Покрутить провидца
  9520. */
  9521. async function rollAscension() {
  9522. const refillable = await Send({calls:[
  9523. {
  9524. name:"userGetInfo",
  9525. args:{},
  9526. ident:"userGetInfo"
  9527. }
  9528. ]}).then(e => e.results[0].result.response.refillable);
  9529. const i47 = refillable.find(i => i.id == 47);
  9530. if (i47?.amount) {
  9531. await Send({ calls: [{ name: "ascensionChest_open", args: { paid: false, amount: 1 }, ident: "body" }] });
  9532. setProgress(I18N('DONE'), true);
  9533. } else {
  9534. setProgress(I18N('NOT_ENOUGH_AP'), true);
  9535. }
  9536. }
  9537.  
  9538. /**
  9539. * Collect gifts for the New Year
  9540. *
  9541. * Собрать подарки на новый год
  9542. */
  9543. function getGiftNewYear() {
  9544. Send({ calls: [{ name: "newYearGiftGet", args: { type: 0 }, ident: "body" }] }).then(e => {
  9545. const gifts = e.results[0].result.response.gifts;
  9546. const calls = gifts.filter(e => e.opened == 0).map(e => ({
  9547. name: "newYearGiftOpen",
  9548. args: {
  9549. giftId: e.id
  9550. },
  9551. ident: `body_${e.id}`
  9552. }));
  9553. if (!calls.length) {
  9554. setProgress(I18N('NY_NO_GIFTS'), 5000);
  9555. return;
  9556. }
  9557. Send({ calls }).then(e => {
  9558. console.log(e.results)
  9559. const msg = I18N('NY_GIFTS_COLLECTED', { count: e.results.length });
  9560. console.log(msg);
  9561. setProgress(msg, 5000);
  9562. });
  9563. })
  9564. }
  9565.  
  9566. async function updateArtifacts() {
  9567. const count = +await popup.confirm(I18N('SET_NUMBER_LEVELS'), [
  9568. { msg: I18N('BTN_GO'), isInput: true, default: 10 },
  9569. { result: false, isClose: true }
  9570. ]);
  9571. if (!count) {
  9572. return;
  9573. }
  9574. const quest = new questRun;
  9575. await quest.autoInit();
  9576. const heroes = Object.values(quest.questInfo['heroGetAll']);
  9577. const inventory = quest.questInfo['inventoryGet'];
  9578. const calls = [];
  9579. for (let i = count; i > 0; i--) {
  9580. const upArtifact = quest.getUpgradeArtifact();
  9581. if (!upArtifact.heroId) {
  9582. if (await popup.confirm(I18N('POSSIBLE_IMPROVE_LEVELS', { count: calls.length }), [
  9583. { msg: I18N('YES'), result: true },
  9584. { result: false, isClose: true }
  9585. ])) {
  9586. break;
  9587. } else {
  9588. return;
  9589. }
  9590. }
  9591. const hero = heroes.find(e => e.id == upArtifact.heroId);
  9592. hero.artifacts[upArtifact.slotId].level++;
  9593. inventory[upArtifact.costCurrency][upArtifact.costId] -= upArtifact.costValue;
  9594. calls.push({
  9595. name: "heroArtifactLevelUp",
  9596. args: {
  9597. heroId: upArtifact.heroId,
  9598. slotId: upArtifact.slotId
  9599. },
  9600. ident: `heroArtifactLevelUp_${i}`
  9601. });
  9602. }
  9603.  
  9604. if (!calls.length) {
  9605. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  9606. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  9607. return;
  9608. }
  9609.  
  9610. await Send(JSON.stringify({ calls })).then(e => {
  9611. if ('error' in e) {
  9612. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  9613. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  9614. } else {
  9615. console.log(I18N('IMPROVED_LEVELS', { count: e.results.length }));
  9616. setProgress(I18N('IMPROVED_LEVELS', { count: e.results.length }), false);
  9617. }
  9618. });
  9619. }
  9620.  
  9621. window.sign = a => {
  9622. const i = this['\x78\x79\x7a'];
  9623. 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'))
  9624. }
  9625.  
  9626. async function updateSkins() {
  9627. const count = +await popup.confirm(I18N('SET_NUMBER_LEVELS'), [
  9628. { msg: I18N('BTN_GO'), isInput: true, default: 10 },
  9629. { result: false, isClose: true }
  9630. ]);
  9631. if (!count) {
  9632. return;
  9633. }
  9634.  
  9635. const quest = new questRun;
  9636. await quest.autoInit();
  9637. const heroes = Object.values(quest.questInfo['heroGetAll']);
  9638. const inventory = quest.questInfo['inventoryGet'];
  9639. const calls = [];
  9640. for (let i = count; i > 0; i--) {
  9641. const upSkin = quest.getUpgradeSkin();
  9642. if (!upSkin.heroId) {
  9643. if (await popup.confirm(I18N('POSSIBLE_IMPROVE_LEVELS', { count: calls.length }), [
  9644. { msg: I18N('YES'), result: true },
  9645. { result: false, isClose: true }
  9646. ])) {
  9647. break;
  9648. } else {
  9649. return;
  9650. }
  9651. }
  9652. const hero = heroes.find(e => e.id == upSkin.heroId);
  9653. hero.skins[upSkin.skinId]++;
  9654. inventory[upSkin.costCurrency][upSkin.costCurrencyId] -= upSkin.cost;
  9655. calls.push({
  9656. name: "heroSkinUpgrade",
  9657. args: {
  9658. heroId: upSkin.heroId,
  9659. skinId: upSkin.skinId
  9660. },
  9661. ident: `heroSkinUpgrade_${i}`
  9662. })
  9663. }
  9664.  
  9665. if (!calls.length) {
  9666. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  9667. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  9668. return;
  9669. }
  9670.  
  9671. await Send(JSON.stringify({ calls })).then(e => {
  9672. if ('error' in e) {
  9673. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  9674. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  9675. } else {
  9676. console.log(I18N('IMPROVED_LEVELS', { count: e.results.length }));
  9677. setProgress(I18N('IMPROVED_LEVELS', { count: e.results.length }), false);
  9678. }
  9679. });
  9680. }
  9681.  
  9682. function getQuestionInfo(img, nameOnly = false) {
  9683. const libHeroes = Object.values(lib.data.hero);
  9684. const parts = img.split(':');
  9685. const id = parts[1];
  9686. switch (parts[0]) {
  9687. case 'titanArtifact_id':
  9688. return cheats.translate("LIB_TITAN_ARTIFACT_NAME_" + id);
  9689. case 'titan':
  9690. return cheats.translate("LIB_HERO_NAME_" + id);
  9691. case 'skill':
  9692. return cheats.translate("LIB_SKILL_" + id);
  9693. case 'inventoryItem_gear':
  9694. return cheats.translate("LIB_GEAR_NAME_" + id);
  9695. case 'inventoryItem_coin':
  9696. return cheats.translate("LIB_COIN_NAME_" + id);
  9697. case 'artifact':
  9698. if (nameOnly) {
  9699. return cheats.translate("LIB_ARTIFACT_NAME_" + id);
  9700. }
  9701. heroes = libHeroes.filter(h => h.id < 100 && h.artifacts.includes(+id));
  9702. return {
  9703. /** Как называется этот артефакт? */
  9704. name: cheats.translate("LIB_ARTIFACT_NAME_" + id),
  9705. /** Какому герою принадлежит этот артефакт? */
  9706. heroes: heroes.map(h => cheats.translate("LIB_HERO_NAME_" + h.id))
  9707. };
  9708. case 'hero':
  9709. if (nameOnly) {
  9710. return cheats.translate("LIB_HERO_NAME_" + id);
  9711. }
  9712. artifacts = lib.data.hero[id].artifacts;
  9713. return {
  9714. /** Как зовут этого героя? */
  9715. name: cheats.translate("LIB_HERO_NAME_" + id),
  9716. /** Какой артефакт принадлежит этому герою? */
  9717. artifact: artifacts.map(a => cheats.translate("LIB_ARTIFACT_NAME_" + a))
  9718. };
  9719. }
  9720. }
  9721.  
  9722. function hintQuest(quest) {
  9723. const result = {};
  9724. if (quest?.questionIcon) {
  9725. const info = getQuestionInfo(quest.questionIcon);
  9726. if (info?.heroes) {
  9727. /** Какому герою принадлежит этот артефакт? */
  9728. result.answer = quest.answers.filter(e => info.heroes.includes(e.answerText.slice(1)));
  9729. }
  9730. if (info?.artifact) {
  9731. /** Какой артефакт принадлежит этому герою? */
  9732. result.answer = quest.answers.filter(e => info.artifact.includes(e.answerText.slice(1)));
  9733. }
  9734. if (typeof info == 'string') {
  9735. result.info = { name: info };
  9736. } else {
  9737. result.info = info;
  9738. }
  9739. }
  9740.  
  9741. if (quest.answers[0]?.answerIcon) {
  9742. result.answer = quest.answers.filter(e => quest.question.includes(getQuestionInfo(e.answerIcon, true)))
  9743. }
  9744.  
  9745. if ((!result?.answer || !result.answer.length) && !result.info?.name) {
  9746. return false;
  9747. }
  9748.  
  9749. let resultText = '';
  9750. if (result?.info) {
  9751. resultText += I18N('PICTURE') + result.info.name;
  9752. }
  9753. console.log(result);
  9754. if (result?.answer && result.answer.length) {
  9755. resultText += I18N('ANSWER') + result.answer[0].id + (!result.answer[0].answerIcon ? ' - ' + result.answer[0].answerText : '');
  9756. }
  9757.  
  9758. return resultText;
  9759. }
  9760.  
  9761. async function farmBattlePass() {
  9762. const isFarmReward = (reward) => {
  9763. return !(reward?.buff || reward?.fragmentHero || reward?.bundleHeroReward);
  9764. };
  9765.  
  9766. const battlePassProcess = (pass) => {
  9767. if (!pass.id) {return []}
  9768. const levels = Object.values(lib.data.battlePass.level).filter(x => x.battlePass == pass.id)
  9769. const last_level = levels[levels.length - 1];
  9770. let actual = Math.max(...levels.filter(p => pass.exp >= p.experience).map(p => p.level))
  9771.  
  9772. if (pass.exp > last_level.experience) {
  9773. actual = last_level.level + (pass.exp - last_level.experience) / last_level.experienceByLevel;
  9774. }
  9775. const calls = [];
  9776. for(let i = 1; i <= actual; i++) {
  9777. const level = i >= last_level.level ? last_level : levels.find(l => l.level === i);
  9778. const reward = {free: level?.freeReward, paid:level?.paidReward};
  9779.  
  9780. if (!pass.rewards[i]?.free && isFarmReward(reward.free)) {
  9781. const args = {level: i, free:true};
  9782. if (!pass.gold) { args.id = pass.id }
  9783. calls.push({ name: 'battlePass_farmReward', args, ident: `${pass.gold ? 'body' : 'spesial'}_free_${args.id}_${i}` });
  9784. }
  9785. if (pass.ticket && !pass.rewards[i]?.paid && isFarmReward(reward.paid)) {
  9786. const args = {level: i, free:false};
  9787. if (!pass.gold) { args.id = pass.id}
  9788. calls.push({ name: 'battlePass_farmReward', args, ident: `${pass.gold ? 'body' : 'spesial'}_paid_${args.id}_${i}` });
  9789. }
  9790. }
  9791. return calls;
  9792. }
  9793.  
  9794. const passes = await Send({
  9795. calls: [
  9796. { name: 'battlePass_getInfo', args: {}, ident: 'getInfo' },
  9797. { name: 'battlePass_getSpecial', args: {}, ident: 'getSpecial' },
  9798. ],
  9799. }).then((e) => [{...e.results[0].result.response?.battlePass, gold: true}, ...Object.values(e.results[1].result.response)]);
  9800.  
  9801. const calls = passes.map(p => battlePassProcess(p)).flat()
  9802.  
  9803. if (!calls.length) {
  9804. setProgress(I18N('NOTHING_TO_COLLECT'));
  9805. return;
  9806. }
  9807.  
  9808. let results = await Send({calls});
  9809. if (results.error) {
  9810. console.log(results.error);
  9811. setProgress(I18N('SOMETHING_WENT_WRONG'));
  9812. } else {
  9813. setProgress(I18N('SEASON_REWARD_COLLECTED', {count: results.results.length}), true);
  9814. }
  9815. }
  9816.  
  9817. async function sellHeroSoulsForGold() {
  9818. let { fragmentHero, heroes } = await Send({
  9819. calls: [
  9820. { name: 'inventoryGet', args: {}, ident: 'inventoryGet' },
  9821. { name: 'heroGetAll', args: {}, ident: 'heroGetAll' },
  9822. ],
  9823. })
  9824. .then((e) => e.results.map((r) => r.result.response))
  9825. .then((e) => ({ fragmentHero: e[0].fragmentHero, heroes: e[1] }));
  9826.  
  9827. const calls = [];
  9828. for (let i in fragmentHero) {
  9829. if (heroes[i] && heroes[i].star == 6) {
  9830. calls.push({
  9831. name: 'inventorySell',
  9832. args: {
  9833. type: 'hero',
  9834. libId: i,
  9835. amount: fragmentHero[i],
  9836. fragment: true,
  9837. },
  9838. ident: 'inventorySell_' + i,
  9839. });
  9840. }
  9841. }
  9842. if (!calls.length) {
  9843. console.log(0);
  9844. return 0;
  9845. }
  9846. const rewards = await Send({ calls }).then((e) => e.results.map((r) => r.result?.response?.gold || 0));
  9847. const gold = rewards.reduce((e, a) => e + a, 0);
  9848. setProgress(I18N('GOLD_RECEIVED', { gold }), true);
  9849. }
  9850.  
  9851. /**
  9852. * Attack of the minions of Asgard
  9853. *
  9854. * Атака прислужников Асгарда
  9855. */
  9856. function testRaidNodes() {
  9857. const { executeRaidNodes } = HWHClasses;
  9858. return new Promise((resolve, reject) => {
  9859. const tower = new executeRaidNodes(resolve, reject);
  9860. tower.start();
  9861. });
  9862. }
  9863.  
  9864. /**
  9865. * Attack of the minions of Asgard
  9866. *
  9867. * Атака прислужников Асгарда
  9868. */
  9869. function executeRaidNodes(resolve, reject) {
  9870. let raidData = {
  9871. teams: [],
  9872. favor: {},
  9873. nodes: [],
  9874. attempts: 0,
  9875. countExecuteBattles: 0,
  9876. cancelBattle: 0,
  9877. }
  9878.  
  9879. callsExecuteRaidNodes = {
  9880. calls: [{
  9881. name: "clanRaid_getInfo",
  9882. args: {},
  9883. ident: "clanRaid_getInfo"
  9884. }, {
  9885. name: "teamGetAll",
  9886. args: {},
  9887. ident: "teamGetAll"
  9888. }, {
  9889. name: "teamGetFavor",
  9890. args: {},
  9891. ident: "teamGetFavor"
  9892. }]
  9893. }
  9894.  
  9895. this.start = function () {
  9896. send(JSON.stringify(callsExecuteRaidNodes), startRaidNodes);
  9897. }
  9898.  
  9899. async function startRaidNodes(data) {
  9900. res = data.results;
  9901. clanRaidInfo = res[0].result.response;
  9902. teamGetAll = res[1].result.response;
  9903. teamGetFavor = res[2].result.response;
  9904.  
  9905. let index = 0;
  9906. let isNotFullPack = false;
  9907. for (let team of teamGetAll.clanRaid_nodes) {
  9908. if (team.length < 6) {
  9909. isNotFullPack = true;
  9910. }
  9911. raidData.teams.push({
  9912. data: {},
  9913. heroes: team.filter(id => id < 6000),
  9914. pet: team.filter(id => id >= 6000).pop(),
  9915. battleIndex: index++
  9916. });
  9917. }
  9918. raidData.favor = teamGetFavor.clanRaid_nodes;
  9919.  
  9920. if (isNotFullPack) {
  9921. if (await popup.confirm(I18N('MINIONS_WARNING'), [
  9922. { msg: I18N('BTN_NO'), result: true },
  9923. { msg: I18N('BTN_YES'), result: false },
  9924. ])) {
  9925. endRaidNodes('isNotFullPack');
  9926. return;
  9927. }
  9928. }
  9929.  
  9930. raidData.nodes = clanRaidInfo.nodes;
  9931. raidData.attempts = clanRaidInfo.attempts;
  9932. setIsCancalBattle(false);
  9933.  
  9934. checkNodes();
  9935. }
  9936.  
  9937. function getAttackNode() {
  9938. for (let nodeId in raidData.nodes) {
  9939. let node = raidData.nodes[nodeId];
  9940. let points = 0
  9941. for (team of node.teams) {
  9942. points += team.points;
  9943. }
  9944. let now = Date.now() / 1000;
  9945. if (!points && now > node.timestamps.start && now < node.timestamps.end) {
  9946. let countTeam = node.teams.length;
  9947. delete raidData.nodes[nodeId];
  9948. return {
  9949. nodeId,
  9950. countTeam
  9951. };
  9952. }
  9953. }
  9954. return null;
  9955. }
  9956.  
  9957. function checkNodes() {
  9958. setProgress(`${I18N('REMAINING_ATTEMPTS')}: ${raidData.attempts}`);
  9959. let nodeInfo = getAttackNode();
  9960. if (nodeInfo && raidData.attempts) {
  9961. startNodeBattles(nodeInfo);
  9962. return;
  9963. }
  9964.  
  9965. endRaidNodes('EndRaidNodes');
  9966. }
  9967.  
  9968. function startNodeBattles(nodeInfo) {
  9969. let {nodeId, countTeam} = nodeInfo;
  9970. let teams = raidData.teams.slice(0, countTeam);
  9971. let heroes = raidData.teams.map(e => e.heroes).flat();
  9972. let favor = {...raidData.favor};
  9973. for (let heroId in favor) {
  9974. if (!heroes.includes(+heroId)) {
  9975. delete favor[heroId];
  9976. }
  9977. }
  9978.  
  9979. let calls = [{
  9980. name: "clanRaid_startNodeBattles",
  9981. args: {
  9982. nodeId,
  9983. teams,
  9984. favor
  9985. },
  9986. ident: "body"
  9987. }];
  9988.  
  9989. send(JSON.stringify({calls}), resultNodeBattles);
  9990. }
  9991.  
  9992. function resultNodeBattles(e) {
  9993. if (e['error']) {
  9994. endRaidNodes('nodeBattlesError', e['error']);
  9995. return;
  9996. }
  9997.  
  9998. console.log(e);
  9999. let battles = e.results[0].result.response.battles;
  10000. let promises = [];
  10001. let battleIndex = 0;
  10002. for (let battle of battles) {
  10003. battle.battleIndex = battleIndex++;
  10004. promises.push(calcBattleResult(battle));
  10005. }
  10006.  
  10007. Promise.all(promises)
  10008. .then(results => {
  10009. const endResults = {};
  10010. let isAllWin = true;
  10011. for (let r of results) {
  10012. isAllWin &&= r.result.win;
  10013. }
  10014. if (!isAllWin) {
  10015. cancelEndNodeBattle(results[0]);
  10016. return;
  10017. }
  10018. raidData.countExecuteBattles = results.length;
  10019. let timeout = 500;
  10020. for (let r of results) {
  10021. setTimeout(endNodeBattle, timeout, r);
  10022. timeout += 500;
  10023. }
  10024. });
  10025. }
  10026. /**
  10027. * Returns the battle calculation promise
  10028. *
  10029. * Возвращает промис расчета боя
  10030. */
  10031. function calcBattleResult(battleData) {
  10032. return new Promise(function (resolve, reject) {
  10033. BattleCalc(battleData, "get_clanPvp", resolve);
  10034. });
  10035. }
  10036. /**
  10037. * Cancels the fight
  10038. *
  10039. * Отменяет бой
  10040. */
  10041. function cancelEndNodeBattle(r) {
  10042. const fixBattle = function (heroes) {
  10043. for (const ids in heroes) {
  10044. hero = heroes[ids];
  10045. hero.energy = random(1, 999);
  10046. if (hero.hp > 0) {
  10047. hero.hp = random(1, hero.hp);
  10048. }
  10049. }
  10050. }
  10051. fixBattle(r.progress[0].attackers.heroes);
  10052. fixBattle(r.progress[0].defenders.heroes);
  10053. endNodeBattle(r);
  10054. }
  10055. /**
  10056. * Ends the fight
  10057. *
  10058. * Завершает бой
  10059. */
  10060. function endNodeBattle(r) {
  10061. let nodeId = r.battleData.result.nodeId;
  10062. let battleIndex = r.battleData.battleIndex;
  10063. let calls = [{
  10064. name: "clanRaid_endNodeBattle",
  10065. args: {
  10066. nodeId,
  10067. battleIndex,
  10068. result: r.result,
  10069. progress: r.progress
  10070. },
  10071. ident: "body"
  10072. }]
  10073.  
  10074. SendRequest(JSON.stringify({calls}), battleResult);
  10075. }
  10076. /**
  10077. * Processing the results of the battle
  10078. *
  10079. * Обработка результатов боя
  10080. */
  10081. function battleResult(e) {
  10082. if (e['error']) {
  10083. endRaidNodes('missionEndError', e['error']);
  10084. return;
  10085. }
  10086. r = e.results[0].result.response;
  10087. if (r['error']) {
  10088. if (r.reason == "invalidBattle") {
  10089. raidData.cancelBattle++;
  10090. checkNodes();
  10091. } else {
  10092. endRaidNodes('missionEndError', e['error']);
  10093. }
  10094. return;
  10095. }
  10096.  
  10097. if (!(--raidData.countExecuteBattles)) {
  10098. raidData.attempts--;
  10099. checkNodes();
  10100. }
  10101. }
  10102. /**
  10103. * Completing a task
  10104. *
  10105. * Завершение задачи
  10106. */
  10107. function endRaidNodes(reason, info) {
  10108. setIsCancalBattle(true);
  10109. let textCancel = raidData.cancelBattle ? ` ${I18N('BATTLES_CANCELED')}: ${raidData.cancelBattle}` : '';
  10110. setProgress(`${I18N('MINION_RAID')} ${I18N('COMPLETED')}! ${textCancel}`, true);
  10111. console.log(reason, info);
  10112. resolve();
  10113. }
  10114. }
  10115.  
  10116. this.HWHClasses.executeRaidNodes = executeRaidNodes;
  10117.  
  10118. /**
  10119. * Asgard Boss Attack Replay
  10120. *
  10121. * Повтор атаки босса Асгарда
  10122. */
  10123. function testBossBattle() {
  10124. const { executeBossBattle } = HWHClasses;
  10125. return new Promise((resolve, reject) => {
  10126. const bossBattle = new executeBossBattle(resolve, reject);
  10127. bossBattle.start(lastBossBattle);
  10128. });
  10129. }
  10130.  
  10131. /**
  10132. * Asgard Boss Attack Replay
  10133. *
  10134. * Повтор атаки босса Асгарда
  10135. */
  10136. function executeBossBattle(resolve, reject) {
  10137.  
  10138. this.start = function (battleInfo) {
  10139. preCalcBattle(battleInfo);
  10140. }
  10141.  
  10142. function getBattleInfo(battle) {
  10143. return new Promise(function (resolve) {
  10144. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  10145. BattleCalc(battle, getBattleType(battle.type), e => {
  10146. let extra = e.progress[0].defenders.heroes[1].extra;
  10147. resolve(extra.damageTaken + extra.damageTakenNextLevel);
  10148. });
  10149. });
  10150. }
  10151.  
  10152. function preCalcBattle(battle) {
  10153. let actions = [];
  10154. const countTestBattle = getInput('countTestBattle');
  10155. for (let i = 0; i < countTestBattle; i++) {
  10156. actions.push(getBattleInfo(battle, true));
  10157. }
  10158. Promise.all(actions)
  10159. .then(resultPreCalcBattle);
  10160. }
  10161.  
  10162. async function resultPreCalcBattle(damages) {
  10163. let maxDamage = 0;
  10164. let minDamage = 1e10;
  10165. let avgDamage = 0;
  10166. for (let damage of damages) {
  10167. avgDamage += damage
  10168. if (damage > maxDamage) {
  10169. maxDamage = damage;
  10170. }
  10171. if (damage < minDamage) {
  10172. minDamage = damage;
  10173. }
  10174. }
  10175. avgDamage /= damages.length;
  10176. console.log(damages.map(e => e.toLocaleString()).join('\n'), avgDamage, maxDamage);
  10177.  
  10178. await popup.confirm(
  10179. `${I18N('ROUND_STAT')} ${damages.length} ${I18N('BATTLE')}:` +
  10180. `<br>${I18N('MINIMUM')}: ` + minDamage.toLocaleString() +
  10181. `<br>${I18N('MAXIMUM')}: ` + maxDamage.toLocaleString() +
  10182. `<br>${I18N('AVERAGE')}: ` + avgDamage.toLocaleString()
  10183. , [
  10184. { msg: I18N('BTN_OK'), result: 0},
  10185. ])
  10186. endBossBattle(I18N('BTN_CANCEL'));
  10187. }
  10188.  
  10189. /**
  10190. * Completing a task
  10191. *
  10192. * Завершение задачи
  10193. */
  10194. function endBossBattle(reason, info) {
  10195. console.log(reason, info);
  10196. resolve();
  10197. }
  10198. }
  10199.  
  10200. this.HWHClasses.executeBossBattle = executeBossBattle;
  10201.  
  10202. class FixBattle {
  10203. minTimer = 1.3;
  10204. maxTimer = 15.3;
  10205.  
  10206. constructor(battle, isTimeout = true) {
  10207. this.battle = structuredClone(battle);
  10208. this.isTimeout = isTimeout;
  10209. }
  10210.  
  10211. timeout(callback, timeout) {
  10212. if (this.isTimeout) {
  10213. this.worker.postMessage(timeout);
  10214. this.worker.onmessage = callback;
  10215. } else {
  10216. callback();
  10217. }
  10218. }
  10219.  
  10220. randTimer() {
  10221. return Math.random() * (this.maxTimer - this.minTimer + 1) + this.minTimer;
  10222. }
  10223.  
  10224. setAvgTime(startTime) {
  10225. this.fixTime += Date.now() - startTime;
  10226. this.avgTime = this.fixTime / this.count;
  10227. }
  10228.  
  10229. init() {
  10230. this.fixTime = 0;
  10231. this.lastTimer = 0;
  10232. this.index = 0;
  10233. this.lastBossDamage = 0;
  10234. this.bestResult = {
  10235. count: 0,
  10236. timer: 0,
  10237. value: 0,
  10238. result: null,
  10239. progress: null,
  10240. };
  10241. this.lastBattleResult = {
  10242. win: false,
  10243. };
  10244. this.worker = new Worker(
  10245. URL.createObjectURL(
  10246. new Blob([
  10247. `self.onmessage = function(e) {
  10248. const timeout = e.data;
  10249. setTimeout(() => {
  10250. self.postMessage(1);
  10251. }, timeout);
  10252. };`,
  10253. ])
  10254. )
  10255. );
  10256. }
  10257.  
  10258. async start(endTime = Date.now() + 6e4, maxCount = 100) {
  10259. this.endTime = endTime;
  10260. this.maxCount = maxCount;
  10261. this.init();
  10262. return await new Promise((resolve) => {
  10263. this.resolve = resolve;
  10264. this.count = 0;
  10265. this.loop();
  10266. });
  10267. }
  10268.  
  10269. endFix() {
  10270. this.bestResult.maxCount = this.count;
  10271. this.worker.terminate();
  10272. this.resolve(this.bestResult);
  10273. }
  10274.  
  10275. async loop() {
  10276. const start = Date.now();
  10277. if (this.isEndLoop()) {
  10278. this.endFix();
  10279. return;
  10280. }
  10281. this.count++;
  10282. try {
  10283. this.lastResult = await Calc(this.battle);
  10284. } catch (e) {
  10285. this.updateProgressTimer(this.index++);
  10286. this.timeout(this.loop.bind(this), 0);
  10287. return;
  10288. }
  10289. const { progress, result } = this.lastResult;
  10290. this.lastBattleResult = result;
  10291. this.lastBattleProgress = progress;
  10292. this.setAvgTime(start);
  10293. this.checkResult();
  10294. this.showResult();
  10295. this.updateProgressTimer();
  10296. this.timeout(this.loop.bind(this), 0);
  10297. }
  10298.  
  10299. isEndLoop() {
  10300. return this.count >= this.maxCount || this.endTime < Date.now();
  10301. }
  10302.  
  10303. updateProgressTimer(index = 0) {
  10304. this.lastTimer = this.randTimer();
  10305. this.battle.progress = [{ attackers: { input: ['auto', 0, 0, 'auto', index, this.lastTimer] } }];
  10306. }
  10307.  
  10308. showResult() {
  10309. console.log(
  10310. this.count,
  10311. this.avgTime.toFixed(2),
  10312. (this.endTime - Date.now()) / 1000,
  10313. this.lastTimer.toFixed(2),
  10314. this.lastBossDamage.toLocaleString(),
  10315. this.bestResult.value.toLocaleString()
  10316. );
  10317. }
  10318.  
  10319. checkResult() {
  10320. const { damageTaken, damageTakenNextLevel } = this.lastBattleProgress[0].defenders.heroes[1].extra;
  10321. this.lastBossDamage = damageTaken + damageTakenNextLevel;
  10322. if (this.lastBossDamage > this.bestResult.value) {
  10323. this.bestResult = {
  10324. count: this.count,
  10325. timer: this.lastTimer,
  10326. value: this.lastBossDamage,
  10327. result: structuredClone(this.lastBattleResult),
  10328. progress: structuredClone(this.lastBattleProgress),
  10329. };
  10330. }
  10331. }
  10332.  
  10333. stopFix() {
  10334. this.endTime = 0;
  10335. }
  10336. }
  10337.  
  10338. this.HWHClasses.FixBattle = FixBattle;
  10339.  
  10340. class WinFixBattle extends FixBattle {
  10341. checkResult() {
  10342. if (this.lastBattleResult.win) {
  10343. this.bestResult = {
  10344. count: this.count,
  10345. timer: this.lastTimer,
  10346. value: this.lastBattleResult.stars,
  10347. result: structuredClone(this.lastBattleResult),
  10348. progress: structuredClone(this.lastBattleProgress),
  10349. battleTimer: this.lastResult.battleTimer,
  10350. };
  10351. }
  10352. }
  10353.  
  10354. setWinTimer(value) {
  10355. this.winTimer = value;
  10356. }
  10357.  
  10358. setMaxTimer(value) {
  10359. this.maxTimer = value;
  10360. }
  10361.  
  10362. randTimer() {
  10363. if (this.winTimer) {
  10364. return this.winTimer;
  10365. }
  10366. return super.randTimer();
  10367. }
  10368.  
  10369. isEndLoop() {
  10370. return super.isEndLoop() || this.bestResult.result?.win;
  10371. }
  10372.  
  10373. showResult() {
  10374. console.log(
  10375. this.count,
  10376. this.avgTime.toFixed(2),
  10377. (this.endTime - Date.now()) / 1000,
  10378. this.lastResult.battleTime,
  10379. this.lastTimer,
  10380. this.bestResult.value
  10381. );
  10382. const endTime = ((this.endTime - Date.now()) / 1000).toFixed(2);
  10383. const avgTime = this.avgTime.toFixed(2);
  10384. const msg = `${I18N('LETS_FIX')} ${this.count}/${this.maxCount}<br/>${endTime}s<br/>${avgTime}ms`;
  10385. setProgress(msg, false, this.stopFix.bind(this));
  10386. }
  10387. }
  10388.  
  10389. this.HWHClasses.WinFixBattle = WinFixBattle;
  10390.  
  10391. class BestOrWinFixBattle extends WinFixBattle {
  10392. isNoMakeWin = false;
  10393.  
  10394. getState(result) {
  10395. let beforeSumFactor = 0;
  10396. const beforeHeroes = result.battleData.defenders[0];
  10397. for (let heroId in beforeHeroes) {
  10398. const hero = beforeHeroes[heroId];
  10399. const state = hero.state;
  10400. let factor = 1;
  10401. if (state) {
  10402. const hp = state.hp / (hero?.hp || 1);
  10403. const energy = state.energy / 1e3;
  10404. factor = hp + energy / 20;
  10405. }
  10406. beforeSumFactor += factor;
  10407. }
  10408.  
  10409. let afterSumFactor = 0;
  10410. const afterHeroes = result.progress[0].defenders.heroes;
  10411. for (let heroId in afterHeroes) {
  10412. const hero = afterHeroes[heroId];
  10413. const hp = hero.hp / (beforeHeroes[heroId]?.hp || 1);
  10414. const energy = hero.energy / 1e3;
  10415. const factor = hp + energy / 20;
  10416. afterSumFactor += factor;
  10417. }
  10418. return 100 - Math.floor((afterSumFactor / beforeSumFactor) * 1e4) / 100;
  10419. }
  10420.  
  10421. setNoMakeWin(value) {
  10422. this.isNoMakeWin = value;
  10423. }
  10424.  
  10425. checkResult() {
  10426. const state = this.getState(this.lastResult);
  10427. console.log(state);
  10428.  
  10429. if (state > this.bestResult.value) {
  10430. if (!(this.isNoMakeWin && this.lastBattleResult.win)) {
  10431. this.bestResult = {
  10432. count: this.count,
  10433. timer: this.lastTimer,
  10434. value: state,
  10435. result: structuredClone(this.lastBattleResult),
  10436. progress: structuredClone(this.lastBattleProgress),
  10437. battleTimer: this.lastResult.battleTimer,
  10438. };
  10439. }
  10440. }
  10441. }
  10442. }
  10443.  
  10444. this.HWHClasses.BestOrWinFixBattle = BestOrWinFixBattle;
  10445.  
  10446. class BossFixBattle extends FixBattle {
  10447. showResult() {
  10448. super.showResult();
  10449. //setTimeout(() => {
  10450. const best = this.bestResult;
  10451. const maxDmg = best.value.toLocaleString();
  10452. const avgTime = this.avgTime.toLocaleString();
  10453. const msg = `${I18N('LETS_FIX')} ${this.count}/${this.maxCount}<br/>${maxDmg}<br/>${avgTime}ms`;
  10454. setProgress(msg, false, this.stopFix.bind(this));
  10455. //}, 0);
  10456. }
  10457. }
  10458.  
  10459. this.HWHClasses.BossFixBattle = BossFixBattle;
  10460.  
  10461. class DungeonFixBattle extends FixBattle {
  10462. init() {
  10463. super.init();
  10464. this.isTimeout = false;
  10465. this.bestResult = {
  10466. count: 0,
  10467. timer: 0,
  10468. value: {
  10469. hp: -Infinity,
  10470. energy: -Infinity,
  10471. },
  10472. result: null,
  10473. progress: null,
  10474. };
  10475. }
  10476.  
  10477. setState() {
  10478. const result = this.lastResult;
  10479. let beforeHP = 0;
  10480. let beforeEnergy = 0;
  10481. const beforeTitans = result.battleData.attackers;
  10482. for (let titanId in beforeTitans) {
  10483. const titan = beforeTitans[titanId];
  10484. const state = titan.state;
  10485. if (state) {
  10486. beforeHP += state.hp / titan.hp;
  10487. beforeEnergy += state.energy / 1e3;
  10488. }
  10489. }
  10490.  
  10491. let afterHP = 0;
  10492. let afterEnergy = 0;
  10493. const afterTitans = result.progress[0].attackers.heroes;
  10494. for (let titanId in afterTitans) {
  10495. const titan = afterTitans[titanId];
  10496. afterHP += titan.hp / beforeTitans[titanId].hp;
  10497. afterEnergy += titan.energy / 1e3;
  10498. }
  10499.  
  10500. this.lastState = {
  10501. hp: afterHP - beforeHP,
  10502. energy: afterEnergy - beforeEnergy,
  10503. };
  10504. }
  10505.  
  10506. checkResult() {
  10507. this.setState();
  10508. if (
  10509. this.lastState.hp > this.bestResult.value.hp ||
  10510. (this.lastState.hp === this.bestResult.value.hp && this.lastState.energy > this.bestResult.value.energy)
  10511. ) {
  10512. this.bestResult = {
  10513. count: this.count,
  10514. timer: this.lastTimer,
  10515. value: this.lastState,
  10516. result: this.lastResult.result,
  10517. progress: this.lastResult.progress,
  10518. };
  10519. }
  10520. }
  10521.  
  10522. showResult() {
  10523. if (this.isShowResult) {
  10524. console.log(this.count, this.lastTimer.toFixed(2), JSON.stringify(this.lastState), JSON.stringify(this.bestResult.value));
  10525. }
  10526. }
  10527. }
  10528.  
  10529. this.HWHClasses.DungeonFixBattle = DungeonFixBattle;
  10530.  
  10531. const masterWsMixin = {
  10532. wsStart() {
  10533. const socket = new WebSocket(this.url);
  10534.  
  10535. socket.onopen = () => {
  10536. console.log('Connected to server');
  10537.  
  10538. // Пример создания новой задачи
  10539. const newTask = {
  10540. type: 'newTask',
  10541. battle: this.battle,
  10542. endTime: this.endTime - 1e4,
  10543. maxCount: this.maxCount,
  10544. };
  10545. socket.send(JSON.stringify(newTask));
  10546. };
  10547.  
  10548. socket.onmessage = this.onmessage.bind(this);
  10549.  
  10550. socket.onclose = () => {
  10551. console.log('Disconnected from server');
  10552. };
  10553.  
  10554. this.ws = socket;
  10555. },
  10556.  
  10557. onmessage(event) {
  10558. const data = JSON.parse(event.data);
  10559. switch (data.type) {
  10560. case 'newTask': {
  10561. console.log('newTask:', data);
  10562. this.id = data.id;
  10563. this.countExecutor = data.count;
  10564. break;
  10565. }
  10566. case 'getSolTask': {
  10567. console.log('getSolTask:', data);
  10568. this.endFix(data.solutions);
  10569. break;
  10570. }
  10571. case 'resolveTask': {
  10572. console.log('resolveTask:', data);
  10573. if (data.id === this.id && data.solutions.length === this.countExecutor) {
  10574. this.worker.terminate();
  10575. this.endFix(data.solutions);
  10576. }
  10577. break;
  10578. }
  10579. default:
  10580. console.log('Unknown message type:', data.type);
  10581. }
  10582. },
  10583.  
  10584. getTask() {
  10585. this.ws.send(
  10586. JSON.stringify({
  10587. type: 'getSolTask',
  10588. id: this.id,
  10589. })
  10590. );
  10591. },
  10592. };
  10593.  
  10594. /*
  10595. mFix = new action.masterFixBattle(battle)
  10596. await mFix.start(Date.now() + 6e4, 1);
  10597. */
  10598. class masterFixBattle extends FixBattle {
  10599. constructor(battle, url = 'wss://localho.st:3000') {
  10600. super(battle, true);
  10601. this.url = url;
  10602. }
  10603.  
  10604. async start(endTime, maxCount) {
  10605. this.endTime = endTime;
  10606. this.maxCount = maxCount;
  10607. this.init();
  10608. this.wsStart();
  10609. return await new Promise((resolve) => {
  10610. this.resolve = resolve;
  10611. const timeout = this.endTime - Date.now();
  10612. this.timeout(this.getTask.bind(this), timeout);
  10613. });
  10614. }
  10615.  
  10616. async endFix(solutions) {
  10617. this.ws.close();
  10618. let maxCount = 0;
  10619. for (const solution of solutions) {
  10620. maxCount += solution.maxCount;
  10621. if (solution.value > this.bestResult.value) {
  10622. this.bestResult = solution;
  10623. }
  10624. }
  10625. this.count = maxCount;
  10626. super.endFix();
  10627. }
  10628. }
  10629.  
  10630. Object.assign(masterFixBattle.prototype, masterWsMixin);
  10631.  
  10632. this.HWHClasses.masterFixBattle = masterFixBattle;
  10633.  
  10634. class masterWinFixBattle extends WinFixBattle {
  10635. constructor(battle, url = 'wss://localho.st:3000') {
  10636. super(battle, true);
  10637. this.url = url;
  10638. }
  10639.  
  10640. async start(endTime, maxCount) {
  10641. this.endTime = endTime;
  10642. this.maxCount = maxCount;
  10643. this.init();
  10644. this.wsStart();
  10645. return await new Promise((resolve) => {
  10646. this.resolve = resolve;
  10647. const timeout = this.endTime - Date.now();
  10648. this.timeout(this.getTask.bind(this), timeout);
  10649. });
  10650. }
  10651.  
  10652. async endFix(solutions) {
  10653. this.ws.close();
  10654. let maxCount = 0;
  10655. for (const solution of solutions) {
  10656. maxCount += solution.maxCount;
  10657. if (solution.value > this.bestResult.value) {
  10658. this.bestResult = solution;
  10659. }
  10660. }
  10661. this.count = maxCount;
  10662. super.endFix();
  10663. }
  10664. }
  10665.  
  10666. Object.assign(masterWinFixBattle.prototype, masterWsMixin);
  10667.  
  10668. this.HWHClasses.masterWinFixBattle = masterWinFixBattle;
  10669.  
  10670. const slaveWsMixin = {
  10671. wsStop() {
  10672. this.ws.close();
  10673. },
  10674.  
  10675. wsStart() {
  10676. const socket = new WebSocket(this.url);
  10677.  
  10678. socket.onopen = () => {
  10679. console.log('Connected to server');
  10680. };
  10681. socket.onmessage = this.onmessage.bind(this);
  10682. socket.onclose = () => {
  10683. console.log('Disconnected from server');
  10684. };
  10685.  
  10686. this.ws = socket;
  10687. },
  10688.  
  10689. async onmessage(event) {
  10690. const data = JSON.parse(event.data);
  10691. switch (data.type) {
  10692. case 'newTask': {
  10693. console.log('newTask:', data.task);
  10694. const { battle, endTime, maxCount } = data.task;
  10695. this.battle = battle;
  10696. const id = data.task.id;
  10697. const solution = await this.start(endTime, maxCount);
  10698. this.ws.send(
  10699. JSON.stringify({
  10700. type: 'resolveTask',
  10701. id,
  10702. solution,
  10703. })
  10704. );
  10705. break;
  10706. }
  10707. default:
  10708. console.log('Unknown message type:', data.type);
  10709. }
  10710. },
  10711. };
  10712. /*
  10713. sFix = new action.slaveFixBattle();
  10714. sFix.wsStart()
  10715. */
  10716. class slaveFixBattle extends FixBattle {
  10717. constructor(url = 'wss://localho.st:3000') {
  10718. super(null, false);
  10719. this.isTimeout = false;
  10720. this.url = url;
  10721. }
  10722. }
  10723.  
  10724. Object.assign(slaveFixBattle.prototype, slaveWsMixin);
  10725.  
  10726. this.HWHClasses.slaveFixBattle = slaveFixBattle;
  10727.  
  10728. class slaveWinFixBattle extends WinFixBattle {
  10729. constructor(url = 'wss://localho.st:3000') {
  10730. super(null, false);
  10731. this.isTimeout = false;
  10732. this.url = url;
  10733. }
  10734. }
  10735.  
  10736. Object.assign(slaveWinFixBattle.prototype, slaveWsMixin);
  10737.  
  10738. this.HWHClasses.slaveWinFixBattle = slaveWinFixBattle;
  10739. /**
  10740. * Auto-repeat attack
  10741. *
  10742. * Автоповтор атаки
  10743. */
  10744. function testAutoBattle() {
  10745. const { executeAutoBattle } = HWHClasses;
  10746. return new Promise((resolve, reject) => {
  10747. const bossBattle = new executeAutoBattle(resolve, reject);
  10748. bossBattle.start(lastBattleArg, lastBattleInfo);
  10749. });
  10750. }
  10751.  
  10752. /**
  10753. * Auto-repeat attack
  10754. *
  10755. * Автоповтор атаки
  10756. */
  10757. function executeAutoBattle(resolve, reject) {
  10758. let battleArg = {};
  10759. let countBattle = 0;
  10760. let countError = 0;
  10761. let findCoeff = 0;
  10762. let dataNotEeceived = 0;
  10763. let stopAutoBattle = false;
  10764.  
  10765. let isSetWinTimer = false;
  10766. 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>';
  10767. 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>';
  10768. 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>';
  10769.  
  10770. this.start = function (battleArgs, battleInfo) {
  10771. battleArg = battleArgs;
  10772. if (nameFuncStartBattle == 'invasion_bossStart') {
  10773. startBattle();
  10774. return;
  10775. }
  10776. preCalcBattle(battleInfo);
  10777. }
  10778. /**
  10779. * Returns a promise for combat recalculation
  10780. *
  10781. * Возвращает промис для прерасчета боя
  10782. */
  10783. function getBattleInfo(battle) {
  10784. return new Promise(function (resolve) {
  10785. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  10786. Calc(battle).then(e => {
  10787. e.coeff = calcCoeff(e, 'defenders');
  10788. resolve(e);
  10789. });
  10790. });
  10791. }
  10792. /**
  10793. * Battle recalculation
  10794. *
  10795. * Прерасчет боя
  10796. */
  10797. function preCalcBattle(battle) {
  10798. let actions = [];
  10799. const countTestBattle = getInput('countTestBattle');
  10800. for (let i = 0; i < countTestBattle; i++) {
  10801. actions.push(getBattleInfo(battle));
  10802. }
  10803. Promise.all(actions)
  10804. .then(resultPreCalcBattle);
  10805. }
  10806. /**
  10807. * Processing the results of the battle recalculation
  10808. *
  10809. * Обработка результатов прерасчета боя
  10810. */
  10811. async function resultPreCalcBattle(results) {
  10812. let countWin = results.reduce((s, w) => w.result.win + s, 0);
  10813. setProgress(`${I18N('CHANCE_TO_WIN')} ${Math.floor(countWin / results.length * 100)}% (${results.length})`, false, hideProgress);
  10814. if (countWin > 0) {
  10815. setIsCancalBattle(false);
  10816. startBattle();
  10817. return;
  10818. }
  10819.  
  10820. let minCoeff = 100;
  10821. let maxCoeff = -100;
  10822. let avgCoeff = 0;
  10823. results.forEach(e => {
  10824. if (e.coeff < minCoeff) minCoeff = e.coeff;
  10825. if (e.coeff > maxCoeff) maxCoeff = e.coeff;
  10826. avgCoeff += e.coeff;
  10827. });
  10828. avgCoeff /= results.length;
  10829.  
  10830. if (nameFuncStartBattle == 'invasion_bossStart' ||
  10831. nameFuncStartBattle == 'bossAttack') {
  10832. const result = await popup.confirm(
  10833. I18N('BOSS_VICTORY_IMPOSSIBLE', { battles: results.length }), [
  10834. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  10835. { msg: I18N('BTN_DO_IT'), result: true },
  10836. ])
  10837. if (result) {
  10838. setIsCancalBattle(false);
  10839. startBattle();
  10840. return;
  10841. }
  10842. setProgress(I18N('NOT_THIS_TIME'), true);
  10843. endAutoBattle('invasion_bossStart');
  10844. return;
  10845. }
  10846.  
  10847. const result = await popup.confirm(
  10848. I18N('VICTORY_IMPOSSIBLE') +
  10849. `<br>${I18N('ROUND_STAT')} ${results.length} ${I18N('BATTLE')}:` +
  10850. `<br>${I18N('MINIMUM')}: ` + minCoeff.toLocaleString() +
  10851. `<br>${I18N('MAXIMUM')}: ` + maxCoeff.toLocaleString() +
  10852. `<br>${I18N('AVERAGE')}: ` + avgCoeff.toLocaleString() +
  10853. `<br>${I18N('FIND_COEFF')} ` + avgCoeff.toLocaleString(), [
  10854. { msg: I18N('BTN_CANCEL'), result: 0, isCancel: true },
  10855. { msg: I18N('BTN_GO'), isInput: true, default: Math.round(avgCoeff * 1000) / 1000 },
  10856. ])
  10857. if (result) {
  10858. findCoeff = result;
  10859. setIsCancalBattle(false);
  10860. startBattle();
  10861. return;
  10862. }
  10863. setProgress(I18N('NOT_THIS_TIME'), true);
  10864. endAutoBattle(I18N('NOT_THIS_TIME'));
  10865. }
  10866.  
  10867. /**
  10868. * Calculation of the combat result coefficient
  10869. *
  10870. * Расчет коэфициента результата боя
  10871. */
  10872. function calcCoeff(result, packType) {
  10873. let beforeSumFactor = 0;
  10874. const beforePack = result.battleData[packType][0];
  10875. for (let heroId in beforePack) {
  10876. const hero = beforePack[heroId];
  10877. const state = hero.state;
  10878. let factor = 1;
  10879. if (state) {
  10880. const hp = state.hp / state.maxHp;
  10881. const energy = state.energy / 1e3;
  10882. factor = hp + energy / 20;
  10883. }
  10884. beforeSumFactor += factor;
  10885. }
  10886.  
  10887. let afterSumFactor = 0;
  10888. const afterPack = result.progress[0][packType].heroes;
  10889. for (let heroId in afterPack) {
  10890. const hero = afterPack[heroId];
  10891. const stateHp = beforePack[heroId]?.state?.hp || beforePack[heroId]?.stats?.hp;
  10892. const hp = hero.hp / stateHp;
  10893. const energy = hero.energy / 1e3;
  10894. const factor = hp + energy / 20;
  10895. afterSumFactor += factor;
  10896. }
  10897. const resultCoeff = -(afterSumFactor - beforeSumFactor);
  10898. return Math.round(resultCoeff * 1000) / 1000;
  10899. }
  10900. /**
  10901. * Start battle
  10902. *
  10903. * Начало боя
  10904. */
  10905. function startBattle() {
  10906. countBattle++;
  10907. const countMaxBattle = getInput('countAutoBattle');
  10908. // setProgress(countBattle + '/' + countMaxBattle);
  10909. if (countBattle > countMaxBattle) {
  10910. setProgress(`${I18N('RETRY_LIMIT_EXCEEDED')}: ${countMaxBattle}`, true);
  10911. endAutoBattle(`${I18N('RETRY_LIMIT_EXCEEDED')}: ${countMaxBattle}`)
  10912. return;
  10913. }
  10914. if (stopAutoBattle) {
  10915. setProgress(I18N('STOPPED'), true);
  10916. endAutoBattle('STOPPED');
  10917. return;
  10918. }
  10919. send({calls: [{
  10920. name: nameFuncStartBattle,
  10921. args: battleArg,
  10922. ident: "body"
  10923. }]}, calcResultBattle);
  10924. }
  10925. /**
  10926. * Battle calculation
  10927. *
  10928. * Расчет боя
  10929. */
  10930. async function calcResultBattle(e) {
  10931. if (!e) {
  10932. console.log('данные не были получены');
  10933. if (dataNotEeceived < 10) {
  10934. dataNotEeceived++;
  10935. startBattle();
  10936. return;
  10937. }
  10938. endAutoBattle('Error', 'данные не были получены ' + dataNotEeceived + ' раз');
  10939. return;
  10940. }
  10941. if ('error' in e) {
  10942. if (e.error.description === 'too many tries') {
  10943. invasionTimer += 100;
  10944. countBattle--;
  10945. countError++;
  10946. console.log(`Errors: ${countError}`, e.error);
  10947. startBattle();
  10948. return;
  10949. }
  10950. const result = await popup.confirm(I18N('ERROR_DURING_THE_BATTLE') + '<br>' + e.error.description, [
  10951. { msg: I18N('BTN_OK'), result: false },
  10952. { msg: I18N('RELOAD_GAME'), result: true },
  10953. ]);
  10954. endAutoBattle('Error', e.error);
  10955. if (result) {
  10956. location.reload();
  10957. }
  10958. return;
  10959. }
  10960. let battle = e.results[0].result.response.battle
  10961. if (nameFuncStartBattle == 'towerStartBattle' ||
  10962. nameFuncStartBattle == 'bossAttack' ||
  10963. nameFuncStartBattle == 'invasion_bossStart') {
  10964. battle = e.results[0].result.response;
  10965. }
  10966. lastBattleInfo = battle;
  10967. BattleCalc(battle, getBattleType(battle.type), resultBattle);
  10968. }
  10969. /**
  10970. * Processing the results of the battle
  10971. *
  10972. * Обработка результатов боя
  10973. */
  10974. async function resultBattle(e) {
  10975. const isWin = e.result.win;
  10976. if (isWin) {
  10977. endBattle(e, false);
  10978. return;
  10979. } else if (isChecked('tryFixIt_v2')) {
  10980. const { WinFixBattle } = HWHClasses;
  10981. const cloneBattle = structuredClone(e.battleData);
  10982. const bFix = new WinFixBattle(cloneBattle);
  10983. let attempts = Infinity;
  10984. if (nameFuncStartBattle == 'invasion_bossStart' && !isSetWinTimer) {
  10985. let winTimer = await popup.confirm(`Secret number:`, [
  10986. { result: false, isClose: true },
  10987. { msg: 'Go', isInput: true, default: '0' },
  10988. ]);
  10989. winTimer = Number.parseFloat(winTimer);
  10990. if (winTimer) {
  10991. attempts = 5;
  10992. bFix.setWinTimer(winTimer);
  10993. }
  10994. isSetWinTimer = true;
  10995. }
  10996. let endTime = Date.now() + 6e4;
  10997. if (nameFuncStartBattle == 'invasion_bossStart') {
  10998. endTime = Date.now() + 6e4 * 4;
  10999. bFix.setMaxTimer(120.3);
  11000. }
  11001. const result = await bFix.start(endTime, attempts);
  11002. console.log(result);
  11003. if (result.value) {
  11004. endBattle(result, false);
  11005. return;
  11006. }
  11007. }
  11008. const countMaxBattle = getInput('countAutoBattle');
  11009. if (findCoeff) {
  11010. const coeff = calcCoeff(e, 'defenders');
  11011. setProgress(`${countBattle}/${countMaxBattle}, ${coeff}`);
  11012. if (coeff > findCoeff) {
  11013. endBattle(e, false);
  11014. return;
  11015. }
  11016. } else {
  11017. if (nameFuncStartBattle == 'invasion_bossStart') {
  11018. const bossLvl = lastBattleInfo.typeId >= 130 ? lastBattleInfo.typeId : '';
  11019. const justice = lastBattleInfo?.effects?.attackers?.percentInOutDamageModAndEnergyIncrease_any_99_100_300_99_1000_300 || 0;
  11020. setProgress(`${svgBoss} ${bossLvl} ${svgJustice} ${justice} <br>${svgAttempt} ${countBattle}/${countMaxBattle}`, false, () => {
  11021. stopAutoBattle = true;
  11022. });
  11023. await new Promise((resolve) => setTimeout(resolve, 5000));
  11024. } else {
  11025. setProgress(`${countBattle}/${countMaxBattle}`);
  11026. }
  11027. }
  11028. if (nameFuncStartBattle == 'towerStartBattle' ||
  11029. nameFuncStartBattle == 'bossAttack' ||
  11030. nameFuncStartBattle == 'invasion_bossStart') {
  11031. startBattle();
  11032. return;
  11033. }
  11034. cancelEndBattle(e);
  11035. }
  11036. /**
  11037. * Cancel fight
  11038. *
  11039. * Отмена боя
  11040. */
  11041. function cancelEndBattle(r) {
  11042. const fixBattle = function (heroes) {
  11043. for (const ids in heroes) {
  11044. hero = heroes[ids];
  11045. hero.energy = random(1, 999);
  11046. if (hero.hp > 0) {
  11047. hero.hp = random(1, hero.hp);
  11048. }
  11049. }
  11050. }
  11051. fixBattle(r.progress[0].attackers.heroes);
  11052. fixBattle(r.progress[0].defenders.heroes);
  11053. endBattle(r, true);
  11054. }
  11055. /**
  11056. * End of the fight
  11057. *
  11058. * Завершение боя */
  11059. function endBattle(battleResult, isCancal) {
  11060. let calls = [{
  11061. name: nameFuncEndBattle,
  11062. args: {
  11063. result: battleResult.result,
  11064. progress: battleResult.progress
  11065. },
  11066. ident: "body"
  11067. }];
  11068.  
  11069. if (nameFuncStartBattle == 'invasion_bossStart') {
  11070. calls[0].args.id = lastBattleArg.id;
  11071. }
  11072.  
  11073. send(JSON.stringify({
  11074. calls
  11075. }), async e => {
  11076. console.log(e);
  11077. if (isCancal) {
  11078. startBattle();
  11079. return;
  11080. }
  11081.  
  11082. setProgress(`${I18N('SUCCESS')}!`, 5000)
  11083. if (nameFuncStartBattle == 'invasion_bossStart' ||
  11084. nameFuncStartBattle == 'bossAttack') {
  11085. const countMaxBattle = getInput('countAutoBattle');
  11086. const bossLvl = lastBattleInfo.typeId >= 130 ? lastBattleInfo.typeId : '';
  11087. const justice = lastBattleInfo?.effects?.attackers?.percentInOutDamageModAndEnergyIncrease_any_99_100_300_99_1000_300 || 0;
  11088. let winTimer = '';
  11089. if (nameFuncStartBattle == 'invasion_bossStart') {
  11090. winTimer = '<br>Secret number: ' + battleResult.progress[0].attackers.input[5];
  11091. }
  11092. const result = await popup.confirm(
  11093. I18N('BOSS_HAS_BEEN_DEF_TEXT', {
  11094. bossLvl: `${svgBoss} ${bossLvl} ${svgJustice} ${justice}`,
  11095. countBattle: svgAttempt + ' ' + countBattle,
  11096. countMaxBattle,
  11097. winTimer,
  11098. }),
  11099. [
  11100. { msg: I18N('BTN_OK'), result: 0 },
  11101. { msg: I18N('MAKE_A_SYNC'), result: 1 },
  11102. { msg: I18N('RELOAD_GAME'), result: 2 },
  11103. ]
  11104. );
  11105. if (result) {
  11106. if (result == 1) {
  11107. cheats.refreshGame();
  11108. }
  11109. if (result == 2) {
  11110. location.reload();
  11111. }
  11112. }
  11113.  
  11114. }
  11115. endAutoBattle(`${I18N('SUCCESS')}!`)
  11116. });
  11117. }
  11118. /**
  11119. * Completing a task
  11120. *
  11121. * Завершение задачи
  11122. */
  11123. function endAutoBattle(reason, info) {
  11124. setIsCancalBattle(true);
  11125. console.log(reason, info);
  11126. resolve();
  11127. }
  11128. }
  11129.  
  11130. this.HWHClasses.executeAutoBattle = executeAutoBattle;
  11131.  
  11132. function testDailyQuests() {
  11133. const { dailyQuests } = HWHClasses;
  11134. return new Promise((resolve, reject) => {
  11135. const quests = new dailyQuests(resolve, reject);
  11136. quests.init(questsInfo);
  11137. quests.start();
  11138. });
  11139. }
  11140.  
  11141. /**
  11142. * Automatic completion of daily quests
  11143. *
  11144. * Автоматическое выполнение ежедневных квестов
  11145. */
  11146. class dailyQuests {
  11147. /**
  11148. * Send(' {"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}').then(e => console.log(e))
  11149. * Send(' {"calls":[{"name":"heroGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  11150. * Send(' {"calls":[{"name":"titanGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  11151. * Send(' {"calls":[{"name":"inventoryGet","args":{},"ident":"body"}]}').then(e => console.log(e))
  11152. * Send(' {"calls":[{"name":"questGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  11153. * Send(' {"calls":[{"name":"bossGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  11154. */
  11155. callsList = ['userGetInfo', 'heroGetAll', 'titanGetAll', 'inventoryGet', 'questGetAll', 'bossGetAll', 'missionGetAll'];
  11156.  
  11157. dataQuests = {
  11158. 10001: {
  11159. description: 'Улучши умения героев 3 раза', // ++++++++++++++++
  11160. doItCall: () => {
  11161. const upgradeSkills = this.getUpgradeSkills();
  11162. return upgradeSkills.map(({ heroId, skill }, index) => ({
  11163. name: 'heroUpgradeSkill',
  11164. args: { heroId, skill },
  11165. ident: `heroUpgradeSkill_${index}`,
  11166. }));
  11167. },
  11168. isWeCanDo: () => {
  11169. const upgradeSkills = this.getUpgradeSkills();
  11170. let sumGold = 0;
  11171. for (const skill of upgradeSkills) {
  11172. sumGold += this.skillCost(skill.value);
  11173. if (!skill.heroId) {
  11174. return false;
  11175. }
  11176. }
  11177. return this.questInfo['userGetInfo'].gold > sumGold;
  11178. },
  11179. },
  11180. 10002: {
  11181. description: 'Пройди 10 миссий', // --------------
  11182. isWeCanDo: () => false,
  11183. },
  11184. 10003: {
  11185. description: 'Пройди 3 героические миссии', // ++++++++++++++++
  11186. isWeCanDo: () => {
  11187. const vipPoints = +this.questInfo.userGetInfo.vipPoints;
  11188. const goldTicket = !!this.questInfo.inventoryGet.consumable[151];
  11189. return (vipPoints > 100 || goldTicket) && this.getHeroicMissionId();
  11190. },
  11191. doItCall: () => {
  11192. const selectedMissionId = this.getHeroicMissionId();
  11193. const goldTicket = !!this.questInfo.inventoryGet.consumable[151];
  11194. const vipLevel = Math.max(...lib.data.level.vip.filter(l => l.vipPoints <= +this.questInfo.userGetInfo.vipPoints).map(l => l.level));
  11195. // Возвращаем массив команд для рейда
  11196. if (vipLevel >= 5 || goldTicket) {
  11197. return [{ name: 'missionRaid', args: { id: selectedMissionId, times: 3 }, ident: 'missionRaid_1' }];
  11198. } else {
  11199. return [
  11200. { name: 'missionRaid', args: { id: selectedMissionId, times: 1 }, ident: 'missionRaid_1' },
  11201. { name: 'missionRaid', args: { id: selectedMissionId, times: 1 }, ident: 'missionRaid_2' },
  11202. { name: 'missionRaid', args: { id: selectedMissionId, times: 1 }, ident: 'missionRaid_3' },
  11203. ];
  11204. }
  11205. },
  11206. },
  11207. 10004: {
  11208. description: 'Сразись 3 раза на Арене или Гранд Арене', // --------------
  11209. isWeCanDo: () => false,
  11210. },
  11211. 10006: {
  11212. description: 'Используй обмен изумрудов 1 раз', // ++++++++++++++++
  11213. doItCall: () => [
  11214. {
  11215. name: 'refillableAlchemyUse',
  11216. args: { multi: false },
  11217. ident: 'refillableAlchemyUse',
  11218. },
  11219. ],
  11220. isWeCanDo: () => {
  11221. const starMoney = this.questInfo['userGetInfo'].starMoney;
  11222. return starMoney >= 20;
  11223. },
  11224. },
  11225. 10007: {
  11226. description: 'Соверши 1 призыв в Атриуме Душ', // ++++++++++++++++
  11227. doItCall: () => [{ name: 'gacha_open', args: { ident: 'heroGacha', free: true, pack: false }, ident: 'gacha_open' }],
  11228. isWeCanDo: () => {
  11229. const soulCrystal = this.questInfo['inventoryGet'].coin[38];
  11230. return soulCrystal > 0;
  11231. },
  11232. },
  11233. 10016: {
  11234. description: 'Отправь подарки согильдийцам', // ++++++++++++++++
  11235. doItCall: () => [{ name: 'clanSendDailyGifts', args: {}, ident: 'clanSendDailyGifts' }],
  11236. isWeCanDo: () => true,
  11237. },
  11238. 10018: {
  11239. description: 'Используй зелье опыта', // ++++++++++++++++
  11240. doItCall: () => {
  11241. const expHero = this.getExpHero();
  11242. return [
  11243. {
  11244. name: 'consumableUseHeroXp',
  11245. args: {
  11246. heroId: expHero.heroId,
  11247. libId: expHero.libId,
  11248. amount: 1,
  11249. },
  11250. ident: 'consumableUseHeroXp',
  11251. },
  11252. ];
  11253. },
  11254. isWeCanDo: () => {
  11255. const expHero = this.getExpHero();
  11256. return expHero.heroId && expHero.libId;
  11257. },
  11258. },
  11259. 10019: {
  11260. description: 'Открой 1 сундук в Башне',
  11261. doItFunc: testTower,
  11262. isWeCanDo: () => false,
  11263. },
  11264. 10020: {
  11265. description: 'Открой 3 сундука в Запределье', // Готово
  11266. doItCall: () => {
  11267. return this.getOutlandChest();
  11268. },
  11269. isWeCanDo: () => {
  11270. const outlandChest = this.getOutlandChest();
  11271. return outlandChest.length > 0;
  11272. },
  11273. },
  11274. 10021: {
  11275. description: 'Собери 75 Титанита в Подземелье Гильдии',
  11276. isWeCanDo: () => false,
  11277. },
  11278. 10022: {
  11279. description: 'Собери 150 Титанита в Подземелье Гильдии',
  11280. doItFunc: testDungeon,
  11281. isWeCanDo: () => false,
  11282. },
  11283. 10023: {
  11284. description: 'Прокачай Дар Стихий на 1 уровень', // Готово
  11285. doItCall: () => {
  11286. const heroId = this.getHeroIdTitanGift();
  11287. return [
  11288. { name: 'heroTitanGiftLevelUp', args: { heroId }, ident: 'heroTitanGiftLevelUp' },
  11289. { name: 'heroTitanGiftDrop', args: { heroId }, ident: 'heroTitanGiftDrop' },
  11290. ];
  11291. },
  11292. isWeCanDo: () => {
  11293. const heroId = this.getHeroIdTitanGift();
  11294. return heroId;
  11295. },
  11296. },
  11297. 10024: {
  11298. description: 'Повысь уровень любого артефакта один раз', // Готово
  11299. doItCall: () => {
  11300. const upArtifact = this.getUpgradeArtifact();
  11301. return [
  11302. {
  11303. name: 'heroArtifactLevelUp',
  11304. args: {
  11305. heroId: upArtifact.heroId,
  11306. slotId: upArtifact.slotId,
  11307. },
  11308. ident: `heroArtifactLevelUp`,
  11309. },
  11310. ];
  11311. },
  11312. isWeCanDo: () => {
  11313. const upgradeArtifact = this.getUpgradeArtifact();
  11314. return upgradeArtifact.heroId;
  11315. },
  11316. },
  11317. 10025: {
  11318. description: 'Начни 1 Экспедицию',
  11319. doItFunc: checkExpedition,
  11320. isWeCanDo: () => false,
  11321. },
  11322. 10026: {
  11323. description: 'Начни 4 Экспедиции', // --------------
  11324. doItFunc: checkExpedition,
  11325. isWeCanDo: () => false,
  11326. },
  11327. 10027: {
  11328. description: 'Победи в 1 бою Турнира Стихий',
  11329. doItFunc: testTitanArena,
  11330. isWeCanDo: () => false,
  11331. },
  11332. 10028: {
  11333. description: 'Повысь уровень любого артефакта титанов', // Готово
  11334. doItCall: () => {
  11335. const upTitanArtifact = this.getUpgradeTitanArtifact();
  11336. return [
  11337. {
  11338. name: 'titanArtifactLevelUp',
  11339. args: {
  11340. titanId: upTitanArtifact.titanId,
  11341. slotId: upTitanArtifact.slotId,
  11342. },
  11343. ident: `titanArtifactLevelUp`,
  11344. },
  11345. ];
  11346. },
  11347. isWeCanDo: () => {
  11348. const upgradeTitanArtifact = this.getUpgradeTitanArtifact();
  11349. return upgradeTitanArtifact.titanId;
  11350. },
  11351. },
  11352. 10029: {
  11353. description: 'Открой сферу артефактов титанов', // ++++++++++++++++
  11354. doItCall: () => [{ name: 'titanArtifactChestOpen', args: { amount: 1, free: true }, ident: 'titanArtifactChestOpen' }],
  11355. isWeCanDo: () => {
  11356. return this.questInfo['inventoryGet']?.consumable[55] > 0;
  11357. },
  11358. },
  11359. 10030: {
  11360. description: 'Улучши облик любого героя 1 раз', // Готово
  11361. doItCall: () => {
  11362. const upSkin = this.getUpgradeSkin();
  11363. return [
  11364. {
  11365. name: 'heroSkinUpgrade',
  11366. args: {
  11367. heroId: upSkin.heroId,
  11368. skinId: upSkin.skinId,
  11369. },
  11370. ident: `heroSkinUpgrade`,
  11371. },
  11372. ];
  11373. },
  11374. isWeCanDo: () => {
  11375. const upgradeSkin = this.getUpgradeSkin();
  11376. return upgradeSkin.heroId;
  11377. },
  11378. },
  11379. 10031: {
  11380. description: 'Победи в 6 боях Турнира Стихий', // --------------
  11381. doItFunc: testTitanArena,
  11382. isWeCanDo: () => false,
  11383. },
  11384. 10043: {
  11385. description: 'Начни или присоеденись к Приключению', // --------------
  11386. isWeCanDo: () => false,
  11387. },
  11388. 10044: {
  11389. description: 'Воспользуйся призывом питомцев 1 раз', // ++++++++++++++++
  11390. doItCall: () => [{ name: 'pet_chestOpen', args: { amount: 1, paid: false }, ident: 'pet_chestOpen' }],
  11391. isWeCanDo: () => {
  11392. return this.questInfo['inventoryGet']?.consumable[90] > 0;
  11393. },
  11394. },
  11395. 10046: {
  11396. /**
  11397. * TODO: Watch Adventure
  11398. * TODO: Смотреть приключение
  11399. */
  11400. description: 'Открой 3 сундука в Приключениях',
  11401. isWeCanDo: () => false,
  11402. },
  11403. 10047: {
  11404. description: 'Набери 150 очков активности в Гильдии', // Готово
  11405. doItCall: () => {
  11406. const enchantRune = this.getEnchantRune();
  11407. return [
  11408. {
  11409. name: 'heroEnchantRune',
  11410. args: {
  11411. heroId: enchantRune.heroId,
  11412. tier: enchantRune.tier,
  11413. items: {
  11414. consumable: { [enchantRune.itemId]: 1 },
  11415. },
  11416. },
  11417. ident: `heroEnchantRune`,
  11418. },
  11419. ];
  11420. },
  11421. isWeCanDo: () => {
  11422. const userInfo = this.questInfo['userGetInfo'];
  11423. const enchantRune = this.getEnchantRune();
  11424. return enchantRune.heroId && userInfo.gold > 1e3;
  11425. },
  11426. },
  11427. };
  11428.  
  11429. constructor(resolve, reject, questInfo) {
  11430. this.resolve = resolve;
  11431. this.reject = reject;
  11432. }
  11433.  
  11434. init(questInfo) {
  11435. this.questInfo = questInfo;
  11436. this.isAuto = false;
  11437. }
  11438.  
  11439. async autoInit(isAuto) {
  11440. this.isAuto = isAuto || false;
  11441. const quests = {};
  11442. const calls = this.callsList.map((name) => ({
  11443. name,
  11444. args: {},
  11445. ident: name,
  11446. }));
  11447. const result = await Send(JSON.stringify({ calls })).then((e) => e.results);
  11448. for (const call of result) {
  11449. quests[call.ident] = call.result.response;
  11450. }
  11451. this.questInfo = quests;
  11452. }
  11453.  
  11454. async start() {
  11455. const weCanDo = [];
  11456. const selectedActions = getSaveVal('selectedActions', {});
  11457. for (let quest of this.questInfo['questGetAll']) {
  11458. if (quest.id in this.dataQuests && quest.state == 1) {
  11459. if (!selectedActions[quest.id]) {
  11460. selectedActions[quest.id] = {
  11461. checked: false,
  11462. };
  11463. }
  11464.  
  11465. const isWeCanDo = this.dataQuests[quest.id].isWeCanDo;
  11466. if (!isWeCanDo.call(this)) {
  11467. continue;
  11468. }
  11469.  
  11470. weCanDo.push({
  11471. name: quest.id,
  11472. label: I18N(`QUEST_${quest.id}`),
  11473. checked: selectedActions[quest.id].checked,
  11474. });
  11475. }
  11476. }
  11477.  
  11478. if (!weCanDo.length) {
  11479. this.end(I18N('NOTHING_TO_DO'));
  11480. return;
  11481. }
  11482.  
  11483. console.log(weCanDo);
  11484. let taskList = [];
  11485. if (this.isAuto) {
  11486. taskList = weCanDo;
  11487. } else {
  11488. const answer = await popup.confirm(
  11489. `${I18N('YOU_CAN_COMPLETE')}:`,
  11490. [
  11491. { msg: I18N('BTN_DO_IT'), result: true },
  11492. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  11493. ],
  11494. weCanDo
  11495. );
  11496. if (!answer) {
  11497. this.end('');
  11498. return;
  11499. }
  11500. taskList = popup.getCheckBoxes();
  11501. taskList.forEach((e) => {
  11502. selectedActions[e.name].checked = e.checked;
  11503. });
  11504. setSaveVal('selectedActions', selectedActions);
  11505. }
  11506.  
  11507. const calls = [];
  11508. let countChecked = 0;
  11509. for (const task of taskList) {
  11510. if (task.checked) {
  11511. countChecked++;
  11512. const quest = this.dataQuests[task.name];
  11513. console.log(quest.description);
  11514.  
  11515. if (quest.doItCall) {
  11516. const doItCall = quest.doItCall.call(this);
  11517. calls.push(...doItCall);
  11518. }
  11519. }
  11520. }
  11521.  
  11522. if (!countChecked) {
  11523. this.end(I18N('NOT_QUEST_COMPLETED'));
  11524. return;
  11525. }
  11526.  
  11527. const result = await Send(JSON.stringify({ calls }));
  11528. if (result.error) {
  11529. console.error(result.error, result.error.call);
  11530. }
  11531. this.end(`${I18N('COMPLETED_QUESTS')}: ${countChecked}`);
  11532. }
  11533.  
  11534. errorHandling(error) {
  11535. //console.error(error);
  11536. let errorInfo = error.toString() + '\n';
  11537. try {
  11538. const errorStack = error.stack.split('\n');
  11539. const endStack = errorStack.map((e) => e.split('@')[0]).indexOf('testDoYourBest');
  11540. errorInfo += errorStack.slice(0, endStack).join('\n');
  11541. } catch (e) {
  11542. errorInfo += error.stack;
  11543. }
  11544. copyText(errorInfo);
  11545. }
  11546.  
  11547. skillCost(lvl) {
  11548. return 573 * lvl ** 0.9 + lvl ** 2.379;
  11549. }
  11550.  
  11551. getUpgradeSkills() {
  11552. const heroes = Object.values(this.questInfo['heroGetAll']);
  11553. const upgradeSkills = [
  11554. { heroId: 0, slotId: 0, value: 130 },
  11555. { heroId: 0, slotId: 0, value: 130 },
  11556. { heroId: 0, slotId: 0, value: 130 },
  11557. ];
  11558. const skillLib = lib.getData('skill');
  11559. /**
  11560. * color - 1 (белый) открывает 1 навык
  11561. * color - 2 (зеленый) открывает 2 навык
  11562. * color - 4 (синий) открывает 3 навык
  11563. * color - 7 (фиолетовый) открывает 4 навык
  11564. */
  11565. const colors = [1, 2, 4, 7];
  11566. for (const hero of heroes) {
  11567. const level = hero.level;
  11568. const color = hero.color;
  11569. for (let skillId in hero.skills) {
  11570. const tier = skillLib[skillId].tier;
  11571. const sVal = hero.skills[skillId];
  11572. if (color < colors[tier] || tier < 1 || tier > 4) {
  11573. continue;
  11574. }
  11575. for (let upSkill of upgradeSkills) {
  11576. if (sVal < upSkill.value && sVal < level) {
  11577. upSkill.value = sVal;
  11578. upSkill.heroId = hero.id;
  11579. upSkill.skill = tier;
  11580. break;
  11581. }
  11582. }
  11583. }
  11584. }
  11585. return upgradeSkills;
  11586. }
  11587.  
  11588. getUpgradeArtifact() {
  11589. const heroes = Object.values(this.questInfo['heroGetAll']);
  11590. const inventory = this.questInfo['inventoryGet'];
  11591. const upArt = { heroId: 0, slotId: 0, level: 100 };
  11592.  
  11593. const heroLib = lib.getData('hero');
  11594. const artifactLib = lib.getData('artifact');
  11595.  
  11596. for (const hero of heroes) {
  11597. const heroInfo = heroLib[hero.id];
  11598. const level = hero.level;
  11599. if (level < 20) {
  11600. continue;
  11601. }
  11602.  
  11603. for (let slotId in hero.artifacts) {
  11604. const art = hero.artifacts[slotId];
  11605. /* Текущая звезданость арта */
  11606. const star = art.star;
  11607. if (!star) {
  11608. continue;
  11609. }
  11610. /* Текущий уровень арта */
  11611. const level = art.level;
  11612. if (level >= 100) {
  11613. continue;
  11614. }
  11615. /* Идентификатор арта в библиотеке */
  11616. const artifactId = heroInfo.artifacts[slotId];
  11617. const artInfo = artifactLib.id[artifactId];
  11618. const costNextLevel = artifactLib.type[artInfo.type].levels[level + 1].cost;
  11619.  
  11620. const costCurrency = Object.keys(costNextLevel).pop();
  11621. const costValues = Object.entries(costNextLevel[costCurrency]).pop();
  11622. const costId = costValues[0];
  11623. const costValue = +costValues[1];
  11624.  
  11625. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  11626. if (level < upArt.level && inventory[costCurrency][costId] >= costValue) {
  11627. upArt.level = level;
  11628. upArt.heroId = hero.id;
  11629. upArt.slotId = slotId;
  11630. upArt.costCurrency = costCurrency;
  11631. upArt.costId = costId;
  11632. upArt.costValue = costValue;
  11633. }
  11634. }
  11635. }
  11636. return upArt;
  11637. }
  11638.  
  11639. getUpgradeSkin() {
  11640. const heroes = Object.values(this.questInfo['heroGetAll']);
  11641. const inventory = this.questInfo['inventoryGet'];
  11642. const upSkin = { heroId: 0, skinId: 0, level: 60, cost: 1500 };
  11643.  
  11644. const skinLib = lib.getData('skin');
  11645.  
  11646. for (const hero of heroes) {
  11647. const level = hero.level;
  11648. if (level < 20) {
  11649. continue;
  11650. }
  11651.  
  11652. for (let skinId in hero.skins) {
  11653. /* Текущий уровень скина */
  11654. const level = hero.skins[skinId];
  11655. if (level >= 60) {
  11656. continue;
  11657. }
  11658. /* Идентификатор скина в библиотеке */
  11659. const skinInfo = skinLib[skinId];
  11660. if (!skinInfo.statData.levels?.[level + 1]) {
  11661. continue;
  11662. }
  11663. const costNextLevel = skinInfo.statData.levels[level + 1].cost;
  11664.  
  11665. const costCurrency = Object.keys(costNextLevel).pop();
  11666. const costCurrencyId = Object.keys(costNextLevel[costCurrency]).pop();
  11667. const costValue = +costNextLevel[costCurrency][costCurrencyId];
  11668.  
  11669. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  11670. if (level < upSkin.level && costValue < upSkin.cost && inventory[costCurrency][costCurrencyId] >= costValue) {
  11671. upSkin.cost = costValue;
  11672. upSkin.level = level;
  11673. upSkin.heroId = hero.id;
  11674. upSkin.skinId = skinId;
  11675. upSkin.costCurrency = costCurrency;
  11676. upSkin.costCurrencyId = costCurrencyId;
  11677. }
  11678. }
  11679. }
  11680. return upSkin;
  11681. }
  11682.  
  11683. getUpgradeTitanArtifact() {
  11684. const titans = Object.values(this.questInfo['titanGetAll']);
  11685. const inventory = this.questInfo['inventoryGet'];
  11686. const userInfo = this.questInfo['userGetInfo'];
  11687. const upArt = { titanId: 0, slotId: 0, level: 120 };
  11688.  
  11689. const titanLib = lib.getData('titan');
  11690. const artTitanLib = lib.getData('titanArtifact');
  11691.  
  11692. for (const titan of titans) {
  11693. const titanInfo = titanLib[titan.id];
  11694. // const level = titan.level
  11695. // if (level < 20) {
  11696. // continue;
  11697. // }
  11698.  
  11699. for (let slotId in titan.artifacts) {
  11700. const art = titan.artifacts[slotId];
  11701. /* Текущая звезданость арта */
  11702. const star = art.star;
  11703. if (!star) {
  11704. continue;
  11705. }
  11706. /* Текущий уровень арта */
  11707. const level = art.level;
  11708. if (level >= 120) {
  11709. continue;
  11710. }
  11711. /* Идентификатор арта в библиотеке */
  11712. const artifactId = titanInfo.artifacts[slotId];
  11713. const artInfo = artTitanLib.id[artifactId];
  11714. const costNextLevel = artTitanLib.type[artInfo.type].levels[level + 1].cost;
  11715.  
  11716. const costCurrency = Object.keys(costNextLevel).pop();
  11717. let costValue = 0;
  11718. let currentValue = 0;
  11719. if (costCurrency == 'gold') {
  11720. costValue = costNextLevel[costCurrency];
  11721. currentValue = userInfo.gold;
  11722. } else {
  11723. const costValues = Object.entries(costNextLevel[costCurrency]).pop();
  11724. const costId = costValues[0];
  11725. costValue = +costValues[1];
  11726. currentValue = inventory[costCurrency][costId];
  11727. }
  11728.  
  11729. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  11730. if (level < upArt.level && currentValue >= costValue) {
  11731. upArt.level = level;
  11732. upArt.titanId = titan.id;
  11733. upArt.slotId = slotId;
  11734. break;
  11735. }
  11736. }
  11737. }
  11738. return upArt;
  11739. }
  11740.  
  11741. getEnchantRune() {
  11742. const heroes = Object.values(this.questInfo['heroGetAll']);
  11743. const inventory = this.questInfo['inventoryGet'];
  11744. const enchRune = { heroId: 0, tier: 0, exp: 43750, itemId: 0 };
  11745. for (let i = 1; i <= 4; i++) {
  11746. if (inventory.consumable[i] > 0) {
  11747. enchRune.itemId = i;
  11748. break;
  11749. }
  11750. return enchRune;
  11751. }
  11752.  
  11753. const runeLib = lib.getData('rune');
  11754. const runeLvls = Object.values(runeLib.level);
  11755. /**
  11756. * color - 4 (синий) открывает 1 и 2 символ
  11757. * color - 7 (фиолетовый) открывает 3 символ
  11758. * color - 8 (фиолетовый +1) открывает 4 символ
  11759. * color - 9 (фиолетовый +2) открывает 5 символ
  11760. */
  11761. // TODO: кажется надо учесть уровень команды
  11762. const colors = [4, 4, 7, 8, 9];
  11763. for (const hero of heroes) {
  11764. const color = hero.color;
  11765.  
  11766. for (let runeTier in hero.runes) {
  11767. /* Проверка на доступность руны */
  11768. if (color < colors[runeTier]) {
  11769. continue;
  11770. }
  11771. /* Текущий опыт руны */
  11772. const exp = hero.runes[runeTier];
  11773. if (exp >= 43750) {
  11774. continue;
  11775. }
  11776.  
  11777. let level = 0;
  11778. if (exp) {
  11779. for (let lvl of runeLvls) {
  11780. if (exp >= lvl.enchantValue) {
  11781. level = lvl.level;
  11782. } else {
  11783. break;
  11784. }
  11785. }
  11786. }
  11787. /** Уровень героя необходимый для уровня руны */
  11788. const heroLevel = runeLib.level[level].heroLevel;
  11789. if (hero.level < heroLevel) {
  11790. continue;
  11791. }
  11792.  
  11793. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  11794. if (exp < enchRune.exp) {
  11795. enchRune.exp = exp;
  11796. enchRune.heroId = hero.id;
  11797. enchRune.tier = runeTier;
  11798. break;
  11799. }
  11800. }
  11801. }
  11802. return enchRune;
  11803. }
  11804.  
  11805. getOutlandChest() {
  11806. const bosses = this.questInfo['bossGetAll'];
  11807.  
  11808. const calls = [];
  11809.  
  11810. for (let boss of bosses) {
  11811. if (boss.mayRaid) {
  11812. calls.push({
  11813. name: 'bossRaid',
  11814. args: {
  11815. bossId: boss.id,
  11816. },
  11817. ident: 'bossRaid_' + boss.id,
  11818. });
  11819. calls.push({
  11820. name: 'bossOpenChest',
  11821. args: {
  11822. bossId: boss.id,
  11823. amount: 1,
  11824. starmoney: 0,
  11825. },
  11826. ident: 'bossOpenChest_' + boss.id,
  11827. });
  11828. } else if (boss.chestId == 1) {
  11829. calls.push({
  11830. name: 'bossOpenChest',
  11831. args: {
  11832. bossId: boss.id,
  11833. amount: 1,
  11834. starmoney: 0,
  11835. },
  11836. ident: 'bossOpenChest_' + boss.id,
  11837. });
  11838. }
  11839. }
  11840.  
  11841. return calls;
  11842. }
  11843.  
  11844. getExpHero() {
  11845. const heroes = Object.values(this.questInfo['heroGetAll']);
  11846. const inventory = this.questInfo['inventoryGet'];
  11847. const expHero = { heroId: 0, exp: 3625195, libId: 0 };
  11848. /** зелья опыта (consumable 9, 10, 11, 12) */
  11849. for (let i = 9; i <= 12; i++) {
  11850. if (inventory.consumable[i]) {
  11851. expHero.libId = i;
  11852. break;
  11853. }
  11854. }
  11855.  
  11856. for (const hero of heroes) {
  11857. const exp = hero.xp;
  11858. if (exp < expHero.exp) {
  11859. expHero.heroId = hero.id;
  11860. }
  11861. }
  11862. return expHero;
  11863. }
  11864.  
  11865. getHeroIdTitanGift() {
  11866. const heroes = Object.values(this.questInfo['heroGetAll']);
  11867. const inventory = this.questInfo['inventoryGet'];
  11868. const user = this.questInfo['userGetInfo'];
  11869. const titanGiftLib = lib.getData('titanGift');
  11870. /** Искры */
  11871. const titanGift = inventory.consumable[24];
  11872. let heroId = 0;
  11873. let minLevel = 30;
  11874.  
  11875. if (titanGift < 250 || user.gold < 7000) {
  11876. return 0;
  11877. }
  11878.  
  11879. for (const hero of heroes) {
  11880. if (hero.titanGiftLevel >= 30) {
  11881. continue;
  11882. }
  11883.  
  11884. if (!hero.titanGiftLevel) {
  11885. return hero.id;
  11886. }
  11887.  
  11888. const cost = titanGiftLib[hero.titanGiftLevel].cost;
  11889. if (minLevel > hero.titanGiftLevel && titanGift >= cost.consumable[24] && user.gold >= cost.gold) {
  11890. minLevel = hero.titanGiftLevel;
  11891. heroId = hero.id;
  11892. }
  11893. }
  11894.  
  11895. return heroId;
  11896. }
  11897.  
  11898. getHeroicMissionId() {
  11899. // Получаем доступные миссии с 3 звездами
  11900. const availableMissionsToRaid = Object.values(this.questInfo.missionGetAll)
  11901. .filter((mission) => mission.stars === 3)
  11902. .map((mission) => mission.id);
  11903.  
  11904. // Получаем героев для улучшения, у которых меньше 6 звезд
  11905. const heroesToUpgrade = Object.values(this.questInfo.heroGetAll)
  11906. .filter((hero) => hero.star < 6)
  11907. .sort((a, b) => b.power - a.power)
  11908. .map((hero) => hero.id);
  11909.  
  11910. // Получаем героические миссии, которые доступны для рейдов
  11911. const heroicMissions = Object.values(lib.data.mission).filter((mission) => mission.isHeroic && availableMissionsToRaid.includes(mission.id));
  11912.  
  11913. // Собираем дропы из героических миссий
  11914. const drops = heroicMissions.map((mission) => {
  11915. const lastWave = mission.normalMode.waves[mission.normalMode.waves.length - 1];
  11916. const allRewards = lastWave.enemies[lastWave.enemies.length - 1]
  11917. .drop.map((drop) => drop.reward);
  11918.  
  11919. const heroId = +Object.keys(allRewards.find((reward) => reward.fragmentHero).fragmentHero).pop();
  11920.  
  11921. return { id: mission.id, heroId };
  11922. });
  11923.  
  11924. // Определяем, какие дропы подходят для героев, которых нужно улучшить
  11925. const heroDrops = heroesToUpgrade.map((heroId) => drops.find((drop) => drop.heroId == heroId)).filter((drop) => drop);
  11926. const firstMission = heroDrops[0];
  11927. // Выбираем миссию для рейда
  11928. const selectedMissionId = firstMission ? firstMission.id : 1;
  11929.  
  11930. const stamina = this.questInfo.userGetInfo.refillable.find((x) => x.id == 1).amount;
  11931. const costMissions = 3 * lib.data.mission[selectedMissionId].normalMode.teamExp;
  11932. if (stamina < costMissions) {
  11933. console.log('Энергии не достаточно');
  11934. return 0;
  11935. }
  11936. return selectedMissionId;
  11937. }
  11938.  
  11939. end(status) {
  11940. setProgress(status, true);
  11941. this.resolve();
  11942. }
  11943. }
  11944.  
  11945. this.questRun = dailyQuests;
  11946. this.HWHClasses.dailyQuests = dailyQuests;
  11947.  
  11948. function testDoYourBest() {
  11949. const { doYourBest } = HWHClasses;
  11950. return new Promise((resolve, reject) => {
  11951. const doIt = new doYourBest(resolve, reject);
  11952. doIt.start();
  11953. });
  11954. }
  11955.  
  11956. /**
  11957. * Do everything button
  11958. *
  11959. * Кнопка сделать все
  11960. */
  11961. class doYourBest {
  11962.  
  11963. funcList = [
  11964. {
  11965. name: 'getOutland',
  11966. label: I18N('ASSEMBLE_OUTLAND'),
  11967. checked: false
  11968. },
  11969. {
  11970. name: 'testTower',
  11971. label: I18N('PASS_THE_TOWER'),
  11972. checked: false
  11973. },
  11974. {
  11975. name: 'checkExpedition',
  11976. label: I18N('CHECK_EXPEDITIONS'),
  11977. checked: false
  11978. },
  11979. {
  11980. name: 'testTitanArena',
  11981. label: I18N('COMPLETE_TOE'),
  11982. checked: false
  11983. },
  11984. {
  11985. name: 'mailGetAll',
  11986. label: I18N('COLLECT_MAIL'),
  11987. checked: false
  11988. },
  11989. {
  11990. name: 'collectAllStuff',
  11991. label: I18N('COLLECT_MISC'),
  11992. title: I18N('COLLECT_MISC_TITLE'),
  11993. checked: false
  11994. },
  11995. {
  11996. name: 'getDailyBonus',
  11997. label: I18N('DAILY_BONUS'),
  11998. checked: false
  11999. },
  12000. {
  12001. name: 'dailyQuests',
  12002. label: I18N('DO_DAILY_QUESTS'),
  12003. checked: false
  12004. },
  12005. {
  12006. name: 'rollAscension',
  12007. label: I18N('SEER_TITLE'),
  12008. checked: false
  12009. },
  12010. {
  12011. name: 'questAllFarm',
  12012. label: I18N('COLLECT_QUEST_REWARDS'),
  12013. checked: false
  12014. },
  12015. {
  12016. name: 'testDungeon',
  12017. label: I18N('COMPLETE_DUNGEON'),
  12018. checked: false
  12019. },
  12020. {
  12021. name: 'synchronization',
  12022. label: I18N('MAKE_A_SYNC'),
  12023. checked: false
  12024. },
  12025. {
  12026. name: 'reloadGame',
  12027. label: I18N('RELOAD_GAME'),
  12028. checked: false
  12029. },
  12030. ];
  12031.  
  12032. functions = {
  12033. getOutland,
  12034. testTower,
  12035. checkExpedition,
  12036. testTitanArena,
  12037. mailGetAll,
  12038. collectAllStuff: async () => {
  12039. await offerFarmAllReward();
  12040. 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"}]}');
  12041. },
  12042. dailyQuests: async function () {
  12043. const quests = new dailyQuests(() => { }, () => { });
  12044. await quests.autoInit(true);
  12045. await quests.start();
  12046. },
  12047. rollAscension,
  12048. getDailyBonus,
  12049. questAllFarm,
  12050. testDungeon,
  12051. synchronization: async () => {
  12052. cheats.refreshGame();
  12053. },
  12054. reloadGame: async () => {
  12055. location.reload();
  12056. },
  12057. }
  12058.  
  12059. constructor(resolve, reject, questInfo) {
  12060. this.resolve = resolve;
  12061. this.reject = reject;
  12062. this.questInfo = questInfo
  12063. }
  12064.  
  12065. async start() {
  12066. const selectedDoIt = getSaveVal('selectedDoIt', {});
  12067.  
  12068. this.funcList.forEach(task => {
  12069. if (!selectedDoIt[task.name]) {
  12070. selectedDoIt[task.name] = {
  12071. checked: task.checked
  12072. }
  12073. } else {
  12074. task.checked = selectedDoIt[task.name].checked
  12075. }
  12076. });
  12077.  
  12078. const answer = await popup.confirm(I18N('RUN_FUNCTION'), [
  12079. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  12080. { msg: I18N('BTN_GO'), result: true },
  12081. ], this.funcList);
  12082.  
  12083. if (!answer) {
  12084. this.end('');
  12085. return;
  12086. }
  12087.  
  12088. const taskList = popup.getCheckBoxes();
  12089. taskList.forEach(task => {
  12090. selectedDoIt[task.name].checked = task.checked;
  12091. });
  12092. setSaveVal('selectedDoIt', selectedDoIt);
  12093. for (const task of popup.getCheckBoxes()) {
  12094. if (task.checked) {
  12095. try {
  12096. setProgress(`${task.label} <br>${I18N('PERFORMED')}!`);
  12097. await this.functions[task.name]();
  12098. setProgress(`${task.label} <br>${I18N('DONE')}!`);
  12099. } catch (error) {
  12100. if (await popup.confirm(`${I18N('ERRORS_OCCURRES')}:<br> ${task.label} <br>${I18N('COPY_ERROR')}?`, [
  12101. { msg: I18N('BTN_NO'), result: false },
  12102. { msg: I18N('BTN_YES'), result: true },
  12103. ])) {
  12104. this.errorHandling(error);
  12105. }
  12106. }
  12107. }
  12108. }
  12109. setTimeout((msg) => {
  12110. this.end(msg);
  12111. }, 2000, I18N('ALL_TASK_COMPLETED'));
  12112. return;
  12113. }
  12114.  
  12115. errorHandling(error) {
  12116. //console.error(error);
  12117. let errorInfo = error.toString() + '\n';
  12118. try {
  12119. const errorStack = error.stack.split('\n');
  12120. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testDoYourBest");
  12121. errorInfo += errorStack.slice(0, endStack).join('\n');
  12122. } catch (e) {
  12123. errorInfo += error.stack;
  12124. }
  12125. copyText(errorInfo);
  12126. }
  12127.  
  12128. end(status) {
  12129. setProgress(status, true);
  12130. this.resolve();
  12131. }
  12132. }
  12133.  
  12134. this.HWHClasses.doYourBest = doYourBest;
  12135.  
  12136. /**
  12137. * Passing the adventure along the specified route
  12138. *
  12139. * Прохождение приключения по указанному маршруту
  12140. */
  12141. function testAdventure(type) {
  12142. const { executeAdventure } = HWHClasses;
  12143. return new Promise((resolve, reject) => {
  12144. const bossBattle = new executeAdventure(resolve, reject);
  12145. bossBattle.start(type);
  12146. });
  12147. }
  12148.  
  12149. /**
  12150. * Passing the adventure along the specified route
  12151. *
  12152. * Прохождение приключения по указанному маршруту
  12153. */
  12154. class executeAdventure {
  12155.  
  12156. type = 'default';
  12157.  
  12158. actions = {
  12159. default: {
  12160. getInfo: "adventure_getInfo",
  12161. startBattle: 'adventure_turnStartBattle',
  12162. endBattle: 'adventure_endBattle',
  12163. collectBuff: 'adventure_turnCollectBuff'
  12164. },
  12165. solo: {
  12166. getInfo: "adventureSolo_getInfo",
  12167. startBattle: 'adventureSolo_turnStartBattle',
  12168. endBattle: 'adventureSolo_endBattle',
  12169. collectBuff: 'adventureSolo_turnCollectBuff'
  12170. }
  12171. }
  12172.  
  12173. terminatеReason = I18N('UNKNOWN');
  12174. callAdventureInfo = {
  12175. name: "adventure_getInfo",
  12176. args: {},
  12177. ident: "adventure_getInfo"
  12178. }
  12179. callTeamGetAll = {
  12180. name: "teamGetAll",
  12181. args: {},
  12182. ident: "teamGetAll"
  12183. }
  12184. callTeamGetFavor = {
  12185. name: "teamGetFavor",
  12186. args: {},
  12187. ident: "teamGetFavor"
  12188. }
  12189. callStartBattle = {
  12190. name: "adventure_turnStartBattle",
  12191. args: {},
  12192. ident: "body"
  12193. }
  12194. callEndBattle = {
  12195. name: "adventure_endBattle",
  12196. args: {
  12197. result: {},
  12198. progress: {},
  12199. },
  12200. ident: "body"
  12201. }
  12202. callCollectBuff = {
  12203. name: "adventure_turnCollectBuff",
  12204. args: {},
  12205. ident: "body"
  12206. }
  12207.  
  12208. constructor(resolve, reject) {
  12209. this.resolve = resolve;
  12210. this.reject = reject;
  12211. }
  12212.  
  12213. async start(type) {
  12214. this.type = type || this.type;
  12215. this.callAdventureInfo.name = this.actions[this.type].getInfo;
  12216. const data = await Send(JSON.stringify({
  12217. calls: [
  12218. this.callAdventureInfo,
  12219. this.callTeamGetAll,
  12220. this.callTeamGetFavor
  12221. ]
  12222. }));
  12223. return this.checkAdventureInfo(data.results);
  12224. }
  12225.  
  12226. async getPath() {
  12227. const oldVal = getSaveVal('adventurePath', '');
  12228. const keyPath = `adventurePath:${this.mapIdent}`;
  12229. const answer = await popup.confirm(I18N('ENTER_THE_PATH'), [
  12230. {
  12231. msg: I18N('START_ADVENTURE'),
  12232. placeholder: '1,2,3,4,5,6',
  12233. isInput: true,
  12234. default: getSaveVal(keyPath, oldVal)
  12235. },
  12236. {
  12237. msg: I18N('BTN_CANCEL'),
  12238. result: false,
  12239. isCancel: true
  12240. },
  12241. ]);
  12242. if (!answer) {
  12243. this.terminatеReason = I18N('BTN_CANCELED');
  12244. return false;
  12245. }
  12246.  
  12247. let path = answer.split(',');
  12248. if (path.length < 2) {
  12249. path = answer.split('-');
  12250. }
  12251. if (path.length < 2) {
  12252. this.terminatеReason = I18N('MUST_TWO_POINTS');
  12253. return false;
  12254. }
  12255.  
  12256. for (let p in path) {
  12257. path[p] = +path[p].trim()
  12258. if (Number.isNaN(path[p])) {
  12259. this.terminatеReason = I18N('MUST_ONLY_NUMBERS');
  12260. return false;
  12261. }
  12262. }
  12263.  
  12264. if (!this.checkPath(path)) {
  12265. return false;
  12266. }
  12267. setSaveVal(keyPath, answer);
  12268. return path;
  12269. }
  12270.  
  12271. checkPath(path) {
  12272. for (let i = 0; i < path.length - 1; i++) {
  12273. const currentPoint = path[i];
  12274. const nextPoint = path[i + 1];
  12275.  
  12276. const isValidPath = this.paths.some(p =>
  12277. (p.from_id === currentPoint && p.to_id === nextPoint) ||
  12278. (p.from_id === nextPoint && p.to_id === currentPoint)
  12279. );
  12280.  
  12281. if (!isValidPath) {
  12282. this.terminatеReason = I18N('INCORRECT_WAY', {
  12283. from: currentPoint,
  12284. to: nextPoint,
  12285. });
  12286. return false;
  12287. }
  12288. }
  12289.  
  12290. return true;
  12291. }
  12292.  
  12293. async checkAdventureInfo(data) {
  12294. this.advInfo = data[0].result.response;
  12295. if (!this.advInfo) {
  12296. this.terminatеReason = I18N('NOT_ON_AN_ADVENTURE') ;
  12297. return this.end();
  12298. }
  12299. const heroesTeam = data[1].result.response.adventure_hero;
  12300. const favor = data[2]?.result.response.adventure_hero;
  12301. const heroes = heroesTeam.slice(0, 5);
  12302. const pet = heroesTeam[5];
  12303. this.args = {
  12304. pet,
  12305. heroes,
  12306. favor,
  12307. path: [],
  12308. broadcast: false
  12309. }
  12310. const advUserInfo = this.advInfo.users[userInfo.id];
  12311. this.turnsLeft = advUserInfo.turnsLeft;
  12312. this.currentNode = advUserInfo.currentNode;
  12313. this.nodes = this.advInfo.nodes;
  12314. this.paths = this.advInfo.paths;
  12315. this.mapIdent = this.advInfo.mapIdent;
  12316.  
  12317. this.path = await this.getPath();
  12318. if (!this.path) {
  12319. return this.end();
  12320. }
  12321.  
  12322. if (this.currentNode == 1 && this.path[0] != 1) {
  12323. this.path.unshift(1);
  12324. }
  12325.  
  12326. return this.loop();
  12327. }
  12328.  
  12329. async loop() {
  12330. const position = this.path.indexOf(+this.currentNode);
  12331. if (!(~position)) {
  12332. this.terminatеReason = I18N('YOU_IN_NOT_ON_THE_WAY');
  12333. return this.end();
  12334. }
  12335. this.path = this.path.slice(position);
  12336. if ((this.path.length - 1) > this.turnsLeft &&
  12337. await popup.confirm(I18N('ATTEMPTS_NOT_ENOUGH'), [
  12338. { msg: I18N('YES_CONTINUE'), result: false },
  12339. { msg: I18N('BTN_NO'), result: true },
  12340. ])) {
  12341. this.terminatеReason = I18N('NOT_ENOUGH_AP');
  12342. return this.end();
  12343. }
  12344. const toPath = [];
  12345. for (const nodeId of this.path) {
  12346. if (!this.turnsLeft) {
  12347. this.terminatеReason = I18N('ATTEMPTS_ARE_OVER');
  12348. return this.end();
  12349. }
  12350. toPath.push(nodeId);
  12351. console.log(toPath);
  12352. if (toPath.length > 1) {
  12353. setProgress(toPath.join(' > ') + ` ${I18N('MOVES')}: ` + this.turnsLeft);
  12354. }
  12355. if (nodeId == this.currentNode) {
  12356. continue;
  12357. }
  12358.  
  12359. const nodeInfo = this.getNodeInfo(nodeId);
  12360. if (nodeInfo.type == 'TYPE_COMBAT') {
  12361. if (nodeInfo.state == 'empty') {
  12362. this.turnsLeft--;
  12363. continue;
  12364. }
  12365.  
  12366. /**
  12367. * Disable regular battle cancellation
  12368. *
  12369. * Отключаем штатную отменую боя
  12370. */
  12371. setIsCancalBattle(false);
  12372. if (await this.battle(toPath)) {
  12373. this.turnsLeft--;
  12374. toPath.splice(0, toPath.indexOf(nodeId));
  12375. nodeInfo.state = 'empty';
  12376. setIsCancalBattle(true);
  12377. continue;
  12378. }
  12379. setIsCancalBattle(true);
  12380. return this.end()
  12381. }
  12382.  
  12383. if (nodeInfo.type == 'TYPE_PLAYERBUFF') {
  12384. const buff = this.checkBuff(nodeInfo);
  12385. if (buff == null) {
  12386. continue;
  12387. }
  12388.  
  12389. if (await this.collectBuff(buff, toPath)) {
  12390. this.turnsLeft--;
  12391. toPath.splice(0, toPath.indexOf(nodeId));
  12392. continue;
  12393. }
  12394. this.terminatеReason = I18N('BUFF_GET_ERROR');
  12395. return this.end();
  12396. }
  12397. }
  12398. this.terminatеReason = I18N('SUCCESS');
  12399. return this.end();
  12400. }
  12401.  
  12402. /**
  12403. * Carrying out a fight
  12404. *
  12405. * Проведение боя
  12406. */
  12407. async battle(path, preCalc = true) {
  12408. const data = await this.startBattle(path);
  12409. try {
  12410. const battle = data.results[0].result.response.battle;
  12411. const result = await Calc(battle);
  12412. if (result.result.win) {
  12413. const info = await this.endBattle(result);
  12414. if (info.results[0].result.response?.error) {
  12415. this.terminatеReason = I18N('BATTLE_END_ERROR');
  12416. return false;
  12417. }
  12418. } else {
  12419. await this.cancelBattle(result);
  12420.  
  12421. if (preCalc && await this.preCalcBattle(battle)) {
  12422. path = path.slice(-2);
  12423. for (let i = 1; i <= getInput('countAutoBattle'); i++) {
  12424. setProgress(`${I18N('AUTOBOT')}: ${i}/${getInput('countAutoBattle')}`);
  12425. const result = await this.battle(path, false);
  12426. if (result) {
  12427. setProgress(I18N('VICTORY'));
  12428. return true;
  12429. }
  12430. }
  12431. this.terminatеReason = I18N('FAILED_TO_WIN_AUTO');
  12432. return false;
  12433. }
  12434. return false;
  12435. }
  12436. } catch (error) {
  12437. console.error(error);
  12438. if (await popup.confirm(I18N('ERROR_OF_THE_BATTLE_COPY'), [
  12439. { msg: I18N('BTN_NO'), result: false },
  12440. { msg: I18N('BTN_YES'), result: true },
  12441. ])) {
  12442. this.errorHandling(error, data);
  12443. }
  12444. this.terminatеReason = I18N('ERROR_DURING_THE_BATTLE');
  12445. return false;
  12446. }
  12447. return true;
  12448. }
  12449.  
  12450. /**
  12451. * Recalculate battles
  12452. *
  12453. * Прерасчтет битвы
  12454. */
  12455. async preCalcBattle(battle) {
  12456. const countTestBattle = getInput('countTestBattle');
  12457. for (let i = 0; i < countTestBattle; i++) {
  12458. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  12459. const result = await Calc(battle);
  12460. if (result.result.win) {
  12461. console.log(i, countTestBattle);
  12462. return true;
  12463. }
  12464. }
  12465. this.terminatеReason = I18N('NO_CHANCE_WIN') + countTestBattle;
  12466. return false;
  12467. }
  12468.  
  12469. /**
  12470. * Starts a fight
  12471. *
  12472. * Начинает бой
  12473. */
  12474. startBattle(path) {
  12475. this.args.path = path;
  12476. this.callStartBattle.name = this.actions[this.type].startBattle;
  12477. this.callStartBattle.args = this.args
  12478. const calls = [this.callStartBattle];
  12479. return Send(JSON.stringify({ calls }));
  12480. }
  12481.  
  12482. cancelBattle(battle) {
  12483. const fixBattle = function (heroes) {
  12484. for (const ids in heroes) {
  12485. const hero = heroes[ids];
  12486. hero.energy = random(1, 999);
  12487. if (hero.hp > 0) {
  12488. hero.hp = random(1, hero.hp);
  12489. }
  12490. }
  12491. }
  12492. fixBattle(battle.progress[0].attackers.heroes);
  12493. fixBattle(battle.progress[0].defenders.heroes);
  12494. return this.endBattle(battle);
  12495. }
  12496.  
  12497. /**
  12498. * Ends the fight
  12499. *
  12500. * Заканчивает бой
  12501. */
  12502. endBattle(battle) {
  12503. this.callEndBattle.name = this.actions[this.type].endBattle;
  12504. this.callEndBattle.args.result = battle.result
  12505. this.callEndBattle.args.progress = battle.progress
  12506. const calls = [this.callEndBattle];
  12507. return Send(JSON.stringify({ calls }));
  12508. }
  12509.  
  12510. /**
  12511. * Checks if you can get a buff
  12512. *
  12513. * Проверяет можно ли получить баф
  12514. */
  12515. checkBuff(nodeInfo) {
  12516. let id = null;
  12517. let value = 0;
  12518. for (const buffId in nodeInfo.buffs) {
  12519. const buff = nodeInfo.buffs[buffId];
  12520. if (buff.owner == null && buff.value > value) {
  12521. id = buffId;
  12522. value = buff.value;
  12523. }
  12524. }
  12525. nodeInfo.buffs[id].owner = 'Я';
  12526. return id;
  12527. }
  12528.  
  12529. /**
  12530. * Collects a buff
  12531. *
  12532. * Собирает баф
  12533. */
  12534. async collectBuff(buff, path) {
  12535. this.callCollectBuff.name = this.actions[this.type].collectBuff;
  12536. this.callCollectBuff.args = { buff, path };
  12537. const calls = [this.callCollectBuff];
  12538. return Send(JSON.stringify({ calls }));
  12539. }
  12540.  
  12541. getNodeInfo(nodeId) {
  12542. return this.nodes.find(node => node.id == nodeId);
  12543. }
  12544.  
  12545. errorHandling(error, data) {
  12546. //console.error(error);
  12547. let errorInfo = error.toString() + '\n';
  12548. try {
  12549. const errorStack = error.stack.split('\n');
  12550. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testAdventure");
  12551. errorInfo += errorStack.slice(0, endStack).join('\n');
  12552. } catch (e) {
  12553. errorInfo += error.stack;
  12554. }
  12555. if (data) {
  12556. errorInfo += '\nData: ' + JSON.stringify(data);
  12557. }
  12558. copyText(errorInfo);
  12559. }
  12560.  
  12561. end() {
  12562. setIsCancalBattle(true);
  12563. setProgress(this.terminatеReason, true);
  12564. console.log(this.terminatеReason);
  12565. this.resolve();
  12566. }
  12567. }
  12568.  
  12569. this.HWHClasses.executeAdventure = executeAdventure;
  12570.  
  12571. /**
  12572. * Passage of brawls
  12573. *
  12574. * Прохождение потасовок
  12575. */
  12576. function testBrawls(isAuto) {
  12577. const { executeBrawls } = HWHClasses;
  12578. return new Promise((resolve, reject) => {
  12579. const brawls = new executeBrawls(resolve, reject);
  12580. brawls.start(brawlsPack, isAuto);
  12581. });
  12582. }
  12583. /**
  12584. * Passage of brawls
  12585. *
  12586. * Прохождение потасовок
  12587. */
  12588. class executeBrawls {
  12589. callBrawlQuestGetInfo = {
  12590. name: "brawl_questGetInfo",
  12591. args: {},
  12592. ident: "brawl_questGetInfo"
  12593. }
  12594. callBrawlFindEnemies = {
  12595. name: "brawl_findEnemies",
  12596. args: {},
  12597. ident: "brawl_findEnemies"
  12598. }
  12599. callBrawlQuestFarm = {
  12600. name: "brawl_questFarm",
  12601. args: {},
  12602. ident: "brawl_questFarm"
  12603. }
  12604. callUserGetInfo = {
  12605. name: "userGetInfo",
  12606. args: {},
  12607. ident: "userGetInfo"
  12608. }
  12609. callTeamGetMaxUpgrade = {
  12610. name: "teamGetMaxUpgrade",
  12611. args: {},
  12612. ident: "teamGetMaxUpgrade"
  12613. }
  12614. callBrawlGetInfo = {
  12615. name: "brawl_getInfo",
  12616. args: {},
  12617. ident: "brawl_getInfo"
  12618. }
  12619.  
  12620. stats = {
  12621. win: 0,
  12622. loss: 0,
  12623. count: 0,
  12624. }
  12625.  
  12626. stage = {
  12627. '3': 1,
  12628. '7': 2,
  12629. '12': 3,
  12630. }
  12631.  
  12632. attempts = 0;
  12633.  
  12634. constructor(resolve, reject) {
  12635. this.resolve = resolve;
  12636. this.reject = reject;
  12637.  
  12638. const allHeroIds = Object.keys(lib.getData('hero'));
  12639. this.callTeamGetMaxUpgrade.args.units = {
  12640. hero: allHeroIds.filter((id) => +id < 1000),
  12641. titan: allHeroIds.filter((id) => +id >= 4000 && +id < 4100),
  12642. pet: allHeroIds.filter((id) => +id >= 6000 && +id < 6100),
  12643. };
  12644. }
  12645.  
  12646. async start(args, isAuto) {
  12647. this.isAuto = isAuto;
  12648. this.args = args;
  12649. setIsCancalBattle(false);
  12650. this.brawlInfo = await this.getBrawlInfo();
  12651. this.attempts = this.brawlInfo.attempts;
  12652.  
  12653. if (!this.attempts && !this.info.boughtEndlessLivesToday) {
  12654. this.end(I18N('DONT_HAVE_LIVES'));
  12655. return;
  12656. }
  12657.  
  12658. while (1) {
  12659. if (!isBrawlsAutoStart) {
  12660. this.end(I18N('BTN_CANCELED'));
  12661. return;
  12662. }
  12663.  
  12664. const maxStage = this.brawlInfo.questInfo.stage;
  12665. const stage = this.stage[maxStage];
  12666. const progress = this.brawlInfo.questInfo.progress;
  12667.  
  12668. setProgress(
  12669. `${I18N('STAGE')} ${stage}: ${progress}/${maxStage}<br>${I18N('FIGHTS')}: ${this.stats.count}<br>${I18N('WINS')}: ${
  12670. this.stats.win
  12671. }<br>${I18N('LOSSES')}: ${this.stats.loss}<br>${I18N('LIVES')}: ${this.attempts}<br>${I18N('STOP')}`,
  12672. false,
  12673. function () {
  12674. isBrawlsAutoStart = false;
  12675. }
  12676. );
  12677.  
  12678. if (this.brawlInfo.questInfo.canFarm) {
  12679. const result = await this.questFarm();
  12680. console.log(result);
  12681. }
  12682.  
  12683. if (!this.continueAttack && this.brawlInfo.questInfo.stage == 12 && this.brawlInfo.questInfo.progress == 12) {
  12684. if (
  12685. await popup.confirm(I18N('BRAWL_DAILY_TASK_COMPLETED'), [
  12686. { msg: I18N('BTN_NO'), result: true },
  12687. { msg: I18N('BTN_YES'), result: false },
  12688. ])
  12689. ) {
  12690. this.end(I18N('SUCCESS'));
  12691. return;
  12692. } else {
  12693. this.continueAttack = true;
  12694. }
  12695. }
  12696.  
  12697. if (!this.attempts && !this.info.boughtEndlessLivesToday) {
  12698. this.end(I18N('DONT_HAVE_LIVES'));
  12699. return;
  12700. }
  12701.  
  12702. const enemie = Object.values(this.brawlInfo.findEnemies).shift();
  12703.  
  12704. // Автоматический подбор пачки
  12705. if (this.isAuto) {
  12706. if (this.mandatoryId <= 4000 && this.mandatoryId != 13) {
  12707. this.end(I18N('BRAWL_AUTO_PACK_NOT_CUR_HERO'));
  12708. return;
  12709. }
  12710. if (this.mandatoryId >= 4000 && this.mandatoryId < 4100) {
  12711. this.args = await this.updateTitanPack(enemie.heroes);
  12712. } else if (this.mandatoryId < 4000 && this.mandatoryId == 13) {
  12713. this.args = await this.updateHeroesPack(enemie.heroes);
  12714. }
  12715. }
  12716.  
  12717. const result = await this.battle(enemie.userId);
  12718. this.brawlInfo = {
  12719. questInfo: result[1].result.response,
  12720. findEnemies: result[2].result.response,
  12721. };
  12722. }
  12723. }
  12724.  
  12725. async updateTitanPack(enemieHeroes) {
  12726. const packs = [
  12727. [4033, 4040, 4041, 4042, 4043],
  12728. [4032, 4040, 4041, 4042, 4043],
  12729. [4031, 4040, 4041, 4042, 4043],
  12730. [4030, 4040, 4041, 4042, 4043],
  12731. [4032, 4033, 4040, 4042, 4043],
  12732. [4030, 4033, 4041, 4042, 4043],
  12733. [4031, 4033, 4040, 4042, 4043],
  12734. [4032, 4033, 4040, 4041, 4043],
  12735. [4023, 4040, 4041, 4042, 4043],
  12736. [4030, 4033, 4040, 4042, 4043],
  12737. [4031, 4033, 4040, 4041, 4043],
  12738. [4022, 4040, 4041, 4042, 4043],
  12739. [4030, 4033, 4040, 4041, 4043],
  12740. [4021, 4040, 4041, 4042, 4043],
  12741. [4020, 4040, 4041, 4042, 4043],
  12742. [4023, 4033, 4040, 4042, 4043],
  12743. [4030, 4032, 4033, 4042, 4043],
  12744. [4023, 4033, 4040, 4041, 4043],
  12745. [4031, 4032, 4033, 4040, 4043],
  12746. [4030, 4032, 4033, 4041, 4043],
  12747. [4030, 4031, 4033, 4042, 4043],
  12748. [4013, 4040, 4041, 4042, 4043],
  12749. [4030, 4032, 4033, 4040, 4043],
  12750. [4030, 4031, 4033, 4041, 4043],
  12751. [4012, 4040, 4041, 4042, 4043],
  12752. [4030, 4031, 4033, 4040, 4043],
  12753. [4011, 4040, 4041, 4042, 4043],
  12754. [4010, 4040, 4041, 4042, 4043],
  12755. [4023, 4032, 4033, 4042, 4043],
  12756. [4022, 4032, 4033, 4042, 4043],
  12757. [4023, 4032, 4033, 4041, 4043],
  12758. [4021, 4032, 4033, 4042, 4043],
  12759. [4022, 4032, 4033, 4041, 4043],
  12760. [4023, 4030, 4033, 4042, 4043],
  12761. [4023, 4032, 4033, 4040, 4043],
  12762. [4013, 4033, 4040, 4042, 4043],
  12763. [4020, 4032, 4033, 4042, 4043],
  12764. [4021, 4032, 4033, 4041, 4043],
  12765. [4022, 4030, 4033, 4042, 4043],
  12766. [4022, 4032, 4033, 4040, 4043],
  12767. [4023, 4030, 4033, 4041, 4043],
  12768. [4023, 4031, 4033, 4040, 4043],
  12769. [4013, 4033, 4040, 4041, 4043],
  12770. [4020, 4031, 4033, 4042, 4043],
  12771. [4020, 4032, 4033, 4041, 4043],
  12772. [4021, 4030, 4033, 4042, 4043],
  12773. [4021, 4032, 4033, 4040, 4043],
  12774. [4022, 4030, 4033, 4041, 4043],
  12775. [4022, 4031, 4033, 4040, 4043],
  12776. [4023, 4030, 4033, 4040, 4043],
  12777. [4030, 4031, 4032, 4033, 4043],
  12778. [4003, 4040, 4041, 4042, 4043],
  12779. [4020, 4030, 4033, 4042, 4043],
  12780. [4020, 4031, 4033, 4041, 4043],
  12781. [4020, 4032, 4033, 4040, 4043],
  12782. [4021, 4030, 4033, 4041, 4043],
  12783. [4021, 4031, 4033, 4040, 4043],
  12784. [4022, 4030, 4033, 4040, 4043],
  12785. [4030, 4031, 4032, 4033, 4042],
  12786. [4002, 4040, 4041, 4042, 4043],
  12787. [4020, 4030, 4033, 4041, 4043],
  12788. [4020, 4031, 4033, 4040, 4043],
  12789. [4021, 4030, 4033, 4040, 4043],
  12790. [4030, 4031, 4032, 4033, 4041],
  12791. [4001, 4040, 4041, 4042, 4043],
  12792. [4030, 4031, 4032, 4033, 4040],
  12793. [4000, 4040, 4041, 4042, 4043],
  12794. [4013, 4032, 4033, 4042, 4043],
  12795. [4012, 4032, 4033, 4042, 4043],
  12796. [4013, 4032, 4033, 4041, 4043],
  12797. [4023, 4031, 4032, 4033, 4043],
  12798. [4011, 4032, 4033, 4042, 4043],
  12799. [4012, 4032, 4033, 4041, 4043],
  12800. [4013, 4030, 4033, 4042, 4043],
  12801. [4013, 4032, 4033, 4040, 4043],
  12802. [4023, 4030, 4032, 4033, 4043],
  12803. [4003, 4033, 4040, 4042, 4043],
  12804. [4013, 4023, 4040, 4042, 4043],
  12805. [4010, 4032, 4033, 4042, 4043],
  12806. [4011, 4032, 4033, 4041, 4043],
  12807. [4012, 4030, 4033, 4042, 4043],
  12808. [4012, 4032, 4033, 4040, 4043],
  12809. [4013, 4030, 4033, 4041, 4043],
  12810. [4013, 4031, 4033, 4040, 4043],
  12811. [4023, 4030, 4031, 4033, 4043],
  12812. [4003, 4033, 4040, 4041, 4043],
  12813. [4013, 4023, 4040, 4041, 4043],
  12814. [4010, 4031, 4033, 4042, 4043],
  12815. [4010, 4032, 4033, 4041, 4043],
  12816. [4011, 4030, 4033, 4042, 4043],
  12817. [4011, 4032, 4033, 4040, 4043],
  12818. [4012, 4030, 4033, 4041, 4043],
  12819. [4012, 4031, 4033, 4040, 4043],
  12820. [4013, 4030, 4033, 4040, 4043],
  12821. [4010, 4030, 4033, 4042, 4043],
  12822. [4010, 4031, 4033, 4041, 4043],
  12823. [4010, 4032, 4033, 4040, 4043],
  12824. [4011, 4030, 4033, 4041, 4043],
  12825. [4011, 4031, 4033, 4040, 4043],
  12826. [4012, 4030, 4033, 4040, 4043],
  12827. [4010, 4030, 4033, 4041, 4043],
  12828. [4010, 4031, 4033, 4040, 4043],
  12829. [4011, 4030, 4033, 4040, 4043],
  12830. [4003, 4032, 4033, 4042, 4043],
  12831. [4002, 4032, 4033, 4042, 4043],
  12832. [4003, 4032, 4033, 4041, 4043],
  12833. [4013, 4031, 4032, 4033, 4043],
  12834. [4001, 4032, 4033, 4042, 4043],
  12835. [4002, 4032, 4033, 4041, 4043],
  12836. [4003, 4030, 4033, 4042, 4043],
  12837. [4003, 4032, 4033, 4040, 4043],
  12838. [4013, 4030, 4032, 4033, 4043],
  12839. [4003, 4023, 4040, 4042, 4043],
  12840. [4000, 4032, 4033, 4042, 4043],
  12841. [4001, 4032, 4033, 4041, 4043],
  12842. [4002, 4030, 4033, 4042, 4043],
  12843. [4002, 4032, 4033, 4040, 4043],
  12844. [4003, 4030, 4033, 4041, 4043],
  12845. [4003, 4031, 4033, 4040, 4043],
  12846. [4020, 4022, 4023, 4042, 4043],
  12847. [4013, 4030, 4031, 4033, 4043],
  12848. [4003, 4023, 4040, 4041, 4043],
  12849. [4000, 4031, 4033, 4042, 4043],
  12850. [4000, 4032, 4033, 4041, 4043],
  12851. [4001, 4030, 4033, 4042, 4043],
  12852. [4001, 4032, 4033, 4040, 4043],
  12853. [4002, 4030, 4033, 4041, 4043],
  12854. [4002, 4031, 4033, 4040, 4043],
  12855. [4003, 4030, 4033, 4040, 4043],
  12856. [4021, 4022, 4023, 4040, 4043],
  12857. [4020, 4022, 4023, 4041, 4043],
  12858. [4020, 4021, 4023, 4042, 4043],
  12859. [4023, 4030, 4031, 4032, 4033],
  12860. [4000, 4030, 4033, 4042, 4043],
  12861. [4000, 4031, 4033, 4041, 4043],
  12862. [4000, 4032, 4033, 4040, 4043],
  12863. [4001, 4030, 4033, 4041, 4043],
  12864. [4001, 4031, 4033, 4040, 4043],
  12865. [4002, 4030, 4033, 4040, 4043],
  12866. [4020, 4022, 4023, 4040, 4043],
  12867. [4020, 4021, 4023, 4041, 4043],
  12868. [4022, 4030, 4031, 4032, 4033],
  12869. [4000, 4030, 4033, 4041, 4043],
  12870. [4000, 4031, 4033, 4040, 4043],
  12871. [4001, 4030, 4033, 4040, 4043],
  12872. [4020, 4021, 4023, 4040, 4043],
  12873. [4021, 4030, 4031, 4032, 4033],
  12874. [4020, 4030, 4031, 4032, 4033],
  12875. [4003, 4031, 4032, 4033, 4043],
  12876. [4020, 4022, 4023, 4033, 4043],
  12877. [4003, 4030, 4032, 4033, 4043],
  12878. [4003, 4013, 4040, 4042, 4043],
  12879. [4020, 4021, 4023, 4033, 4043],
  12880. [4003, 4030, 4031, 4033, 4043],
  12881. [4003, 4013, 4040, 4041, 4043],
  12882. [4013, 4030, 4031, 4032, 4033],
  12883. [4012, 4030, 4031, 4032, 4033],
  12884. [4011, 4030, 4031, 4032, 4033],
  12885. [4010, 4030, 4031, 4032, 4033],
  12886. [4013, 4023, 4031, 4032, 4033],
  12887. [4013, 4023, 4030, 4032, 4033],
  12888. [4020, 4022, 4023, 4032, 4033],
  12889. [4013, 4023, 4030, 4031, 4033],
  12890. [4021, 4022, 4023, 4030, 4033],
  12891. [4020, 4022, 4023, 4031, 4033],
  12892. [4020, 4021, 4023, 4032, 4033],
  12893. [4020, 4021, 4022, 4023, 4043],
  12894. [4003, 4030, 4031, 4032, 4033],
  12895. [4020, 4022, 4023, 4030, 4033],
  12896. [4020, 4021, 4023, 4031, 4033],
  12897. [4020, 4021, 4022, 4023, 4042],
  12898. [4002, 4030, 4031, 4032, 4033],
  12899. [4020, 4021, 4023, 4030, 4033],
  12900. [4020, 4021, 4022, 4023, 4041],
  12901. [4001, 4030, 4031, 4032, 4033],
  12902. [4020, 4021, 4022, 4023, 4040],
  12903. [4000, 4030, 4031, 4032, 4033],
  12904. [4003, 4023, 4031, 4032, 4033],
  12905. [4013, 4020, 4022, 4023, 4043],
  12906. [4003, 4023, 4030, 4032, 4033],
  12907. [4010, 4012, 4013, 4042, 4043],
  12908. [4013, 4020, 4021, 4023, 4043],
  12909. [4003, 4023, 4030, 4031, 4033],
  12910. [4011, 4012, 4013, 4040, 4043],
  12911. [4010, 4012, 4013, 4041, 4043],
  12912. [4010, 4011, 4013, 4042, 4043],
  12913. [4020, 4021, 4022, 4023, 4033],
  12914. [4010, 4012, 4013, 4040, 4043],
  12915. [4010, 4011, 4013, 4041, 4043],
  12916. [4020, 4021, 4022, 4023, 4032],
  12917. [4010, 4011, 4013, 4040, 4043],
  12918. [4020, 4021, 4022, 4023, 4031],
  12919. [4020, 4021, 4022, 4023, 4030],
  12920. [4003, 4013, 4031, 4032, 4033],
  12921. [4010, 4012, 4013, 4033, 4043],
  12922. [4003, 4020, 4022, 4023, 4043],
  12923. [4013, 4020, 4022, 4023, 4033],
  12924. [4003, 4013, 4030, 4032, 4033],
  12925. [4010, 4011, 4013, 4033, 4043],
  12926. [4003, 4020, 4021, 4023, 4043],
  12927. [4013, 4020, 4021, 4023, 4033],
  12928. [4003, 4013, 4030, 4031, 4033],
  12929. [4010, 4012, 4013, 4023, 4043],
  12930. [4003, 4020, 4022, 4023, 4033],
  12931. [4010, 4012, 4013, 4032, 4033],
  12932. [4010, 4011, 4013, 4023, 4043],
  12933. [4003, 4020, 4021, 4023, 4033],
  12934. [4011, 4012, 4013, 4030, 4033],
  12935. [4010, 4012, 4013, 4031, 4033],
  12936. [4010, 4011, 4013, 4032, 4033],
  12937. [4013, 4020, 4021, 4022, 4023],
  12938. [4010, 4012, 4013, 4030, 4033],
  12939. [4010, 4011, 4013, 4031, 4033],
  12940. [4012, 4020, 4021, 4022, 4023],
  12941. [4010, 4011, 4013, 4030, 4033],
  12942. [4011, 4020, 4021, 4022, 4023],
  12943. [4010, 4020, 4021, 4022, 4023],
  12944. [4010, 4012, 4013, 4023, 4033],
  12945. [4000, 4002, 4003, 4042, 4043],
  12946. [4010, 4011, 4013, 4023, 4033],
  12947. [4001, 4002, 4003, 4040, 4043],
  12948. [4000, 4002, 4003, 4041, 4043],
  12949. [4000, 4001, 4003, 4042, 4043],
  12950. [4010, 4011, 4012, 4013, 4043],
  12951. [4003, 4020, 4021, 4022, 4023],
  12952. [4000, 4002, 4003, 4040, 4043],
  12953. [4000, 4001, 4003, 4041, 4043],
  12954. [4010, 4011, 4012, 4013, 4042],
  12955. [4002, 4020, 4021, 4022, 4023],
  12956. [4000, 4001, 4003, 4040, 4043],
  12957. [4010, 4011, 4012, 4013, 4041],
  12958. [4001, 4020, 4021, 4022, 4023],
  12959. [4010, 4011, 4012, 4013, 4040],
  12960. [4000, 4020, 4021, 4022, 4023],
  12961. [4001, 4002, 4003, 4033, 4043],
  12962. [4000, 4002, 4003, 4033, 4043],
  12963. [4003, 4010, 4012, 4013, 4043],
  12964. [4003, 4013, 4020, 4022, 4023],
  12965. [4000, 4001, 4003, 4033, 4043],
  12966. [4003, 4010, 4011, 4013, 4043],
  12967. [4003, 4013, 4020, 4021, 4023],
  12968. [4010, 4011, 4012, 4013, 4033],
  12969. [4010, 4011, 4012, 4013, 4032],
  12970. [4010, 4011, 4012, 4013, 4031],
  12971. [4010, 4011, 4012, 4013, 4030],
  12972. [4001, 4002, 4003, 4023, 4043],
  12973. [4000, 4002, 4003, 4023, 4043],
  12974. [4003, 4010, 4012, 4013, 4033],
  12975. [4000, 4002, 4003, 4032, 4033],
  12976. [4000, 4001, 4003, 4023, 4043],
  12977. [4003, 4010, 4011, 4013, 4033],
  12978. [4001, 4002, 4003, 4030, 4033],
  12979. [4000, 4002, 4003, 4031, 4033],
  12980. [4000, 4001, 4003, 4032, 4033],
  12981. [4010, 4011, 4012, 4013, 4023],
  12982. [4000, 4002, 4003, 4030, 4033],
  12983. [4000, 4001, 4003, 4031, 4033],
  12984. [4010, 4011, 4012, 4013, 4022],
  12985. [4000, 4001, 4003, 4030, 4033],
  12986. [4010, 4011, 4012, 4013, 4021],
  12987. [4010, 4011, 4012, 4013, 4020],
  12988. [4001, 4002, 4003, 4013, 4043],
  12989. [4001, 4002, 4003, 4023, 4033],
  12990. [4000, 4002, 4003, 4013, 4043],
  12991. [4000, 4002, 4003, 4023, 4033],
  12992. [4003, 4010, 4012, 4013, 4023],
  12993. [4000, 4001, 4003, 4013, 4043],
  12994. [4000, 4001, 4003, 4023, 4033],
  12995. [4003, 4010, 4011, 4013, 4023],
  12996. [4001, 4002, 4003, 4013, 4033],
  12997. [4000, 4002, 4003, 4013, 4033],
  12998. [4000, 4001, 4003, 4013, 4033],
  12999. [4000, 4001, 4002, 4003, 4043],
  13000. [4003, 4010, 4011, 4012, 4013],
  13001. [4000, 4001, 4002, 4003, 4042],
  13002. [4002, 4010, 4011, 4012, 4013],
  13003. [4000, 4001, 4002, 4003, 4041],
  13004. [4001, 4010, 4011, 4012, 4013],
  13005. [4000, 4001, 4002, 4003, 4040],
  13006. [4000, 4010, 4011, 4012, 4013],
  13007. [4001, 4002, 4003, 4013, 4023],
  13008. [4000, 4002, 4003, 4013, 4023],
  13009. [4000, 4001, 4003, 4013, 4023],
  13010. [4000, 4001, 4002, 4003, 4033],
  13011. [4000, 4001, 4002, 4003, 4032],
  13012. [4000, 4001, 4002, 4003, 4031],
  13013. [4000, 4001, 4002, 4003, 4030],
  13014. [4000, 4001, 4002, 4003, 4023],
  13015. [4000, 4001, 4002, 4003, 4022],
  13016. [4000, 4001, 4002, 4003, 4021],
  13017. [4000, 4001, 4002, 4003, 4020],
  13018. [4000, 4001, 4002, 4003, 4013],
  13019. [4000, 4001, 4002, 4003, 4012],
  13020. [4000, 4001, 4002, 4003, 4011],
  13021. [4000, 4001, 4002, 4003, 4010],
  13022. ].filter((p) => p.includes(this.mandatoryId));
  13023.  
  13024. const bestPack = {
  13025. pack: packs[0],
  13026. winRate: 0,
  13027. countBattle: 0,
  13028. id: 0,
  13029. };
  13030.  
  13031. for (const id in packs) {
  13032. const pack = packs[id];
  13033. const attackers = this.maxUpgrade.filter((e) => pack.includes(e.id)).reduce((obj, e) => ({ ...obj, [e.id]: e }), {});
  13034. const battle = {
  13035. attackers,
  13036. defenders: [enemieHeroes],
  13037. type: 'brawl_titan',
  13038. };
  13039. const isRandom = this.isRandomBattle(battle);
  13040. const stat = {
  13041. count: 0,
  13042. win: 0,
  13043. winRate: 0,
  13044. };
  13045. for (let i = 1; i <= 20; i++) {
  13046. battle.seed = Math.floor(Date.now() / 1000) + Math.random() * 1000;
  13047. const result = await Calc(battle);
  13048. stat.win += result.result.win;
  13049. stat.count += 1;
  13050. stat.winRate = stat.win / stat.count;
  13051. if (!isRandom || (i >= 2 && stat.winRate < 0.65) || (i >= 10 && stat.winRate == 1)) {
  13052. break;
  13053. }
  13054. }
  13055.  
  13056. if (!isRandom && stat.win) {
  13057. return {
  13058. favor: {},
  13059. heroes: pack,
  13060. };
  13061. }
  13062. if (stat.winRate > 0.85) {
  13063. return {
  13064. favor: {},
  13065. heroes: pack,
  13066. };
  13067. }
  13068. if (stat.winRate > bestPack.winRate) {
  13069. bestPack.countBattle = stat.count;
  13070. bestPack.winRate = stat.winRate;
  13071. bestPack.pack = pack;
  13072. bestPack.id = id;
  13073. }
  13074. }
  13075.  
  13076. //console.log(bestPack.id, bestPack.pack, bestPack.winRate, bestPack.countBattle);
  13077. return {
  13078. favor: {},
  13079. heroes: bestPack.pack,
  13080. };
  13081. }
  13082.  
  13083. isRandomPack(pack) {
  13084. const ids = Object.keys(pack);
  13085. return ids.includes('4023') || ids.includes('4021');
  13086. }
  13087.  
  13088. isRandomBattle(battle) {
  13089. return this.isRandomPack(battle.attackers) || this.isRandomPack(battle.defenders[0]);
  13090. }
  13091.  
  13092. async updateHeroesPack(enemieHeroes) {
  13093. 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}}}];
  13094.  
  13095. const bestPack = {
  13096. pack: packs[0],
  13097. countWin: 0,
  13098. }
  13099.  
  13100. for (const pack of packs) {
  13101. const attackers = pack.attackers;
  13102. const battle = {
  13103. attackers,
  13104. defenders: [enemieHeroes],
  13105. type: 'brawl',
  13106. };
  13107.  
  13108. let countWinBattles = 0;
  13109. let countTestBattle = 10;
  13110. for (let i = 0; i < countTestBattle; i++) {
  13111. battle.seed = Math.floor(Date.now() / 1000) + Math.random() * 1000;
  13112. const result = await Calc(battle);
  13113. if (result.result.win) {
  13114. countWinBattles++;
  13115. }
  13116. if (countWinBattles > 7) {
  13117. console.log(pack)
  13118. return pack.args;
  13119. }
  13120. }
  13121. if (countWinBattles > bestPack.countWin) {
  13122. bestPack.countWin = countWinBattles;
  13123. bestPack.pack = pack.args;
  13124. }
  13125. }
  13126.  
  13127. console.log(bestPack);
  13128. return bestPack.pack;
  13129. }
  13130.  
  13131. async questFarm() {
  13132. const calls = [this.callBrawlQuestFarm];
  13133. const result = await Send(JSON.stringify({ calls }));
  13134. return result.results[0].result.response;
  13135. }
  13136.  
  13137. async getBrawlInfo() {
  13138. const data = await Send(JSON.stringify({
  13139. calls: [
  13140. this.callUserGetInfo,
  13141. this.callBrawlQuestGetInfo,
  13142. this.callBrawlFindEnemies,
  13143. this.callTeamGetMaxUpgrade,
  13144. this.callBrawlGetInfo,
  13145. ]
  13146. }));
  13147.  
  13148. let attempts = data.results[0].result.response.refillable.find(n => n.id == 48);
  13149.  
  13150. const maxUpgrade = data.results[3].result.response;
  13151. const maxHero = Object.values(maxUpgrade.hero);
  13152. const maxTitan = Object.values(maxUpgrade.titan);
  13153. const maxPet = Object.values(maxUpgrade.pet);
  13154. this.maxUpgrade = [...maxHero, ...maxPet, ...maxTitan];
  13155.  
  13156. this.info = data.results[4].result.response;
  13157. this.mandatoryId = lib.data.brawl.promoHero[this.info.id].promoHero;
  13158. return {
  13159. attempts: attempts.amount,
  13160. questInfo: data.results[1].result.response,
  13161. findEnemies: data.results[2].result.response,
  13162. }
  13163. }
  13164.  
  13165. /**
  13166. * Carrying out a fight
  13167. *
  13168. * Проведение боя
  13169. */
  13170. async battle(userId) {
  13171. this.stats.count++;
  13172. const battle = await this.startBattle(userId, this.args);
  13173. const result = await Calc(battle);
  13174. console.log(result.result);
  13175. if (result.result.win) {
  13176. this.stats.win++;
  13177. } else {
  13178. this.stats.loss++;
  13179. if (!this.info.boughtEndlessLivesToday) {
  13180. this.attempts--;
  13181. }
  13182. }
  13183. return await this.endBattle(result);
  13184. // return await this.cancelBattle(result);
  13185. }
  13186.  
  13187. /**
  13188. * Starts a fight
  13189. *
  13190. * Начинает бой
  13191. */
  13192. async startBattle(userId, args) {
  13193. const call = {
  13194. name: "brawl_startBattle",
  13195. args,
  13196. ident: "brawl_startBattle"
  13197. }
  13198. call.args.userId = userId;
  13199. const calls = [call];
  13200. const result = await Send(JSON.stringify({ calls }));
  13201. return result.results[0].result.response;
  13202. }
  13203.  
  13204. cancelBattle(battle) {
  13205. const fixBattle = function (heroes) {
  13206. for (const ids in heroes) {
  13207. const hero = heroes[ids];
  13208. hero.energy = random(1, 999);
  13209. if (hero.hp > 0) {
  13210. hero.hp = random(1, hero.hp);
  13211. }
  13212. }
  13213. }
  13214. fixBattle(battle.progress[0].attackers.heroes);
  13215. fixBattle(battle.progress[0].defenders.heroes);
  13216. return this.endBattle(battle);
  13217. }
  13218.  
  13219. /**
  13220. * Ends the fight
  13221. *
  13222. * Заканчивает бой
  13223. */
  13224. async endBattle(battle) {
  13225. battle.progress[0].attackers.input = ['auto', 0, 0, 'auto', 0, 0];
  13226. const calls = [{
  13227. name: "brawl_endBattle",
  13228. args: {
  13229. result: battle.result,
  13230. progress: battle.progress
  13231. },
  13232. ident: "brawl_endBattle"
  13233. },
  13234. this.callBrawlQuestGetInfo,
  13235. this.callBrawlFindEnemies,
  13236. ];
  13237. const result = await Send(JSON.stringify({ calls }));
  13238. return result.results;
  13239. }
  13240.  
  13241. end(endReason) {
  13242. setIsCancalBattle(true);
  13243. isBrawlsAutoStart = false;
  13244. setProgress(endReason, true);
  13245. console.log(endReason);
  13246. this.resolve();
  13247. }
  13248. }
  13249.  
  13250. this.HWHClasses.executeBrawls = executeBrawls;
  13251.  
  13252. /**
  13253. * Runs missions from the company on a specified list
  13254. * Выполняет миссии из компании по списку
  13255. * @param {Array} missions [{id: 25, times: 3}, {id: 45, times: 30}]
  13256. * @param {Boolean} isRaids выполнять миссии рейдом
  13257. * @returns
  13258. */
  13259. function testCompany(missions, isRaids = false) {
  13260. const { ExecuteCompany } = HWHClasses;
  13261. return new Promise((resolve, reject) => {
  13262. const tower = new ExecuteCompany(resolve, reject);
  13263. tower.start(missions, isRaids);
  13264. });
  13265. }
  13266.  
  13267. /**
  13268. * Fulfilling company missions
  13269. * Выполнение миссий компании
  13270. */
  13271. class ExecuteCompany {
  13272. constructor(resolve, reject) {
  13273. this.resolve = resolve;
  13274. this.reject = reject;
  13275. this.missionsIds = [];
  13276. this.currentNum = 0;
  13277. this.isRaid = false;
  13278. this.currentTimes = 0;
  13279.  
  13280. this.argsMission = {
  13281. id: 0,
  13282. heroes: [],
  13283. favor: {},
  13284. };
  13285. }
  13286.  
  13287. async start(missionIds, isRaids) {
  13288. this.missionsIds = missionIds;
  13289. this.isRaid = isRaids;
  13290. const data = await Caller.send(['teamGetAll', 'teamGetFavor']);
  13291. this.startCompany(data);
  13292. }
  13293.  
  13294. startCompany(data) {
  13295. const [teamGetAll, teamGetFavor] = data;
  13296.  
  13297. this.argsMission.heroes = teamGetAll.mission.filter((id) => id < 6000);
  13298. this.argsMission.favor = teamGetFavor.mission;
  13299.  
  13300. const pet = teamGetAll.mission.filter((id) => id >= 6000).pop();
  13301. if (pet) {
  13302. this.argsMission.pet = pet;
  13303. }
  13304.  
  13305. this.checkStat();
  13306. }
  13307.  
  13308. checkStat() {
  13309. if (!this.missionsIds[this.currentNum].times) {
  13310. this.currentNum++;
  13311. }
  13312.  
  13313. if (this.currentNum === this.missionsIds.length) {
  13314. this.endCompany('EndCompany');
  13315. return;
  13316. }
  13317.  
  13318. this.argsMission.id = this.missionsIds[this.currentNum].id;
  13319. this.currentTimes = this.missionsIds[this.currentNum].times;
  13320. setProgress('Сompany: ' + this.argsMission.id + ' - ' + this.currentTimes, false);
  13321. if (this.isRaid) {
  13322. this.missionRaid();
  13323. } else {
  13324. this.missionStart();
  13325. }
  13326. }
  13327.  
  13328. async missionRaid() {
  13329. try {
  13330. await Caller.send({
  13331. name: 'missionRaid',
  13332. args: {
  13333. id: this.argsMission.id,
  13334. times: this.currentTimes,
  13335. },
  13336. });
  13337. } catch (error) {
  13338. console.warn(error);
  13339. }
  13340.  
  13341. this.missionsIds[this.currentNum].times = 0;
  13342. this.checkStat();
  13343. }
  13344.  
  13345. async missionStart() {
  13346. this.lastMissionBattleStart = Date.now();
  13347. let result = null;
  13348. try {
  13349. result = await Caller.send({
  13350. name: 'missionStart',
  13351. args: this.argsMission,
  13352. });
  13353. } catch (error) {
  13354. console.warn(error);
  13355. this.endCompany('missionStartError', error['error']);
  13356. return;
  13357. }
  13358. this.missionEnd(await Calc(result));
  13359. }
  13360.  
  13361. async missionEnd(r) {
  13362. const timer = r.battleTimer;
  13363. await countdownTimer(timer, 'Сompany: ' + this.argsMission.id + ' - ' + this.currentTimes);
  13364.  
  13365. try {
  13366. await Caller.send({
  13367. name: 'missionEnd',
  13368. args: {
  13369. id: this.argsMission.id,
  13370. result: r.result,
  13371. progress: r.progress,
  13372. },
  13373. });
  13374. } catch (error) {
  13375. this.endCompany('missionEndError', error);
  13376. return;
  13377. }
  13378.  
  13379. this.missionsIds[this.currentNum].times--;
  13380. this.checkStat();
  13381. }
  13382.  
  13383. endCompany(reason, info) {
  13384. setProgress('Сompany completed!', true);
  13385. console.log(reason, info);
  13386. this.resolve();
  13387. }
  13388. }
  13389.  
  13390. this.HWHClasses.ExecuteCompany = ExecuteCompany;
  13391. })();
  13392.  
  13393. /**
  13394. * TODO:
  13395. * Получение всех уровней при сборе всех наград (квест на титанит и на энку) +-
  13396. * Добивание на арене титанов
  13397. * Закрытие окошек по Esc +-
  13398. * Починить работу скрипта на уровне команды ниже 10 +-
  13399. * Написать номальную синхронизацию
  13400. * Запрет сбора квестов и отправки экспеиций в промежуток между локальным обновлением и глобальным обновлением дня
  13401. * Улучшение боев
  13402. */