HeroWarsHelper

Automation of actions for the game Hero Wars

当前为 2025-02-24 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name HeroWarsHelper
  3. // @name:en HeroWarsHelper
  4. // @name:ru HeroWarsHelper
  5. // @namespace HeroWarsHelper
  6. // @version 2.322
  7. // @description Automation of actions for the game Hero Wars
  8. // @description:en Automation of actions for the game Hero Wars
  9. // @description:ru Автоматизация действий для игры Хроники Хаоса
  10. // @author ZingerY
  11. // @license Copyright ZingerY
  12. // @homepage https://zingery.ru/scripts/HeroWarsHelper.user.js
  13. // @icon https://zingery.ru/scripts/VaultBoyIco16.ico
  14. // @icon64 https://zingery.ru/scripts/VaultBoyIco64.png
  15. // @match https://www.hero-wars.com/*
  16. // @match https://apps-1701433570146040.apps.fbsbx.com/*
  17. // @run-at document-start
  18. // ==/UserScript==
  19.  
  20. (function() {
  21. /**
  22. * Start script
  23. *
  24. * Стартуем скрипт
  25. */
  26. console.log('%cStart ' + GM_info.script.name + ', v' + GM_info.script.version + ' by ' + GM_info.script.author, 'color: red');
  27. /**
  28. * Script info
  29. *
  30. * Информация о скрипте
  31. */
  32. this.scriptInfo = (({name, version, author, homepage, lastModified}, updateUrl) =>
  33. ({name, version, author, homepage, lastModified, updateUrl}))
  34. (GM_info.script, GM_info.scriptUpdateURL);
  35. this.GM_info = GM_info;
  36. /**
  37. * Information for completing daily quests
  38. *
  39. * Информация для выполнения ежендевных квестов
  40. */
  41. const questsInfo = {};
  42. /**
  43. * Is the game data loaded
  44. *
  45. * Загружены ли данные игры
  46. */
  47. let isLoadGame = false;
  48. /**
  49. * Headers of the last request
  50. *
  51. * Заголовки последнего запроса
  52. */
  53. let lastHeaders = {};
  54. /**
  55. * Information about sent gifts
  56. *
  57. * Информация об отправленных подарках
  58. */
  59. let freebieCheckInfo = null;
  60. /**
  61. * missionTimer
  62. *
  63. * missionTimer
  64. */
  65. let missionBattle = null;
  66. /**
  67. * User data
  68. *
  69. * Данные пользователя
  70. */
  71. let userInfo;
  72. this.isTimeBetweenNewDays = function () {
  73. if (userInfo.timeZone <= 3) {
  74. return false;
  75. }
  76. const nextDayTs = new Date(userInfo.nextDayTs * 1e3);
  77. const nextServerDayTs = new Date(userInfo.nextServerDayTs * 1e3);
  78. if (nextDayTs > nextServerDayTs) {
  79. nextDayTs.setDate(nextDayTs.getDate() - 1);
  80. }
  81. const now = Date.now();
  82. if (now > nextDayTs && now < nextServerDayTs) {
  83. return true;
  84. }
  85. return false;
  86. };
  87.  
  88. function getUserInfo() {
  89. return userInfo;
  90. }
  91. /**
  92. * Original methods for working with AJAX
  93. *
  94. * Оригинальные методы для работы с AJAX
  95. */
  96. const original = {
  97. open: XMLHttpRequest.prototype.open,
  98. send: XMLHttpRequest.prototype.send,
  99. setRequestHeader: XMLHttpRequest.prototype.setRequestHeader,
  100. SendWebSocket: WebSocket.prototype.send,
  101. fetch: fetch,
  102. };
  103.  
  104. // Sentry blocking
  105. // Блокировка наблюдателя
  106. this.fetch = function (url, options) {
  107. /**
  108. * Checking URL for blocking
  109. * Проверяем URL на блокировку
  110. */
  111. if (url.includes('sentry.io')) {
  112. console.log('%cFetch blocked', 'color: red');
  113. console.log(url, options);
  114. const body = {
  115. id: md5(Date.now()),
  116. };
  117. let info = {};
  118. try {
  119. info = JSON.parse(options.body);
  120. } catch (e) {}
  121. if (info.event_id) {
  122. body.id = info.event_id;
  123. }
  124. /**
  125. * Mock response for blocked URL
  126. *
  127. * Мокаем ответ для заблокированного URL
  128. */
  129. const mockResponse = new Response('Custom blocked response', {
  130. status: 200,
  131. headers: { 'Content-Type': 'application/json' },
  132. body,
  133. });
  134. return Promise.resolve(mockResponse);
  135. } else {
  136. /**
  137. * Call the original fetch function for all other URLs
  138. * Вызываем оригинальную функцию fetch для всех других URL
  139. */
  140. return original.fetch.apply(this, arguments);
  141. }
  142. };
  143.  
  144. /**
  145. * Decoder for converting byte data to JSON string
  146. *
  147. * Декодер для перобразования байтовых данных в JSON строку
  148. */
  149. const decoder = new TextDecoder("utf-8");
  150. /**
  151. * Stores a history of requests
  152. *
  153. * Хранит историю запросов
  154. */
  155. let requestHistory = {};
  156. /**
  157. * URL for API requests
  158. *
  159. * URL для запросов к API
  160. */
  161. let apiUrl = '';
  162.  
  163. /**
  164. * Connecting to the game code
  165. *
  166. * Подключение к коду игры
  167. */
  168. this.cheats = new hackGame();
  169. /**
  170. * The function of calculating the results of the battle
  171. *
  172. * Функция расчета результатов боя
  173. */
  174. this.BattleCalc = cheats.BattleCalc;
  175. /**
  176. * Sending a request available through the console
  177. *
  178. * Отправка запроса доступная через консоль
  179. */
  180. this.SendRequest = send;
  181. /**
  182. * Simple combat calculation available through the console
  183. *
  184. * Простой расчет боя доступный через консоль
  185. */
  186. this.Calc = function (data) {
  187. const type = getBattleType(data?.type);
  188. return new Promise((resolve, reject) => {
  189. try {
  190. BattleCalc(data, type, resolve);
  191. } catch (e) {
  192. reject(e);
  193. }
  194. })
  195. }
  196. /**
  197. * Short asynchronous request
  198. * Usage example (returns information about a character):
  199. * const userInfo = await Send('{"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}')
  200. *
  201. * Короткий асинхронный запрос
  202. * Пример использования (возвращает информацию о персонаже):
  203. * const userInfo = await Send('{"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}')
  204. */
  205. this.Send = function (json, pr) {
  206. return new Promise((resolve, reject) => {
  207. try {
  208. send(json, resolve, pr);
  209. } catch (e) {
  210. reject(e);
  211. }
  212. })
  213. }
  214.  
  215. this.xyz = (({ name, version, author }) => ({ name, version, author }))(GM_info.script);
  216. const i18nLangData = {
  217. /* English translation by BaBa */
  218. en: {
  219. /* Checkboxes */
  220. SKIP_FIGHTS: 'Skip battle',
  221. SKIP_FIGHTS_TITLE: 'Skip battle in Outland and the arena of the titans, auto-pass in the tower and campaign',
  222. ENDLESS_CARDS: 'Infinite cards',
  223. ENDLESS_CARDS_TITLE: 'Disable Divination Cards wasting',
  224. AUTO_EXPEDITION: 'Auto Expedition',
  225. AUTO_EXPEDITION_TITLE: 'Auto-sending expeditions',
  226. CANCEL_FIGHT: 'Cancel battle',
  227. CANCEL_FIGHT_TITLE: 'Ability to cancel manual combat on GW, CoW and Asgard',
  228. GIFTS: 'Gifts',
  229. GIFTS_TITLE: 'Collect gifts automatically',
  230. BATTLE_RECALCULATION: 'Battle recalculation',
  231. BATTLE_RECALCULATION_TITLE: 'Preliminary calculation of the battle',
  232. QUANTITY_CONTROL: 'Quantity control',
  233. QUANTITY_CONTROL_TITLE: 'Ability to specify the number of opened "lootboxes"',
  234. REPEAT_CAMPAIGN: 'Repeat missions',
  235. REPEAT_CAMPAIGN_TITLE: 'Auto-repeat battles in the campaign',
  236. DISABLE_DONAT: 'Disable donation',
  237. DISABLE_DONAT_TITLE: 'Removes all donation offers',
  238. DAILY_QUESTS: 'Quests',
  239. DAILY_QUESTS_TITLE: 'Complete daily quests',
  240. AUTO_QUIZ: 'AutoQuiz',
  241. AUTO_QUIZ_TITLE: 'Automatically receive correct answers to quiz questions',
  242. SECRET_WEALTH_CHECKBOX: 'Automatic purchase in the store "Secret Wealth" when entering the game',
  243. HIDE_SERVERS: 'Collapse servers',
  244. HIDE_SERVERS_TITLE: 'Hide unused servers',
  245. /* Input fields */
  246. HOW_MUCH_TITANITE: 'How much titanite to farm',
  247. COMBAT_SPEED: 'Combat Speed Multiplier',
  248. NUMBER_OF_TEST: 'Number of test fights',
  249. NUMBER_OF_AUTO_BATTLE: 'Number of auto-battle attempts',
  250. /* Buttons */
  251. RUN_SCRIPT: 'Run the',
  252. TO_DO_EVERYTHING: 'Do All',
  253. TO_DO_EVERYTHING_TITLE: 'Perform multiple actions of your choice',
  254. OUTLAND: 'Outland',
  255. OUTLAND_TITLE: 'Collect Outland',
  256. TITAN_ARENA: 'ToE',
  257. TITAN_ARENA_TITLE: 'Complete the titan arena',
  258. DUNGEON: 'Dungeon',
  259. DUNGEON_TITLE: 'Go through the dungeon',
  260. SEER: 'Seer',
  261. SEER_TITLE: 'Roll the Seer',
  262. TOWER: 'Tower',
  263. TOWER_TITLE: 'Pass the tower',
  264. EXPEDITIONS: 'Expeditions',
  265. EXPEDITIONS_TITLE: 'Sending and collecting expeditions',
  266. SYNC: 'Sync',
  267. SYNC_TITLE: 'Partial synchronization of game data without reloading the page',
  268. ARCHDEMON: 'Archdemon',
  269. FURNACE_OF_SOULS: 'Furnace of souls',
  270. ARCHDEMON_TITLE: 'Hitting kills and collecting rewards',
  271. ESTER_EGGS: 'Easter eggs',
  272. ESTER_EGGS_TITLE: 'Collect all Easter eggs or rewards',
  273. REWARDS: 'Rewards',
  274. REWARDS_TITLE: 'Collect all quest rewards',
  275. MAIL: 'Mail',
  276. MAIL_TITLE: 'Collect all mail, except letters with energy and charges of the portal',
  277. MINIONS: 'Minions',
  278. MINIONS_TITLE: 'Attack minions with saved packs',
  279. ADVENTURE: 'Adventure',
  280. ADVENTURE_TITLE: 'Passes the adventure along the specified route',
  281. STORM: 'Storm',
  282. STORM_TITLE: 'Passes the Storm along the specified route',
  283. SANCTUARY: 'Sanctuary',
  284. SANCTUARY_TITLE: 'Fast travel to Sanctuary',
  285. GUILD_WAR: 'Guild War',
  286. GUILD_WAR_TITLE: 'Fast travel to Guild War',
  287. SECRET_WEALTH: 'Secret Wealth',
  288. SECRET_WEALTH_TITLE: 'Buy something in the store "Secret Wealth"',
  289. /* Misc */
  290. BOTTOM_URLS:
  291. '<a href="https://t.me/+0oMwICyV1aQ1MDAy" target="_blank" title="Telegram"><svg width="20" height="20" style="margin:2px" viewBox="0 0 1e3 1e3" xmlns="http://www.w3.org/2000/svg"><defs><linearGradient id="a" x1="50%" x2="50%" y2="99.258%"><stop stop-color="#2AABEE" offset="0"/><stop stop-color="#229ED9" offset="1"/></linearGradient></defs><g fill-rule="evenodd"><circle cx="500" cy="500" r="500" fill="url(#a)"/><path d="m226.33 494.72c145.76-63.505 242.96-105.37 291.59-125.6 138.86-57.755 167.71-67.787 186.51-68.119 4.1362-0.072862 13.384 0.95221 19.375 5.8132 5.0584 4.1045 6.4501 9.6491 7.1161 13.541 0.666 3.8915 1.4953 12.756 0.83608 19.683-7.5246 79.062-40.084 270.92-56.648 359.47-7.0089 37.469-20.81 50.032-34.17 51.262-29.036 2.6719-51.085-19.189-79.207-37.624-44.007-28.847-68.867-46.804-111.58-74.953-49.366-32.531-17.364-50.411 10.769-79.631 7.3626-7.6471 135.3-124.01 137.77-134.57 0.30968-1.3202 0.59708-6.2414-2.3265-8.8399s-7.2385-1.7099-10.352-1.0032c-4.4137 1.0017-74.715 47.468-210.9 139.4-19.955 13.702-38.029 20.379-54.223 20.029-17.853-0.3857-52.194-10.094-77.723-18.393-31.313-10.178-56.199-15.56-54.032-32.846 1.1287-9.0037 13.528-18.212 37.197-27.624z" fill="#fff"/></g></svg></a><a href="https://www.patreon.com/HeroWarsUserScripts" target="_blank" title="Patreon"><svg width="20" height="20" viewBox="0 0 1080 1080" xmlns="http://www.w3.org/2000/svg"><g fill="#FFF" stroke="None"><path d="m1033 324.45c-0.19-137.9-107.59-250.92-233.6-291.7-156.48-50.64-362.86-43.3-512.28 27.2-181.1 85.46-237.99 272.66-240.11 459.36-1.74 153.5 13.58 557.79 241.62 560.67 169.44 2.15 194.67-216.18 273.07-321.33 55.78-74.81 127.6-95.94 216.01-117.82 151.95-37.61 255.51-157.53 255.29-316.38z"/></g></svg></a>',
  292. GIFTS_SENT: 'Gifts sent!',
  293. DO_YOU_WANT: 'Do you really want to do this?',
  294. BTN_RUN: 'Run',
  295. BTN_CANCEL: 'Cancel',
  296. BTN_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 adventure',
  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. if (lang == 'ru') {
  968. return lang;
  969. }
  970. return 'en';
  971. }
  972.  
  973. this.I18N = function (constant, replace) {
  974. const selectLang = getLang();
  975. if (constant && constant in i18nLangData[selectLang]) {
  976. const result = i18nLangData[selectLang][constant];
  977. if (replace) {
  978. return result.sprintf(replace);
  979. }
  980. return result;
  981. }
  982. return `% ${constant} %`;
  983. };
  984.  
  985. String.prototype.sprintf = String.prototype.sprintf ||
  986. function () {
  987. "use strict";
  988. var str = this.toString();
  989. if (arguments.length) {
  990. var t = typeof arguments[0];
  991. var key;
  992. var args = ("string" === t || "number" === t) ?
  993. Array.prototype.slice.call(arguments)
  994. : arguments[0];
  995.  
  996. for (key in args) {
  997. str = str.replace(new RegExp("\\{" + key + "\\}", "gi"), args[key]);
  998. }
  999. }
  1000.  
  1001. return str;
  1002. };
  1003.  
  1004. /**
  1005. * Checkboxes
  1006. *
  1007. * Чекбоксы
  1008. */
  1009. const checkboxes = {
  1010. passBattle: {
  1011. label: I18N('SKIP_FIGHTS'),
  1012. cbox: null,
  1013. title: I18N('SKIP_FIGHTS_TITLE'),
  1014. default: false,
  1015. },
  1016. sendExpedition: {
  1017. label: I18N('AUTO_EXPEDITION'),
  1018. cbox: null,
  1019. title: I18N('AUTO_EXPEDITION_TITLE'),
  1020. default: false,
  1021. },
  1022. cancelBattle: {
  1023. label: I18N('CANCEL_FIGHT'),
  1024. cbox: null,
  1025. title: I18N('CANCEL_FIGHT_TITLE'),
  1026. default: false,
  1027. },
  1028. preCalcBattle: {
  1029. label: I18N('BATTLE_RECALCULATION'),
  1030. cbox: null,
  1031. title: I18N('BATTLE_RECALCULATION_TITLE'),
  1032. default: false,
  1033. },
  1034. countControl: {
  1035. label: I18N('QUANTITY_CONTROL'),
  1036. cbox: null,
  1037. title: I18N('QUANTITY_CONTROL_TITLE'),
  1038. default: true,
  1039. },
  1040. repeatMission: {
  1041. label: I18N('REPEAT_CAMPAIGN'),
  1042. cbox: null,
  1043. title: I18N('REPEAT_CAMPAIGN_TITLE'),
  1044. default: false,
  1045. },
  1046. noOfferDonat: {
  1047. label: I18N('DISABLE_DONAT'),
  1048. cbox: null,
  1049. title: I18N('DISABLE_DONAT_TITLE'),
  1050. /**
  1051. * A crutch to get the field before getting the character id
  1052. *
  1053. * Костыль чтоб получать поле до получения id персонажа
  1054. */
  1055. default: (() => {
  1056. $result = false;
  1057. try {
  1058. $result = JSON.parse(localStorage[GM_info.script.name + ':noOfferDonat']);
  1059. } catch (e) {
  1060. $result = false;
  1061. }
  1062. return $result || false;
  1063. })(),
  1064. },
  1065. dailyQuests: {
  1066. label: I18N('DAILY_QUESTS'),
  1067. cbox: null,
  1068. title: I18N('DAILY_QUESTS_TITLE'),
  1069. default: false,
  1070. },
  1071. // Потасовки
  1072. autoBrawls: {
  1073. label: I18N('BRAWLS'),
  1074. cbox: null,
  1075. title: I18N('BRAWLS_TITLE'),
  1076. default: (() => {
  1077. $result = false;
  1078. try {
  1079. $result = JSON.parse(localStorage[GM_info.script.name + ':autoBrawls']);
  1080. } catch (e) {
  1081. $result = false;
  1082. }
  1083. return $result || false;
  1084. })(),
  1085. hide: false,
  1086. },
  1087. getAnswer: {
  1088. label: I18N('AUTO_QUIZ'),
  1089. cbox: null,
  1090. title: I18N('AUTO_QUIZ_TITLE'),
  1091. default: false,
  1092. hide: true,
  1093. },
  1094. tryFixIt_v2: {
  1095. label: I18N('BTN_TRY_FIX_IT'),
  1096. cbox: null,
  1097. title: I18N('BTN_TRY_FIX_IT_TITLE'),
  1098. default: false,
  1099. hide: false,
  1100. },
  1101. showErrors: {
  1102. label: I18N('SHOW_ERRORS'),
  1103. cbox: null,
  1104. title: I18N('SHOW_ERRORS_TITLE'),
  1105. default: true,
  1106. },
  1107. buyForGold: {
  1108. label: I18N('BUY_FOR_GOLD'),
  1109. cbox: null,
  1110. title: I18N('BUY_FOR_GOLD_TITLE'),
  1111. default: false,
  1112. },
  1113. hideServers: {
  1114. label: I18N('HIDE_SERVERS'),
  1115. cbox: null,
  1116. title: I18N('HIDE_SERVERS_TITLE'),
  1117. default: false,
  1118. },
  1119. fastSeason: {
  1120. label: I18N('FAST_SEASON'),
  1121. cbox: null,
  1122. title: I18N('FAST_SEASON_TITLE'),
  1123. default: false,
  1124. },
  1125. };
  1126. /**
  1127. * Get checkbox state
  1128. *
  1129. * Получить состояние чекбокса
  1130. */
  1131. function isChecked(checkBox) {
  1132. if (!(checkBox in checkboxes)) {
  1133. return false;
  1134. }
  1135. return checkboxes[checkBox].cbox?.checked;
  1136. }
  1137. /**
  1138. * Input fields
  1139. *
  1140. * Поля ввода
  1141. */
  1142. const inputs = {
  1143. countTitanit: {
  1144. input: null,
  1145. title: I18N('HOW_MUCH_TITANITE'),
  1146. default: 150,
  1147. },
  1148. speedBattle: {
  1149. input: null,
  1150. title: I18N('COMBAT_SPEED'),
  1151. default: 5,
  1152. },
  1153. countTestBattle: {
  1154. input: null,
  1155. title: I18N('NUMBER_OF_TEST'),
  1156. default: 10,
  1157. },
  1158. countAutoBattle: {
  1159. input: null,
  1160. title: I18N('NUMBER_OF_AUTO_BATTLE'),
  1161. default: 10,
  1162. },
  1163. FPS: {
  1164. input: null,
  1165. title: 'FPS',
  1166. default: 60,
  1167. }
  1168. }
  1169. /**
  1170. * Checks the checkbox
  1171. *
  1172. * Поплучить данные поля ввода
  1173. */
  1174. function getInput(inputName) {
  1175. return inputs[inputName]?.input?.value;
  1176. }
  1177.  
  1178. /**
  1179. * Control FPS
  1180. *
  1181. * Контроль FPS
  1182. */
  1183. let nextAnimationFrame = Date.now();
  1184. const oldRequestAnimationFrame = this.requestAnimationFrame;
  1185. this.requestAnimationFrame = async function (e) {
  1186. const FPS = Number(getInput('FPS')) || -1;
  1187. const now = Date.now();
  1188. const delay = nextAnimationFrame - now;
  1189. nextAnimationFrame = Math.max(now, nextAnimationFrame) + Math.min(1e3 / FPS, 1e3);
  1190. if (delay > 0) {
  1191. await new Promise((e) => setTimeout(e, delay));
  1192. }
  1193. oldRequestAnimationFrame(e);
  1194. };
  1195. /**
  1196. * Button List
  1197. *
  1198. * Список кнопочек
  1199. */
  1200. const buttons = {
  1201. getOutland: {
  1202. name: I18N('TO_DO_EVERYTHING'),
  1203. title: I18N('TO_DO_EVERYTHING_TITLE'),
  1204. func: testDoYourBest,
  1205. },
  1206. doActions: {
  1207. name: I18N('ACTIONS'),
  1208. title: I18N('ACTIONS_TITLE'),
  1209. func: async function () {
  1210. const popupButtons = [
  1211. {
  1212. msg: I18N('OUTLAND'),
  1213. result: function () {
  1214. confShow(`${I18N('RUN_SCRIPT')} ${I18N('OUTLAND')}?`, getOutland);
  1215. },
  1216. title: I18N('OUTLAND_TITLE'),
  1217. },
  1218. {
  1219. msg: I18N('TOWER'),
  1220. result: function () {
  1221. confShow(`${I18N('RUN_SCRIPT')} ${I18N('TOWER')}?`, testTower);
  1222. },
  1223. title: I18N('TOWER_TITLE'),
  1224. },
  1225. {
  1226. msg: I18N('EXPEDITIONS'),
  1227. result: function () {
  1228. confShow(`${I18N('RUN_SCRIPT')} ${I18N('EXPEDITIONS')}?`, checkExpedition);
  1229. },
  1230. title: I18N('EXPEDITIONS_TITLE'),
  1231. },
  1232. {
  1233. msg: I18N('MINIONS'),
  1234. result: function () {
  1235. confShow(`${I18N('RUN_SCRIPT')} ${I18N('MINIONS')}?`, testRaidNodes);
  1236. },
  1237. title: I18N('MINIONS_TITLE'),
  1238. },
  1239. {
  1240. msg: I18N('ESTER_EGGS'),
  1241. result: function () {
  1242. confShow(`${I18N('RUN_SCRIPT')} ${I18N('ESTER_EGGS')}?`, offerFarmAllReward);
  1243. },
  1244. title: I18N('ESTER_EGGS_TITLE'),
  1245. },
  1246. {
  1247. msg: I18N('STORM'),
  1248. result: function () {
  1249. testAdventure('solo');
  1250. },
  1251. title: I18N('STORM_TITLE'),
  1252. },
  1253. {
  1254. msg: I18N('REWARDS'),
  1255. result: function () {
  1256. confShow(`${I18N('RUN_SCRIPT')} ${I18N('REWARDS')}?`, questAllFarm);
  1257. },
  1258. title: I18N('REWARDS_TITLE'),
  1259. },
  1260. {
  1261. msg: I18N('MAIL'),
  1262. result: function () {
  1263. confShow(`${I18N('RUN_SCRIPT')} ${I18N('MAIL')}?`, mailGetAll);
  1264. },
  1265. title: I18N('MAIL_TITLE'),
  1266. },
  1267. {
  1268. msg: I18N('SEER'),
  1269. result: function () {
  1270. confShow(`${I18N('RUN_SCRIPT')} ${I18N('SEER')}?`, rollAscension);
  1271. },
  1272. title: I18N('SEER_TITLE'),
  1273. },
  1274. /*
  1275. {
  1276. msg: I18N('NY_GIFTS'),
  1277. result: getGiftNewYear,
  1278. title: I18N('NY_GIFTS_TITLE'),
  1279. },
  1280. */
  1281. ];
  1282. popupButtons.push({ result: false, isClose: true });
  1283. const answer = await popup.confirm(`${I18N('CHOOSE_ACTION')}:`, popupButtons);
  1284. if (typeof answer === 'function') {
  1285. answer();
  1286. }
  1287. },
  1288. },
  1289. doOthers: {
  1290. name: I18N('OTHERS'),
  1291. title: I18N('OTHERS_TITLE'),
  1292. func: async function () {
  1293. const popupButtons = [
  1294. {
  1295. msg: I18N('GET_ENERGY'),
  1296. result: farmStamina,
  1297. title: I18N('GET_ENERGY_TITLE'),
  1298. },
  1299. {
  1300. msg: I18N('ITEM_EXCHANGE'),
  1301. result: fillActive,
  1302. title: I18N('ITEM_EXCHANGE_TITLE'),
  1303. },
  1304. {
  1305. msg: I18N('BUY_SOULS'),
  1306. result: function () {
  1307. confShow(`${I18N('RUN_SCRIPT')} ${I18N('BUY_SOULS')}?`, buyHeroFragments);
  1308. },
  1309. title: I18N('BUY_SOULS_TITLE'),
  1310. },
  1311. {
  1312. msg: I18N('BUY_FOR_GOLD'),
  1313. result: function () {
  1314. confShow(`${I18N('RUN_SCRIPT')} ${I18N('BUY_FOR_GOLD')}?`, buyInStoreForGold);
  1315. },
  1316. title: I18N('BUY_FOR_GOLD_TITLE'),
  1317. },
  1318. {
  1319. msg: I18N('BUY_OUTLAND'),
  1320. result: bossOpenChestPay,
  1321. title: I18N('BUY_OUTLAND_TITLE'),
  1322. },
  1323. {
  1324. msg: I18N('AUTO_RAID_ADVENTURE'),
  1325. result: autoRaidAdventure,
  1326. title: I18N('AUTO_RAID_ADVENTURE_TITLE'),
  1327. },
  1328. {
  1329. msg: I18N('CLAN_STAT'),
  1330. result: clanStatistic,
  1331. title: I18N('CLAN_STAT_TITLE'),
  1332. },
  1333. {
  1334. msg: I18N('EPIC_BRAWL'),
  1335. result: async function () {
  1336. confShow(`${I18N('RUN_SCRIPT')} ${I18N('EPIC_BRAWL')}?`, () => {
  1337. const brawl = new epicBrawl();
  1338. brawl.start();
  1339. });
  1340. },
  1341. title: I18N('EPIC_BRAWL_TITLE'),
  1342. },
  1343. {
  1344. msg: I18N('ARTIFACTS_UPGRADE'),
  1345. result: updateArtifacts,
  1346. title: I18N('ARTIFACTS_UPGRADE_TITLE'),
  1347. },
  1348. {
  1349. msg: I18N('SKINS_UPGRADE'),
  1350. result: updateSkins,
  1351. title: I18N('SKINS_UPGRADE_TITLE'),
  1352. },
  1353. {
  1354. msg: I18N('SEASON_REWARD'),
  1355. result: farmBattlePass,
  1356. title: I18N('SEASON_REWARD_TITLE'),
  1357. },
  1358. {
  1359. msg: I18N('SELL_HERO_SOULS'),
  1360. result: sellHeroSoulsForGold,
  1361. title: I18N('SELL_HERO_SOULS_TITLE'),
  1362. },
  1363. {
  1364. msg: I18N('CHANGE_MAP'),
  1365. result: async function () {
  1366. const maps = Object.values(lib.data.seasonAdventure.list)
  1367. .filter((e) => e.map.cells.length > 2)
  1368. .map((i) => ({
  1369. msg: I18N('MAP_NUM', { num: i.id }),
  1370. result: i.id,
  1371. }));
  1372.  
  1373. const result = await popup.confirm(I18N('SELECT_ISLAND_MAP'), [...maps, { result: false, isClose: true }]);
  1374. if (result) {
  1375. cheats.changeIslandMap(result);
  1376. }
  1377. },
  1378. title: I18N('CHANGE_MAP_TITLE'),
  1379. },
  1380. {
  1381. msg: I18N('HERO_POWER'),
  1382. result: async () => {
  1383. const calls = ['userGetInfo', 'heroGetAll'].map((name) => ({
  1384. name,
  1385. args: {},
  1386. ident: name,
  1387. }));
  1388. const [maxHeroSumPower, heroSumPower] = await Send({ calls }).then((e) => [
  1389. e.results[0].result.response.maxSumPower.heroes,
  1390. Object.values(e.results[1].result.response).reduce((a, e) => a + e.power, 0),
  1391. ]);
  1392. const power = maxHeroSumPower - heroSumPower;
  1393. let msg =
  1394. I18N('MAX_POWER_REACHED', { power: maxHeroSumPower.toLocaleString() }) +
  1395. '<br>' +
  1396. I18N('CURRENT_POWER', { power: heroSumPower.toLocaleString() }) +
  1397. '<br>' +
  1398. I18N('POWER_TO_MAX', { power: power.toLocaleString(), color: power >= 4000 ? 'green' : 'red' });
  1399. await popup.confirm(msg, [{ msg: I18N('BTN_OK'), result: 0 }]);
  1400. },
  1401. title: I18N('HERO_POWER_TITLE'),
  1402. },
  1403. ];
  1404. popupButtons.push({ result: false, isClose: true });
  1405. const answer = await popup.confirm(`${I18N('CHOOSE_ACTION')}:`, popupButtons);
  1406. if (typeof answer === 'function') {
  1407. answer();
  1408. }
  1409. },
  1410. },
  1411. testTitanArena: {
  1412. isCombine: true,
  1413. combineList: [
  1414. {
  1415. text: I18N('TITAN_ARENA'),
  1416. title: I18N('TITAN_ARENA_TITLE'),
  1417. func: function () {
  1418. confShow(`${I18N('RUN_SCRIPT')} ${I18N('TITAN_ARENA')}?`, testTitanArena);
  1419. },
  1420. },
  1421. {
  1422. text: '>>',
  1423. func: cheats.goTitanValley,
  1424. title: I18N('TITAN_VALLEY_TITLE'),
  1425. color: 'green',
  1426. },
  1427. ],
  1428. },
  1429. testDungeon: {
  1430. isCombine: true,
  1431. combineList: [
  1432. {
  1433. text: I18N('DUNGEON'),
  1434. func: function () {
  1435. confShow(`${I18N('RUN_SCRIPT')} ${I18N('DUNGEON')}?`, testDungeon);
  1436. },
  1437. title: I18N('DUNGEON_TITLE'),
  1438. },
  1439. {
  1440. text: '>>',
  1441. func: cheats.goClanIsland,
  1442. title: I18N('GUILD_ISLAND_TITLE'),
  1443. color: 'green',
  1444. },
  1445. ],
  1446. },
  1447. testAdventure: {
  1448. isCombine: true,
  1449. combineList: [
  1450. {
  1451. text: I18N('ADVENTURE'),
  1452. func: testAdventure,
  1453. title: I18N('ADVENTURE_TITLE'),
  1454. },
  1455. {
  1456. text: '>>',
  1457. func: cheats.goSanctuary,
  1458. title: I18N('SANCTUARY_TITLE'),
  1459. color: 'green',
  1460. },
  1461. ],
  1462. },
  1463. // Архидемон
  1464. bossRatingEvent: {
  1465. name: I18N('ARCHDEMON'),
  1466. title: I18N('ARCHDEMON_TITLE'),
  1467. func: function () {
  1468. confShow(`${I18N('RUN_SCRIPT')} ${I18N('ARCHDEMON')}?`, bossRatingEvent);
  1469. },
  1470. hide: true,
  1471. },
  1472. // Горнило душ
  1473. bossRatingEvent: {
  1474. name: I18N('FURNACE_OF_SOULS'),
  1475. title: I18N('ARCHDEMON_TITLE'),
  1476. func: function () {
  1477. confShow(`${I18N('RUN_SCRIPT')} ${I18N('FURNACE_OF_SOULS')}?`, bossRatingEventSouls);
  1478. },
  1479. hide: true,
  1480. },
  1481. rewardsAndMailFarm: {
  1482. name: I18N('REWARDS_AND_MAIL'),
  1483. title: I18N('REWARDS_AND_MAIL_TITLE'),
  1484. func: function () {
  1485. confShow(`${I18N('RUN_SCRIPT')} ${I18N('REWARDS_AND_MAIL')}?`, rewardsAndMailFarm);
  1486. },
  1487. },
  1488. goToClanWar: {
  1489. name: I18N('GUILD_WAR'),
  1490. title: I18N('GUILD_WAR_TITLE'),
  1491. func: cheats.goClanWar,
  1492. },
  1493. dailyQuests: {
  1494. name: I18N('DAILY_QUESTS'),
  1495. title: I18N('DAILY_QUESTS_TITLE'),
  1496. func: async function () {
  1497. const quests = new dailyQuests(
  1498. () => {},
  1499. () => {}
  1500. );
  1501. await quests.autoInit();
  1502. quests.start();
  1503. },
  1504. },
  1505. newDay: {
  1506. name: I18N('SYNC'),
  1507. title: I18N('SYNC_TITLE'),
  1508. func: function () {
  1509. confShow(`${I18N('RUN_SCRIPT')} ${I18N('SYNC')}?`, cheats.refreshGame);
  1510. },
  1511. },
  1512. };
  1513. /**
  1514. * Display buttons
  1515. *
  1516. * Вывести кнопочки
  1517. */
  1518. function addControlButtons() {
  1519. for (let name in buttons) {
  1520. button = buttons[name];
  1521. if (button.hide) {
  1522. continue;
  1523. }
  1524. if (button.isCombine) {
  1525. button['button'] = scriptMenu.addCombinedButton(button.combineList);
  1526. continue;
  1527. }
  1528. button['button'] = scriptMenu.addButton(button.name, button.func, button.title);
  1529. }
  1530. }
  1531. /**
  1532. * Adds links
  1533. *
  1534. * Добавляет ссылки
  1535. */
  1536. function addBottomUrls() {
  1537. scriptMenu.addHeader(I18N('BOTTOM_URLS'));
  1538. }
  1539. /**
  1540. * Stop repetition of the mission
  1541. *
  1542. * Остановить повтор миссии
  1543. */
  1544. let isStopSendMission = false;
  1545. /**
  1546. * There is a repetition of the mission
  1547. *
  1548. * Идет повтор миссии
  1549. */
  1550. let isSendsMission = false;
  1551. /**
  1552. * Data on the past mission
  1553. *
  1554. * Данные о прошедшей мисии
  1555. */
  1556. let lastMissionStart = {}
  1557. /**
  1558. * Start time of the last battle in the company
  1559. *
  1560. * Время начала последнего боя в кампании
  1561. */
  1562. let lastMissionBattleStart = 0;
  1563. /**
  1564. * Data for calculating the last battle with the boss
  1565. *
  1566. * Данные для расчете последнего боя с боссом
  1567. */
  1568. let lastBossBattle = null;
  1569. /**
  1570. * Information about the last battle
  1571. *
  1572. * Данные о прошедшей битве
  1573. */
  1574. let lastBattleArg = {}
  1575. let lastBossBattleStart = null;
  1576. this.addBattleTimer = 4;
  1577. this.invasionTimer = 2500;
  1578. const invasionInfo = {
  1579. buff: 0,
  1580. bossLvl: 130,
  1581. };
  1582. const invasionDataPacks = {
  1583. 130: { buff: 0, pet: 6004, heroes: [58, 48, 16, 65, 59], favor: { 16: 6004, 48: 6001, 58: 6002, 59: 6005, 65: 6000 } },
  1584. 140: { buff: 0, pet: 6006, heroes: [1, 4, 13, 58, 65], favor: { 1: 6001, 4: 6006, 13: 6002, 58: 6005, 65: 6000 } },
  1585. 150: { buff: 0, pet: 6006, heroes: [1, 12, 17, 21, 65], favor: { 1: 6001, 12: 6003, 17: 6006, 21: 6002, 65: 6000 } },
  1586. 160: { buff: 0, pet: 6008, heroes: [12, 21, 34, 58, 65], favor: { 12: 6003, 21: 6006, 34: 6008, 58: 6002, 65: 6001 } },
  1587. 170: { buff: 0, pet: 6005, heroes: [33, 12, 65, 21, 4], favor: { 4: 6001, 12: 6003, 21: 6006, 33: 6008, 65: 6000 } },
  1588. 180: { buff: 20, pet: 6009, heroes: [58, 13, 5, 17, 65], favor: { 5: 6006, 13: 6003, 58: 6005 } },
  1589. 190: { buff: 0, pet: 6006, heroes: [1, 12, 21, 36, 65], favor: { 1: 6004, 12: 6003, 21: 6006, 36: 6005, 65: 6000 } },
  1590. 200: { buff: 0, pet: 6006, heroes: [12, 1, 13, 2, 65], favor: { 2: 6001, 12: 6003, 13: 6006, 65: 6000 } },
  1591. 210: { buff: 15, pet: 6005, heroes: [12, 21, 33, 58, 65], favor: { 12: 6003, 21: 6006, 33: 6008, 58: 6005, 65: 6001 } },
  1592. 220: { buff: 5, pet: 6006, heroes: [58, 13, 7, 34, 65], favor: { 7: 6002, 13: 6008, 34: 6006, 58: 6005, 65: 6001 } },
  1593. 230: { buff: 35, pet: 6005, heroes: [5, 7, 13, 58, 65], favor: { 5: 6006, 7: 6003, 13: 6002, 58: 6005, 65: 6000 } },
  1594. 240: { buff: 0, pet: 6005, heroes: [12, 58, 1, 36, 65], favor: { 1: 6006, 12: 6003, 36: 6005, 65: 6001 } },
  1595. 250: { buff: 15, pet: 6005, heroes: [12, 36, 4, 16, 65], favor: { 12: 6003, 16: 6004, 36: 6005, 65: 6001 } },
  1596. 260: { buff: 15, pet: 6005, heroes: [48, 12, 36, 65, 4], favor: { 4: 6006, 12: 6003, 36: 6005, 48: 6000, 65: 6007 } },
  1597. 270: { buff: 35, pet: 6005, heroes: [12, 58, 36, 4, 65], favor: { 4: 6006, 12: 6003, 36: 6005 } },
  1598. 280: { buff: 80, pet: 6005, heroes: [21, 36, 48, 7, 65], favor: { 7: 6003, 21: 6006, 36: 6005, 48: 6001, 65: 6000 } },
  1599. 290: { buff: 95, pet: 6008, heroes: [12, 21, 36, 35, 65], favor: { 12: 6003, 21: 6006, 36: 6005, 65: 6007 } },
  1600. 300: { buff: 25, pet: 6005, heroes: [12, 13, 4, 34, 65], favor: { 4: 6006, 12: 6003, 13: 6007, 34: 6002 } },
  1601. 310: { buff: 45, pet: 6005, heroes: [12, 21, 58, 33, 65], favor: { 12: 6003, 21: 6006, 33: 6002, 58: 6005, 65: 6007 } },
  1602. 320: { buff: 70, pet: 6005, heroes: [12, 48, 2, 6, 65], favor: { 6: 6005, 12: 6003 } },
  1603. 330: { buff: 70, pet: 6005, heroes: [12, 21, 36, 5, 65], favor: { 5: 6002, 12: 6003, 21: 6006, 36: 6005, 65: 6000 } },
  1604. 340: { buff: 55, pet: 6009, heroes: [12, 36, 13, 6, 65], favor: { 6: 6005, 12: 6003, 13: 6002, 36: 6006, 65: 6000 } },
  1605. 350: { buff: 100, pet: 6005, heroes: [12, 21, 58, 34, 65], favor: { 12: 6003, 21: 6006, 58: 6005 } },
  1606. 360: { buff: 85, pet: 6007, heroes: [12, 21, 36, 4, 65], favor: { 4: 6006, 12: 6003, 21: 6002, 36: 6005 } },
  1607. 370: { buff: 90, pet: 6008, heroes: [12, 21, 36, 13, 65], favor: { 12: 6003, 13: 6007, 21: 6006, 36: 6005, 65: 6001 } },
  1608. 380: { buff: 165, pet: 6005, heroes: [12, 33, 36, 4, 65], favor: { 4: 6001, 12: 6003, 33: 6006 } },
  1609. 390: { buff: 235, pet: 6005, heroes: [21, 58, 48, 2, 65], favor: { 2: 6005, 21: 6002 } },
  1610. 400: { buff: 125, pet: 6006, heroes: [12, 21, 36, 48, 65], favor: { 12: 6003, 21: 6006, 36: 6005, 48: 6001, 65: 6007 } },
  1611. };
  1612. /**
  1613. * The name of the function of the beginning of the battle
  1614. *
  1615. * Имя функции начала боя
  1616. */
  1617. let nameFuncStartBattle = '';
  1618. /**
  1619. * The name of the function of the end of the battle
  1620. *
  1621. * Имя функции конца боя
  1622. */
  1623. let nameFuncEndBattle = '';
  1624. /**
  1625. * Data for calculating the last battle
  1626. *
  1627. * Данные для расчета последнего боя
  1628. */
  1629. let lastBattleInfo = null;
  1630. /**
  1631. * The ability to cancel the battle
  1632. *
  1633. * Возможность отменить бой
  1634. */
  1635. let isCancalBattle = true;
  1636.  
  1637. function setIsCancalBattle(value) {
  1638. isCancalBattle = value;
  1639. }
  1640.  
  1641. /**
  1642. * Certificator of the last open nesting doll
  1643. *
  1644. * Идетификатор последней открытой матрешки
  1645. */
  1646. let lastRussianDollId = null;
  1647. /**
  1648. * Cancel the training guide
  1649. *
  1650. * Отменить обучающее руководство
  1651. */
  1652. this.isCanceledTutorial = false;
  1653.  
  1654. /**
  1655. * Data from the last question of the quiz
  1656. *
  1657. * Данные последнего вопроса викторины
  1658. */
  1659. let lastQuestion = null;
  1660. /**
  1661. * Answer to the last question of the quiz
  1662. *
  1663. * Ответ на последний вопрос викторины
  1664. */
  1665. let lastAnswer = null;
  1666. /**
  1667. * Flag for opening keys or titan artifact spheres
  1668. *
  1669. * Флаг открытия ключей или сфер артефактов титанов
  1670. */
  1671. let artifactChestOpen = false;
  1672. /**
  1673. * The name of the function to open keys or orbs of titan artifacts
  1674. *
  1675. * Имя функции открытия ключей или сфер артефактов титанов
  1676. */
  1677. let artifactChestOpenCallName = '';
  1678. let correctShowOpenArtifact = 0;
  1679. /**
  1680. * Data for the last battle in the dungeon
  1681. * (Fix endless cards)
  1682. *
  1683. * Данные для последнего боя в подземке
  1684. * (Исправление бесконечных карт)
  1685. */
  1686. let lastDungeonBattleData = null;
  1687. /**
  1688. * Start time of the last battle in the dungeon
  1689. *
  1690. * Время начала последнего боя в подземелье
  1691. */
  1692. let lastDungeonBattleStart = 0;
  1693. /**
  1694. * Subscription end time
  1695. *
  1696. * Время окончания подписки
  1697. */
  1698. let subEndTime = 0;
  1699. /**
  1700. * Number of prediction cards
  1701. *
  1702. * Количество карт предсказаний
  1703. */
  1704. let countPredictionCard = 0;
  1705.  
  1706. /**
  1707. * Brawl pack
  1708. *
  1709. * Пачка для потасовок
  1710. */
  1711. let brawlsPack = null;
  1712. /**
  1713. * Autobrawl started
  1714. *
  1715. * Автопотасовка запущена
  1716. */
  1717. let isBrawlsAutoStart = false;
  1718. let clanDominationGetInfo = null;
  1719. /**
  1720. * Copies the text to the clipboard
  1721. *
  1722. * Копирует тест в буфер обмена
  1723. * @param {*} text copied text // копируемый текст
  1724. */
  1725. function copyText(text) {
  1726. let copyTextarea = document.createElement("textarea");
  1727. copyTextarea.style.opacity = "0";
  1728. copyTextarea.textContent = text;
  1729. document.body.appendChild(copyTextarea);
  1730. copyTextarea.select();
  1731. document.execCommand("copy");
  1732. document.body.removeChild(copyTextarea);
  1733. delete copyTextarea;
  1734. }
  1735. /**
  1736. * Returns the history of requests
  1737. *
  1738. * Возвращает историю запросов
  1739. */
  1740. this.getRequestHistory = function() {
  1741. return requestHistory;
  1742. }
  1743. /**
  1744. * Generates a random integer from min to max
  1745. *
  1746. * Гененирует случайное целое число от min до max
  1747. */
  1748. const random = function (min, max) {
  1749. return Math.floor(Math.random() * (max - min + 1) + min);
  1750. }
  1751. const randf = function (min, max) {
  1752. return Math.random() * (max - min + 1) + min;
  1753. };
  1754. /**
  1755. * Clearing the request history
  1756. *
  1757. * Очистка истоии запросов
  1758. */
  1759. setInterval(function () {
  1760. let now = Date.now();
  1761. for (let i in requestHistory) {
  1762. const time = +i.split('_')[0];
  1763. if (now - time > 300000) {
  1764. delete requestHistory[i];
  1765. }
  1766. }
  1767. }, 300000);
  1768. /**
  1769. * Displays the dialog box
  1770. *
  1771. * Отображает диалоговое окно
  1772. */
  1773. function confShow(message, yesCallback, noCallback) {
  1774. let buts = [];
  1775. message = message || I18N('DO_YOU_WANT');
  1776. noCallback = noCallback || (() => {});
  1777. if (yesCallback) {
  1778. buts = [
  1779. { msg: I18N('BTN_RUN'), result: true},
  1780. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true},
  1781. ]
  1782. } else {
  1783. yesCallback = () => {};
  1784. buts = [
  1785. { msg: I18N('BTN_OK'), result: true},
  1786. ];
  1787. }
  1788. popup.confirm(message, buts).then((e) => {
  1789. // dialogPromice = null;
  1790. if (e) {
  1791. yesCallback();
  1792. } else {
  1793. noCallback();
  1794. }
  1795. });
  1796. }
  1797. /**
  1798. * Override/proxy the method for creating a WS package send
  1799. *
  1800. * Переопределяем/проксируем метод создания отправки WS пакета
  1801. */
  1802. WebSocket.prototype.send = function (data) {
  1803. if (!this.isSetOnMessage) {
  1804. const oldOnmessage = this.onmessage;
  1805. this.onmessage = function (event) {
  1806. try {
  1807. const data = JSON.parse(event.data);
  1808. if (!this.isWebSocketLogin && data.result.type == "iframeEvent.login") {
  1809. this.isWebSocketLogin = true;
  1810. } else if (data.result.type == "iframeEvent.login") {
  1811. return;
  1812. }
  1813. } catch (e) { }
  1814. return oldOnmessage.apply(this, arguments);
  1815. }
  1816. this.isSetOnMessage = true;
  1817. }
  1818. original.SendWebSocket.call(this, data);
  1819. }
  1820. /**
  1821. * Overriding/Proxying the Ajax Request Creation Method
  1822. *
  1823. * Переопределяем/проксируем метод создания Ajax запроса
  1824. */
  1825. XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
  1826. this.uniqid = Date.now() + '_' + random(1000000, 10000000);
  1827. this.errorRequest = false;
  1828. if (method == 'POST' && url.includes('.nextersglobal.com/api/') && /api\/$/.test(url)) {
  1829. if (!apiUrl) {
  1830. apiUrl = url;
  1831. const socialInfo = /heroes-(.+?)\./.exec(apiUrl);
  1832. console.log(socialInfo);
  1833. }
  1834. requestHistory[this.uniqid] = {
  1835. method,
  1836. url,
  1837. error: [],
  1838. headers: {},
  1839. request: null,
  1840. response: null,
  1841. signature: [],
  1842. calls: {},
  1843. };
  1844. } else if (method == 'POST' && url.includes('error.nextersglobal.com/client/')) {
  1845. this.errorRequest = true;
  1846. }
  1847. return original.open.call(this, method, url, async, user, password);
  1848. };
  1849. /**
  1850. * Overriding/Proxying the header setting method for the AJAX request
  1851. *
  1852. * Переопределяем/проксируем метод установки заголовков для AJAX запроса
  1853. */
  1854. XMLHttpRequest.prototype.setRequestHeader = function (name, value, check) {
  1855. if (this.uniqid in requestHistory) {
  1856. requestHistory[this.uniqid].headers[name] = value;
  1857. } else {
  1858. check = true;
  1859. }
  1860.  
  1861. if (name == 'X-Auth-Signature') {
  1862. requestHistory[this.uniqid].signature.push(value);
  1863. if (!check) {
  1864. return;
  1865. }
  1866. }
  1867.  
  1868. return original.setRequestHeader.call(this, name, value);
  1869. };
  1870. /**
  1871. * Overriding/Proxying the AJAX Request Sending Method
  1872. *
  1873. * Переопределяем/проксируем метод отправки AJAX запроса
  1874. */
  1875. XMLHttpRequest.prototype.send = async function (sourceData) {
  1876. if (this.uniqid in requestHistory) {
  1877. let tempData = null;
  1878. if (getClass(sourceData) == "ArrayBuffer") {
  1879. tempData = decoder.decode(sourceData);
  1880. } else {
  1881. tempData = sourceData;
  1882. }
  1883. requestHistory[this.uniqid].request = tempData;
  1884. let headers = requestHistory[this.uniqid].headers;
  1885. lastHeaders = Object.assign({}, headers);
  1886. /**
  1887. * Game loading event
  1888. *
  1889. * Событие загрузки игры
  1890. */
  1891. if (headers["X-Request-Id"] > 2 && !isLoadGame) {
  1892. isLoadGame = true;
  1893. if (cheats.libGame) {
  1894. lib.setData(cheats.libGame);
  1895. } else {
  1896. lib.setData(await cheats.LibLoad());
  1897. }
  1898. addControls();
  1899. addControlButtons();
  1900. addBottomUrls();
  1901.  
  1902. if (isChecked('sendExpedition')) {
  1903. const isTimeBetweenDays = isTimeBetweenNewDays();
  1904. if (!isTimeBetweenDays) {
  1905. checkExpedition();
  1906. } else {
  1907. setProgress(I18N('EXPEDITIONS_NOTTIME'), true);
  1908. }
  1909. }
  1910.  
  1911. getAutoGifts();
  1912.  
  1913. cheats.activateHacks();
  1914. justInfo();
  1915. if (isChecked('dailyQuests')) {
  1916. testDailyQuests();
  1917. }
  1918.  
  1919. if (isChecked('buyForGold')) {
  1920. buyInStoreForGold();
  1921. }
  1922. }
  1923. /**
  1924. * Outgoing request data processing
  1925. *
  1926. * Обработка данных исходящего запроса
  1927. */
  1928. sourceData = await checkChangeSend.call(this, sourceData, tempData);
  1929. /**
  1930. * Handling incoming request data
  1931. *
  1932. * Обработка данных входящего запроса
  1933. */
  1934. const oldReady = this.onreadystatechange;
  1935. this.onreadystatechange = async function (e) {
  1936. if (this.errorRequest) {
  1937. return oldReady.apply(this, arguments);
  1938. }
  1939. if(this.readyState == 4 && this.status == 200) {
  1940. isTextResponse = this.responseType === "text" || this.responseType === "";
  1941. let response = isTextResponse ? this.responseText : this.response;
  1942. requestHistory[this.uniqid].response = response;
  1943. /**
  1944. * Replacing incoming request data
  1945. *
  1946. * Заменна данных входящего запроса
  1947. */
  1948. if (isTextResponse) {
  1949. await checkChangeResponse.call(this, response);
  1950. }
  1951. /**
  1952. * A function to run after the request is executed
  1953. *
  1954. * Функция запускаемая после выполения запроса
  1955. */
  1956. if (typeof this.onReadySuccess == 'function') {
  1957. setTimeout(this.onReadySuccess, 500);
  1958. }
  1959. /** Удаляем из истории запросов битвы с боссом */
  1960. if ('invasion_bossStart' in requestHistory[this.uniqid].calls) delete requestHistory[this.uniqid];
  1961. }
  1962. if (oldReady) {
  1963. try {
  1964. return oldReady.apply(this, arguments);
  1965. } catch(e) {
  1966. console.log(oldReady);
  1967. console.error('Error in oldReady:', e);
  1968. }
  1969.  
  1970. }
  1971. }
  1972. }
  1973. if (this.errorRequest) {
  1974. const oldReady = this.onreadystatechange;
  1975. this.onreadystatechange = function () {
  1976. Object.defineProperty(this, 'status', {
  1977. writable: true
  1978. });
  1979. this.status = 200;
  1980. Object.defineProperty(this, 'readyState', {
  1981. writable: true
  1982. });
  1983. this.readyState = 4;
  1984. Object.defineProperty(this, 'responseText', {
  1985. writable: true
  1986. });
  1987. this.responseText = JSON.stringify({
  1988. "result": true
  1989. });
  1990. if (typeof this.onReadySuccess == 'function') {
  1991. setTimeout(this.onReadySuccess, 200);
  1992. }
  1993. return oldReady.apply(this, arguments);
  1994. }
  1995. this.onreadystatechange();
  1996. } else {
  1997. try {
  1998. return original.send.call(this, sourceData);
  1999. } catch(e) {
  2000. debugger;
  2001. }
  2002. }
  2003. };
  2004. /**
  2005. * Processing and substitution of outgoing data
  2006. *
  2007. * Обработка и подмена исходящих данных
  2008. */
  2009. async function checkChangeSend(sourceData, tempData) {
  2010. try {
  2011. /**
  2012. * A function that replaces battle data with incorrect ones to cancel combatя
  2013. *
  2014. * Функция заменяющая данные боя на неверные для отмены боя
  2015. */
  2016. const fixBattle = function (heroes) {
  2017. for (const ids in heroes) {
  2018. hero = heroes[ids];
  2019. hero.energy = random(1, 999);
  2020. if (hero.hp > 0) {
  2021. hero.hp = random(1, hero.hp);
  2022. }
  2023. }
  2024. }
  2025. /**
  2026. * Dialog window 2
  2027. *
  2028. * Диалоговое окно 2
  2029. */
  2030. const showMsg = async function (msg, ansF, ansS) {
  2031. if (typeof popup == 'object') {
  2032. return await popup.confirm(msg, [
  2033. {msg: ansF, result: false},
  2034. {msg: ansS, result: true},
  2035. ]);
  2036. } else {
  2037. return !confirm(`${msg}\n ${ansF} (${I18N('BTN_OK')})\n ${ansS} (${I18N('BTN_CANCEL')})`);
  2038. }
  2039. }
  2040. /**
  2041. * Dialog window 3
  2042. *
  2043. * Диалоговое окно 3
  2044. */
  2045. const showMsgs = async function (msg, ansF, ansS, ansT) {
  2046. return await popup.confirm(msg, [
  2047. {msg: ansF, result: 0},
  2048. {msg: ansS, result: 1},
  2049. {msg: ansT, result: 2},
  2050. ]);
  2051. }
  2052.  
  2053. let changeRequest = false;
  2054. testData = JSON.parse(tempData);
  2055. for (const call of testData.calls) {
  2056. if (!artifactChestOpen) {
  2057. requestHistory[this.uniqid].calls[call.name] = call.ident;
  2058. }
  2059. /**
  2060. * Cancellation of the battle in adventures, on VG and with minions of Asgard
  2061. * Отмена боя в приключениях, на ВГ и с прислужниками Асгарда
  2062. */
  2063. if ((call.name == 'adventure_endBattle' ||
  2064. call.name == 'adventureSolo_endBattle' ||
  2065. call.name == 'clanWarEndBattle' &&
  2066. isChecked('cancelBattle') ||
  2067. call.name == 'crossClanWar_endBattle' &&
  2068. isChecked('cancelBattle') ||
  2069. call.name == 'brawl_endBattle' ||
  2070. call.name == 'towerEndBattle' ||
  2071. call.name == 'invasion_bossEnd' ||
  2072. call.name == 'titanArenaEndBattle' ||
  2073. call.name == 'bossEndBattle' ||
  2074. call.name == 'clanRaid_endNodeBattle') &&
  2075. isCancalBattle) {
  2076. nameFuncEndBattle = call.name;
  2077.  
  2078. if (isChecked('tryFixIt_v2') &&
  2079. !call.args.result.win &&
  2080. (call.name == 'brawl_endBattle' ||
  2081. //call.name == 'crossClanWar_endBattle' ||
  2082. call.name == 'epicBrawl_endBattle' ||
  2083. //call.name == 'clanWarEndBattle' ||
  2084. call.name == 'adventure_endBattle' ||
  2085. call.name == 'titanArenaEndBattle' ||
  2086. call.name == 'bossEndBattle' ||
  2087. call.name == 'adventureSolo_endBattle') &&
  2088. lastBattleInfo) {
  2089. const noFixWin = call.name == 'clanWarEndBattle' || call.name == 'crossClanWar_endBattle';
  2090. const cloneBattle = structuredClone(lastBattleInfo);
  2091. lastBattleInfo = null;
  2092. try {
  2093. const { BestOrWinFixBattle } = HWHClasses;
  2094. const bFix = new BestOrWinFixBattle(cloneBattle);
  2095. bFix.setNoMakeWin(noFixWin);
  2096. let endTime = Date.now() + 3e4;
  2097. if (endTime < cloneBattle.endTime) {
  2098. endTime = cloneBattle.endTime;
  2099. }
  2100. const result = await bFix.start(cloneBattle.endTime, 150);
  2101.  
  2102. if (result.result.win) {
  2103. call.args.result = result.result;
  2104. call.args.progress = result.progress;
  2105. changeRequest = true;
  2106. } else if (result.value) {
  2107. if (
  2108. await popup.confirm(I18N('DEFEAT') + '<br>' + I18N('BEST_RESULT', { value: result.value }), [
  2109. { msg: I18N('BTN_CANCEL'), result: 0 },
  2110. { msg: I18N('BTN_ACCEPT'), result: 1 },
  2111. ])
  2112. ) {
  2113. call.args.result = result.result;
  2114. call.args.progress = result.progress;
  2115. changeRequest = true;
  2116. }
  2117. }
  2118. } catch (error) {
  2119. console.error(error);
  2120. }
  2121. }
  2122.  
  2123. if (!call.args.result.win) {
  2124. let resultPopup = false;
  2125. if (call.name == 'adventure_endBattle' ||
  2126. //call.name == 'invasion_bossEnd' ||
  2127. call.name == 'bossEndBattle' ||
  2128. call.name == 'adventureSolo_endBattle') {
  2129. resultPopup = await showMsgs(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_CANCEL'), I18N('BTN_AUTO'));
  2130. } else if (call.name == 'clanWarEndBattle' ||
  2131. call.name == 'crossClanWar_endBattle') {
  2132. resultPopup = await showMsg(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_AUTO_F5'));
  2133. } else if (call.name !== 'epicBrawl_endBattle' && call.name !== 'titanArenaEndBattle') {
  2134. resultPopup = await showMsg(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_CANCEL'));
  2135. }
  2136. if (resultPopup) {
  2137. if (call.name == 'invasion_bossEnd') {
  2138. this.errorRequest = true;
  2139. }
  2140. fixBattle(call.args.progress[0].attackers.heroes);
  2141. fixBattle(call.args.progress[0].defenders.heroes);
  2142. changeRequest = true;
  2143. if (resultPopup > 1) {
  2144. this.onReadySuccess = testAutoBattle;
  2145. // setTimeout(bossBattle, 1000);
  2146. }
  2147. }
  2148. } else if (call.args.result.stars < 3 && call.name == 'towerEndBattle') {
  2149. resultPopup = await showMsg(I18N('LOST_HEROES'), I18N('BTN_OK'), I18N('BTN_CANCEL'), I18N('BTN_AUTO'));
  2150. if (resultPopup) {
  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. }
  2157. }
  2158. }
  2159. // Потасовки
  2160. if (isChecked('autoBrawls') && !isBrawlsAutoStart && call.name == 'brawl_endBattle') {}
  2161. }
  2162. /**
  2163. * Save pack for Brawls
  2164. *
  2165. * Сохраняем пачку для потасовок
  2166. */
  2167. if (isChecked('autoBrawls') && !isBrawlsAutoStart && call.name == 'brawl_startBattle') {
  2168. console.log(JSON.stringify(call.args));
  2169. brawlsPack = call.args;
  2170. if (
  2171. await popup.confirm(
  2172. I18N('START_AUTO_BRAWLS'),
  2173. [
  2174. { msg: I18N('BTN_NO'), result: false },
  2175. { msg: I18N('BTN_YES'), result: true },
  2176. ],
  2177. [
  2178. {
  2179. name: 'isAuto',
  2180. label: I18N('BRAWL_AUTO_PACK'),
  2181. checked: false,
  2182. },
  2183. ]
  2184. )
  2185. ) {
  2186. isBrawlsAutoStart = true;
  2187. const isAuto = popup.getCheckBoxes().find((e) => e.name === 'isAuto');
  2188. this.errorRequest = true;
  2189. testBrawls(isAuto.checked);
  2190. }
  2191. }
  2192. /**
  2193. * Canceled fight in Asgard
  2194. * Отмена боя в Асгарде
  2195. */
  2196. if (call.name == 'clanRaid_endBossBattle' && isChecked('cancelBattle')) {
  2197. const bossDamage = call.args.progress[0].defenders.heroes[1].extra;
  2198. let maxDamage = bossDamage.damageTaken + bossDamage.damageTakenNextLevel;
  2199. const lastDamage = maxDamage;
  2200.  
  2201. const testFunc = [];
  2202.  
  2203. if (testFuntions.masterFix) {
  2204. testFunc.push({ msg: 'masterFix', isInput: true, default: 100 });
  2205. }
  2206.  
  2207. const resultPopup = await popup.confirm(
  2208. `${I18N('MSG_YOU_APPLIED')} ${lastDamage.toLocaleString()} ${I18N('MSG_DAMAGE')}.`,
  2209. [
  2210. { msg: I18N('BTN_OK'), result: false },
  2211. { msg: I18N('BTN_AUTO_F5'), result: 1 },
  2212. { msg: I18N('BTN_TRY_FIX_IT'), result: 2 },
  2213. ...testFunc,
  2214. ],
  2215. [
  2216. {
  2217. name: 'isStat',
  2218. label: I18N('CALC_STAT'),
  2219. checked: false,
  2220. },
  2221. ]
  2222. );
  2223. if (resultPopup) {
  2224. if (resultPopup == 2) {
  2225. setProgress(I18N('LETS_FIX'), false);
  2226. await new Promise((e) => setTimeout(e, 0));
  2227. const cloneBattle = structuredClone(lastBossBattle);
  2228. const endTime = cloneBattle.endTime - 1e4;
  2229. console.log('fixBossBattleStart');
  2230.  
  2231. const { BossFixBattle } = HWHClasses;
  2232. const bFix = new BossFixBattle(cloneBattle);
  2233. const result = await bFix.start(endTime, 300);
  2234. console.log(result);
  2235.  
  2236. let msgResult = I18N('DAMAGE_NO_FIXED', {
  2237. lastDamage: lastDamage.toLocaleString()
  2238. });
  2239. if (result.value > lastDamage) {
  2240. call.args.result = result.result;
  2241. call.args.progress = result.progress;
  2242. msgResult = I18N('DAMAGE_FIXED', {
  2243. lastDamage: lastDamage.toLocaleString(),
  2244. maxDamage: result.value.toLocaleString(),
  2245. });
  2246. }
  2247. console.log(lastDamage, '>', result.value);
  2248. setProgress(
  2249. msgResult +
  2250. '<br/>' +
  2251. I18N('COUNT_FIXED', {
  2252. count: result.maxCount,
  2253. }),
  2254. false,
  2255. hideProgress
  2256. );
  2257. } else if (resultPopup > 3) {
  2258. const cloneBattle = structuredClone(lastBossBattle);
  2259. const { masterFixBattle } = HWHClasses;
  2260. const mFix = new masterFixBattle(cloneBattle);
  2261. const result = await mFix.start(cloneBattle.endTime, resultPopup);
  2262. console.log(result);
  2263. let msgResult = I18N('DAMAGE_NO_FIXED', {
  2264. lastDamage: lastDamage.toLocaleString(),
  2265. });
  2266. if (result.value > lastDamage) {
  2267. maxDamage = result.value;
  2268. call.args.result = result.result;
  2269. call.args.progress = result.progress;
  2270. msgResult = I18N('DAMAGE_FIXED', {
  2271. lastDamage: lastDamage.toLocaleString(),
  2272. maxDamage: maxDamage.toLocaleString(),
  2273. });
  2274. }
  2275. console.log('Урон:', lastDamage, maxDamage);
  2276. setProgress(msgResult, false, hideProgress);
  2277. } else {
  2278. fixBattle(call.args.progress[0].attackers.heroes);
  2279. fixBattle(call.args.progress[0].defenders.heroes);
  2280. }
  2281. changeRequest = true;
  2282. }
  2283. const isStat = popup.getCheckBoxes().find((e) => e.name === 'isStat');
  2284. if (isStat.checked) {
  2285. this.onReadySuccess = testBossBattle;
  2286. }
  2287. }
  2288. /**
  2289. * Save the Asgard Boss Attack Pack
  2290. * Сохраняем пачку для атаки босса Асгарда
  2291. */
  2292. if (call.name == 'clanRaid_startBossBattle') {
  2293. console.log(JSON.stringify(call.args));
  2294. }
  2295. /**
  2296. * Saving the request to start the last battle
  2297. * Сохранение запроса начала последнего боя
  2298. */
  2299. if (
  2300. call.name == 'clanWarAttack' ||
  2301. call.name == 'crossClanWar_startBattle' ||
  2302. call.name == 'adventure_turnStartBattle' ||
  2303. call.name == 'adventureSolo_turnStartBattle' ||
  2304. call.name == 'bossAttack' ||
  2305. call.name == 'invasion_bossStart' ||
  2306. call.name == 'towerStartBattle'
  2307. ) {
  2308. nameFuncStartBattle = call.name;
  2309. lastBattleArg = call.args;
  2310.  
  2311. if (call.name == 'invasion_bossStart') {
  2312. const timePassed = Date.now() - lastBossBattleStart;
  2313. if (timePassed < invasionTimer) {
  2314. await new Promise((e) => setTimeout(e, invasionTimer - timePassed));
  2315. }
  2316. invasionTimer -= 1;
  2317. }
  2318. lastBossBattleStart = Date.now();
  2319. }
  2320. if (call.name == 'invasion_bossEnd') {
  2321. const lastBattle = lastBattleInfo;
  2322. if (lastBattle && call.args.result.win) {
  2323. lastBattle.progress = call.args.progress;
  2324. const result = await Calc(lastBattle);
  2325. let timer = getTimer(result.battleTime, 1) + addBattleTimer;
  2326. const period = Math.ceil((Date.now() - lastBossBattleStart) / 1000);
  2327. console.log(timer, period);
  2328. if (period < timer) {
  2329. timer = timer - period;
  2330. await countdownTimer(timer);
  2331. }
  2332. }
  2333. }
  2334. /**
  2335. * Disable spending divination cards
  2336. * Отключить трату карт предсказаний
  2337. */
  2338. if (call.name == 'dungeonEndBattle') {
  2339. if (call.args.isRaid) {
  2340. if (countPredictionCard <= 0) {
  2341. delete call.args.isRaid;
  2342. changeRequest = true;
  2343. } else if (countPredictionCard > 0) {
  2344. countPredictionCard--;
  2345. }
  2346. }
  2347. console.log(`Cards: ${countPredictionCard}`);
  2348. /**
  2349. * Fix endless cards
  2350. * Исправление бесконечных карт
  2351. */
  2352. const lastBattle = lastDungeonBattleData;
  2353. if (lastBattle && !call.args.isRaid) {
  2354. if (changeRequest) {
  2355. lastBattle.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  2356. } else {
  2357. lastBattle.progress = call.args.progress;
  2358. }
  2359. const result = await Calc(lastBattle);
  2360.  
  2361. if (changeRequest) {
  2362. call.args.progress = result.progress;
  2363. call.args.result = result.result;
  2364. }
  2365. let timer = result.battleTimer + addBattleTimer;
  2366. const period = Math.ceil((Date.now() - lastDungeonBattleStart) / 1000);
  2367. console.log(timer, period);
  2368. if (period < timer) {
  2369. timer = timer - period;
  2370. await countdownTimer(timer);
  2371. }
  2372. }
  2373. }
  2374. /**
  2375. * Quiz Answer
  2376. * Ответ на викторину
  2377. */
  2378. if (call.name == 'quizAnswer') {
  2379. /**
  2380. * Automatically changes the answer to the correct one if there is one.
  2381. * Автоматически меняет ответ на правильный если он есть
  2382. */
  2383. if (lastAnswer && isChecked('getAnswer')) {
  2384. call.args.answerId = lastAnswer;
  2385. lastAnswer = null;
  2386. changeRequest = true;
  2387. }
  2388. }
  2389. /**
  2390. * Present
  2391. * Подарки
  2392. */
  2393. if (call.name == 'freebieCheck') {
  2394. freebieCheckInfo = call;
  2395. }
  2396. /** missionTimer */
  2397. if (call.name == 'missionEnd' && missionBattle) {
  2398. let startTimer = false;
  2399. if (!call.args.result.win) {
  2400. startTimer = await popup.confirm(I18N('DEFEAT_TURN_TIMER'), [
  2401. { msg: I18N('BTN_NO'), result: false },
  2402. { msg: I18N('BTN_YES'), result: true },
  2403. ]);
  2404. }
  2405.  
  2406. if (call.args.result.win || startTimer) {
  2407. missionBattle.progress = call.args.progress;
  2408. missionBattle.result = call.args.result;
  2409. const result = await Calc(missionBattle);
  2410.  
  2411. let timer = result.battleTimer + addBattleTimer;
  2412. const period = Math.ceil((Date.now() - lastMissionBattleStart) / 1000);
  2413. if (period < timer) {
  2414. timer = timer - period;
  2415. await countdownTimer(timer);
  2416. }
  2417. missionBattle = null;
  2418. } else {
  2419. this.errorRequest = true;
  2420. }
  2421. }
  2422. /**
  2423. * Getting mission data for auto-repeat
  2424. * Получение данных миссии для автоповтора
  2425. */
  2426. if (isChecked('repeatMission') &&
  2427. call.name == 'missionEnd') {
  2428. let missionInfo = {
  2429. id: call.args.id,
  2430. result: call.args.result,
  2431. heroes: call.args.progress[0].attackers.heroes,
  2432. count: 0,
  2433. }
  2434. setTimeout(async () => {
  2435. if (!isSendsMission && await popup.confirm(I18N('MSG_REPEAT_MISSION'), [
  2436. { msg: I18N('BTN_REPEAT'), result: true},
  2437. { msg: I18N('BTN_NO'), result: false},
  2438. ])) {
  2439. isStopSendMission = false;
  2440. isSendsMission = true;
  2441. sendsMission(missionInfo);
  2442. }
  2443. }, 0);
  2444. }
  2445. /**
  2446. * Getting mission data
  2447. * Получение данных миссии
  2448. * missionTimer
  2449. */
  2450. if (call.name == 'missionStart') {
  2451. lastMissionStart = call.args;
  2452. lastMissionBattleStart = Date.now();
  2453. }
  2454. /**
  2455. * Specify the quantity for Titan Orbs and Pet Eggs
  2456. * Указать количество для сфер титанов и яиц петов
  2457. */
  2458. if (isChecked('countControl') &&
  2459. (call.name == 'pet_chestOpen' ||
  2460. call.name == 'titanUseSummonCircle') &&
  2461. call.args.amount > 1) {
  2462. const startAmount = call.args.amount;
  2463. const result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2464. { msg: I18N('BTN_OPEN'), isInput: true, default: 1},
  2465. ]);
  2466. if (result) {
  2467. const item = call.name == 'pet_chestOpen' ? { id: 90, type: 'consumable' } : { id: 13, type: 'coin' };
  2468. cheats.updateInventory({
  2469. [item.type]: {
  2470. [item.id]: -(result - startAmount),
  2471. },
  2472. });
  2473. call.args.amount = result;
  2474. changeRequest = true;
  2475. }
  2476. }
  2477. /**
  2478. * Specify the amount for keys and spheres of titan artifacts
  2479. * Указать колличество для ключей и сфер артефактов титанов
  2480. */
  2481. if (isChecked('countControl') &&
  2482. (call.name == 'artifactChestOpen' ||
  2483. call.name == 'titanArtifactChestOpen') &&
  2484. call.args.amount > 1 &&
  2485. call.args.free &&
  2486. !changeRequest) {
  2487. artifactChestOpenCallName = call.name;
  2488. const startAmount = call.args.amount;
  2489. let result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2490. { msg: I18N('BTN_OPEN'), isInput: true, default: 1 },
  2491. ]);
  2492. if (result) {
  2493. const openChests = result;
  2494. let sphere = result < 10 ? 1 : 10;
  2495. call.args.amount = sphere;
  2496. for (let count = openChests - sphere; count > 0; count -= sphere) {
  2497. if (count < 10) sphere = 1;
  2498. const ident = artifactChestOpenCallName + "_" + count;
  2499. testData.calls.push({
  2500. name: artifactChestOpenCallName,
  2501. args: {
  2502. amount: sphere,
  2503. free: true,
  2504. },
  2505. ident: ident
  2506. });
  2507. if (!Array.isArray(requestHistory[this.uniqid].calls[call.name])) {
  2508. requestHistory[this.uniqid].calls[call.name] = [requestHistory[this.uniqid].calls[call.name]];
  2509. }
  2510. requestHistory[this.uniqid].calls[call.name].push(ident);
  2511. }
  2512.  
  2513. const consumableId = call.name == 'artifactChestOpen' ? 45 : 55;
  2514. cheats.updateInventory({
  2515. consumable: {
  2516. [consumableId]: -(openChests - startAmount),
  2517. },
  2518. });
  2519. artifactChestOpen = true;
  2520. changeRequest = true;
  2521. }
  2522. }
  2523. if (call.name == 'consumableUseLootBox') {
  2524. lastRussianDollId = call.args.libId;
  2525. /**
  2526. * Specify quantity for gold caskets
  2527. * Указать количество для золотых шкатулок
  2528. */
  2529. if (isChecked('countControl') &&
  2530. call.args.libId == 148 &&
  2531. call.args.amount > 1) {
  2532. const result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2533. { msg: I18N('BTN_OPEN'), isInput: true, default: call.args.amount},
  2534. ]);
  2535. call.args.amount = result;
  2536. changeRequest = true;
  2537. }
  2538. if (isChecked('countControl') && call.args.libId >= 362 && call.args.libId <= 389) {
  2539. this.massOpen = call.args.libId;
  2540. }
  2541. }
  2542. if (call.name == 'invasion_bossStart' && isChecked('tryFixIt_v2') && call.args.id == 217) {
  2543. const pack = invasionDataPacks[invasionInfo.bossLvl];
  2544. if (pack.buff != invasionInfo.buff) {
  2545. setProgress(
  2546. I18N('INVASION_BOSS_BUFF', {
  2547. bossLvl: invasionInfo.bossLvl,
  2548. needBuff: pack.buff,
  2549. haveBuff: invasionInfo.buff,
  2550. }),
  2551. false
  2552. );
  2553. } else {
  2554. call.args.pet = pack.pet;
  2555. call.args.heroes = pack.heroes;
  2556. call.args.favor = pack.favor;
  2557. changeRequest = true;
  2558. }
  2559. }
  2560. /**
  2561. * Changing the maximum number of raids in the campaign
  2562. * Изменение максимального количества рейдов в кампании
  2563. */
  2564. // if (call.name == 'missionRaid') {
  2565. // if (isChecked('countControl') && call.args.times > 1) {
  2566. // const result = +(await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2567. // { msg: I18N('BTN_RUN'), isInput: true, default: call.args.times },
  2568. // ]));
  2569. // call.args.times = result > call.args.times ? call.args.times : result;
  2570. // changeRequest = true;
  2571. // }
  2572. // }
  2573. }
  2574.  
  2575. let headers = requestHistory[this.uniqid].headers;
  2576. if (changeRequest) {
  2577. sourceData = JSON.stringify(testData);
  2578. headers['X-Auth-Signature'] = getSignature(headers, sourceData);
  2579. }
  2580.  
  2581. let signature = headers['X-Auth-Signature'];
  2582. if (signature) {
  2583. original.setRequestHeader.call(this, 'X-Auth-Signature', signature);
  2584. }
  2585. } catch (err) {
  2586. console.log("Request(send, " + this.uniqid + "):\n", sourceData, "Error:\n", err);
  2587. }
  2588. return sourceData;
  2589. }
  2590. /**
  2591. * Processing and substitution of incoming data
  2592. *
  2593. * Обработка и подмена входящих данных
  2594. */
  2595. async function checkChangeResponse(response) {
  2596. try {
  2597. isChange = false;
  2598. let nowTime = Math.round(Date.now() / 1000);
  2599. callsIdent = requestHistory[this.uniqid].calls;
  2600. respond = JSON.parse(response);
  2601. /**
  2602. * If the request returned an error removes the error (removes synchronization errors)
  2603. * Если запрос вернул ошибку удаляет ошибку (убирает ошибки синхронизации)
  2604. */
  2605. if (respond.error) {
  2606. isChange = true;
  2607. console.error(respond.error);
  2608. if (isChecked('showErrors')) {
  2609. popup.confirm(I18N('ERROR_MSG', {
  2610. name: respond.error.name,
  2611. description: respond.error.description,
  2612. }));
  2613. }
  2614. if (respond.error.name != 'AccountBan') {
  2615. delete respond.error;
  2616. respond.results = [];
  2617. }
  2618. }
  2619. let mainReward = null;
  2620. const allReward = {};
  2621. let countTypeReward = 0;
  2622. let readQuestInfo = false;
  2623. for (const call of respond.results) {
  2624. /**
  2625. * Obtaining initial data for completing quests
  2626. * Получение исходных данных для выполнения квестов
  2627. */
  2628. if (readQuestInfo) {
  2629. questsInfo[call.ident] = call.result.response;
  2630. }
  2631. /**
  2632. * Getting a user ID
  2633. * Получение идетификатора пользователя
  2634. */
  2635. if (call.ident == callsIdent['registration']) {
  2636. userId = call.result.response.userId;
  2637. if (localStorage['userId'] != userId) {
  2638. localStorage['newGiftSendIds'] = '';
  2639. localStorage['userId'] = userId;
  2640. }
  2641. await openOrMigrateDatabase(userId);
  2642. readQuestInfo = true;
  2643. }
  2644. /**
  2645. * Hiding donation offers 1
  2646. * Скрываем предложения доната 1
  2647. */
  2648. if (call.ident == callsIdent['billingGetAll'] && getSaveVal('noOfferDonat')) {
  2649. const billings = call.result.response?.billings;
  2650. const bundle = call.result.response?.bundle;
  2651. if (billings && bundle) {
  2652. call.result.response.billings = call.result.response.billings.filter((e) => ['repeatableOffer'].includes(e.type));
  2653. call.result.response.bundle = [];
  2654. isChange = true;
  2655. }
  2656. }
  2657. /**
  2658. * Hiding donation offers 2
  2659. * Скрываем предложения доната 2
  2660. */
  2661. if (getSaveVal('noOfferDonat') &&
  2662. (call.ident == callsIdent['offerGetAll'] ||
  2663. call.ident == callsIdent['specialOffer_getAll'])) {
  2664. let offers = call.result.response;
  2665. if (offers) {
  2666. call.result.response = offers.filter(
  2667. (e) => !['addBilling', 'bundleCarousel'].includes(e.type) || ['idleResource', 'stagesOffer'].includes(e.offerType)
  2668. );
  2669. isChange = true;
  2670. }
  2671. }
  2672. /**
  2673. * Hiding donation offers 3
  2674. * Скрываем предложения доната 3
  2675. */
  2676. if (getSaveVal('noOfferDonat') && call.result?.bundleUpdate) {
  2677. delete call.result.bundleUpdate;
  2678. isChange = true;
  2679. }
  2680. /**
  2681. * Hiding donation offers 4
  2682. * Скрываем предложения доната 4
  2683. */
  2684. if (call.result?.specialOffers) {
  2685. const offers = call.result.specialOffers;
  2686. call.result.specialOffers = offers.filter(
  2687. (e) => !['addBilling', 'bundleCarousel'].includes(e.type) || ['idleResource', 'stagesOffer'].includes(e.offerType)
  2688. );
  2689. isChange = true;
  2690. }
  2691. /**
  2692. * Copies a quiz question to the clipboard
  2693. * Копирует вопрос викторины в буфер обмена и получает на него ответ если есть
  2694. */
  2695. if (call.ident == callsIdent['quizGetNewQuestion']) {
  2696. let quest = call.result.response;
  2697. console.log(quest.question);
  2698. copyText(quest.question);
  2699. setProgress(I18N('QUESTION_COPY'), true);
  2700. quest.lang = null;
  2701. if (typeof NXFlashVars !== 'undefined') {
  2702. quest.lang = NXFlashVars.interface_lang;
  2703. }
  2704. lastQuestion = quest;
  2705. if (isChecked('getAnswer')) {
  2706. const answer = await getAnswer(lastQuestion);
  2707. let showText = '';
  2708. if (answer) {
  2709. lastAnswer = answer;
  2710. console.log(answer);
  2711. showText = `${I18N('ANSWER_KNOWN')}: ${answer}`;
  2712. } else {
  2713. showText = I18N('ANSWER_NOT_KNOWN');
  2714. }
  2715.  
  2716. try {
  2717. const hint = hintQuest(quest);
  2718. if (hint) {
  2719. showText += I18N('HINT') + hint;
  2720. }
  2721. } catch(e) {}
  2722.  
  2723. setProgress(showText, true);
  2724. }
  2725. }
  2726. /**
  2727. * Submits a question with an answer to the database
  2728. * Отправляет вопрос с ответом в базу данных
  2729. */
  2730. if (call.ident == callsIdent['quizAnswer']) {
  2731. const answer = call.result.response;
  2732. if (lastQuestion) {
  2733. const answerInfo = {
  2734. answer,
  2735. question: lastQuestion,
  2736. lang: null,
  2737. }
  2738. if (typeof NXFlashVars !== 'undefined') {
  2739. answerInfo.lang = NXFlashVars.interface_lang;
  2740. }
  2741. lastQuestion = null;
  2742. setTimeout(sendAnswerInfo, 0, answerInfo);
  2743. }
  2744. }
  2745. /**
  2746. * Get user data
  2747. * Получить даныне пользователя
  2748. */
  2749. if (call.ident == callsIdent['userGetInfo']) {
  2750. let user = call.result.response;
  2751. document.title = user.name;
  2752. userInfo = Object.assign({}, user);
  2753. delete userInfo.refillable;
  2754. if (!questsInfo['userGetInfo']) {
  2755. questsInfo['userGetInfo'] = user;
  2756. }
  2757. }
  2758. /**
  2759. * Start of the battle for recalculation
  2760. * Начало боя для прерасчета
  2761. */
  2762. if (call.ident == callsIdent['clanWarAttack'] ||
  2763. call.ident == callsIdent['crossClanWar_startBattle'] ||
  2764. call.ident == callsIdent['bossAttack'] ||
  2765. call.ident == callsIdent['battleGetReplay'] ||
  2766. call.ident == callsIdent['brawl_startBattle'] ||
  2767. call.ident == callsIdent['adventureSolo_turnStartBattle'] ||
  2768. call.ident == callsIdent['invasion_bossStart'] ||
  2769. call.ident == callsIdent['titanArenaStartBattle'] ||
  2770. call.ident == callsIdent['towerStartBattle'] ||
  2771. call.ident == callsIdent['epicBrawl_startBattle'] ||
  2772. call.ident == callsIdent['adventure_turnStartBattle']) {
  2773. let battle = call.result.response.battle || call.result.response.replay;
  2774. if (call.ident == callsIdent['brawl_startBattle'] ||
  2775. call.ident == callsIdent['bossAttack'] ||
  2776. call.ident == callsIdent['towerStartBattle'] ||
  2777. call.ident == callsIdent['invasion_bossStart']) {
  2778. battle = call.result.response;
  2779. }
  2780. lastBattleInfo = battle;
  2781. if (call.ident == callsIdent['battleGetReplay'] && call.result.response.replay.type === "clan_raid") {
  2782. if (call?.result?.response?.replay?.result?.damage) {
  2783. const damages = Object.values(call.result.response.replay.result.damage);
  2784. const bossDamage = damages.reduce((a, v) => a + v, 0);
  2785. setProgress(I18N('BOSS_DAMAGE') + bossDamage.toLocaleString(), false, hideProgress);
  2786. continue;
  2787. }
  2788. }
  2789. if (!isChecked('preCalcBattle')) {
  2790. continue;
  2791. }
  2792. const preCalcBattle = structuredClone(battle);
  2793. setProgress(I18N('BEING_RECALC'));
  2794. let battleDuration = 120;
  2795. try {
  2796. const typeBattle = getBattleType(preCalcBattle.type);
  2797. battleDuration = +lib.data.battleConfig[typeBattle.split('_')[1]].config.battleDuration;
  2798. } catch (e) { }
  2799. //console.log(battle.type);
  2800. function getBattleInfo(battle, isRandSeed) {
  2801. return new Promise(function (resolve) {
  2802. if (isRandSeed) {
  2803. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  2804. }
  2805. BattleCalc(battle, getBattleType(battle.type), e => resolve(e));
  2806. });
  2807. }
  2808. let actions = [getBattleInfo(preCalcBattle, false)];
  2809. let countTestBattle = getInput('countTestBattle');
  2810. if (call.ident == callsIdent['invasion_bossStart'] ) {
  2811. countTestBattle = 0;
  2812. }
  2813. if (call.ident == callsIdent['battleGetReplay']) {
  2814. preCalcBattle.progress = [{ attackers: { input: ['auto', 0, 0, 'auto', 0, 0] } }];
  2815. }
  2816. for (let i = 0; i < countTestBattle; i++) {
  2817. actions.push(getBattleInfo(preCalcBattle, true));
  2818. }
  2819. Promise.all(actions)
  2820. .then(e => {
  2821. e = e.map(n => ({win: n.result.win, time: n.battleTime}));
  2822. let firstBattle = e.shift();
  2823. const timer = Math.floor(battleDuration - firstBattle.time);
  2824. const min = ('00' + Math.floor(timer / 60)).slice(-2);
  2825. const sec = ('00' + Math.floor(timer - min * 60)).slice(-2);
  2826. let msg = `${I18N('THIS_TIME')} ${firstBattle.win ? I18N('VICTORY') : I18N('DEFEAT')}`;
  2827. if (e.length) {
  2828. const countWin = e.reduce((w, s) => w + s.win, 0);
  2829. msg += ` ${I18N('CHANCE_TO_WIN')}: ${Math.floor((countWin / e.length) * 100)}% (${e.length})`;
  2830. }
  2831. msg += `, ${min}:${sec}`
  2832. setProgress(msg, false, hideProgress)
  2833. });
  2834. }
  2835. /**
  2836. * Start of the Asgard boss fight
  2837. * Начало боя с боссом Асгарда
  2838. */
  2839. if (call.ident == callsIdent['clanRaid_startBossBattle']) {
  2840. lastBossBattle = call.result.response.battle;
  2841. lastBossBattle.endTime = Date.now() + 160 * 1000;
  2842. if (isChecked('preCalcBattle')) {
  2843. const result = await Calc(lastBossBattle).then(e => e.progress[0].defenders.heroes[1].extra);
  2844. const bossDamage = result.damageTaken + result.damageTakenNextLevel;
  2845. setProgress(I18N('BOSS_DAMAGE') + bossDamage.toLocaleString(), false, hideProgress);
  2846. }
  2847. }
  2848. /**
  2849. * Cancel tutorial
  2850. * Отмена туториала
  2851. */
  2852. if (isCanceledTutorial && call.ident == callsIdent['tutorialGetInfo']) {
  2853. let chains = call.result.response.chains;
  2854. for (let n in chains) {
  2855. chains[n] = 9999;
  2856. }
  2857. isChange = true;
  2858. }
  2859. /**
  2860. * Opening keys and spheres of titan artifacts
  2861. * Открытие ключей и сфер артефактов титанов
  2862. */
  2863. if (artifactChestOpen &&
  2864. (call.ident == callsIdent[artifactChestOpenCallName] ||
  2865. (callsIdent[artifactChestOpenCallName] && callsIdent[artifactChestOpenCallName].includes(call.ident)))) {
  2866. let reward = call.result.response[artifactChestOpenCallName == 'artifactChestOpen' ? 'chestReward' : 'reward'];
  2867.  
  2868. reward.forEach(e => {
  2869. for (let f in e) {
  2870. if (!allReward[f]) {
  2871. allReward[f] = {};
  2872. }
  2873. for (let o in e[f]) {
  2874. if (!allReward[f][o]) {
  2875. allReward[f][o] = e[f][o];
  2876. countTypeReward++;
  2877. } else {
  2878. allReward[f][o] += e[f][o];
  2879. }
  2880. }
  2881. }
  2882. });
  2883.  
  2884. if (!call.ident.includes(artifactChestOpenCallName)) {
  2885. mainReward = call.result.response;
  2886. }
  2887. }
  2888.  
  2889. if (countTypeReward > 20) {
  2890. correctShowOpenArtifact = 3;
  2891. } else {
  2892. correctShowOpenArtifact = 0;
  2893. }
  2894. /**
  2895. * Sum the result of opening Pet Eggs
  2896. * Суммирование результата открытия яиц питомцев
  2897. */
  2898. if (isChecked('countControl') && call.ident == callsIdent['pet_chestOpen']) {
  2899. const rewards = call.result.response.rewards;
  2900. if (rewards.length > 10) {
  2901. /**
  2902. * Removing pet cards
  2903. * Убираем карточки петов
  2904. */
  2905. for (const reward of rewards) {
  2906. if (reward.petCard) {
  2907. delete reward.petCard;
  2908. }
  2909. }
  2910. }
  2911. rewards.forEach(e => {
  2912. for (let f in e) {
  2913. if (!allReward[f]) {
  2914. allReward[f] = {};
  2915. }
  2916. for (let o in e[f]) {
  2917. if (!allReward[f][o]) {
  2918. allReward[f][o] = e[f][o];
  2919. } else {
  2920. allReward[f][o] += e[f][o];
  2921. }
  2922. }
  2923. }
  2924. });
  2925. call.result.response.rewards = [allReward];
  2926. isChange = true;
  2927. }
  2928. /**
  2929. * Removing titan cards
  2930. * Убираем карточки титанов
  2931. */
  2932. if (call.ident == callsIdent['titanUseSummonCircle']) {
  2933. if (call.result.response.rewards.length > 10) {
  2934. for (const reward of call.result.response.rewards) {
  2935. if (reward.titanCard) {
  2936. delete reward.titanCard;
  2937. }
  2938. }
  2939. isChange = true;
  2940. }
  2941. }
  2942. /**
  2943. * Auto-repeat opening matryoshkas
  2944. * АвтоПовтор открытия матрешек
  2945. */
  2946. if (isChecked('countControl') && call.ident == callsIdent['consumableUseLootBox']) {
  2947. let [countLootBox, lootBox] = Object.entries(call.result.response).pop();
  2948. countLootBox = +countLootBox;
  2949. let newCount = 0;
  2950. if (lootBox?.consumable && lootBox.consumable[lastRussianDollId]) {
  2951. newCount += lootBox.consumable[lastRussianDollId];
  2952. delete lootBox.consumable[lastRussianDollId];
  2953. }
  2954. if (
  2955. newCount &&
  2956. (await popup.confirm(`${I18N('BTN_OPEN')} ${newCount} ${I18N('OPEN_DOLLS')}?`, [
  2957. { msg: I18N('BTN_OPEN'), result: true },
  2958. { msg: I18N('BTN_NO'), result: false, isClose: true },
  2959. ]))
  2960. ) {
  2961. const [count, recursionResult] = await openRussianDolls(lastRussianDollId, newCount);
  2962. countLootBox += +count;
  2963. mergeItemsObj(lootBox, recursionResult);
  2964. isChange = true;
  2965. }
  2966.  
  2967. if (this.massOpen) {
  2968. if (
  2969. await popup.confirm(I18N('OPEN_ALL_EQUIP_BOXES'), [
  2970. { msg: I18N('BTN_OPEN'), result: true },
  2971. { msg: I18N('BTN_NO'), result: false, isClose: true },
  2972. ])
  2973. ) {
  2974. const consumable = await Send({ calls: [{ name: 'inventoryGet', args: {}, ident: 'inventoryGet' }] }).then((e) =>
  2975. Object.entries(e.results[0].result.response.consumable)
  2976. );
  2977. const calls = [];
  2978. const deleteItems = {};
  2979. for (const [libId, amount] of consumable) {
  2980. if (libId != this.massOpen && libId >= 362 && libId <= 389) {
  2981. calls.push({
  2982. name: 'consumableUseLootBox',
  2983. args: { libId, amount },
  2984. ident: 'consumableUseLootBox_' + libId,
  2985. });
  2986. deleteItems[libId] = -amount;
  2987. }
  2988. }
  2989. const responses = await Send({ calls }).then((e) => e.results.map((r) => r.result.response).flat());
  2990.  
  2991. for (const loot of responses) {
  2992. const [count, result] = Object.entries(loot).pop();
  2993. countLootBox += +count;
  2994.  
  2995. mergeItemsObj(lootBox, result);
  2996. }
  2997. isChange = true;
  2998.  
  2999. this.onReadySuccess = () => {
  3000. cheats.updateInventory({ consumable: deleteItems });
  3001. cheats.refreshInventory();
  3002. };
  3003. }
  3004. }
  3005.  
  3006. if (isChange) {
  3007. call.result.response = {
  3008. [countLootBox]: lootBox,
  3009. };
  3010. }
  3011. }
  3012. /**
  3013. * Dungeon recalculation (fix endless cards)
  3014. * Прерасчет подземки (исправление бесконечных карт)
  3015. */
  3016. if (call.ident == callsIdent['dungeonStartBattle']) {
  3017. lastDungeonBattleData = call.result.response;
  3018. lastDungeonBattleStart = Date.now();
  3019. }
  3020. /**
  3021. * Getting the number of prediction cards
  3022. * Получение количества карт предсказаний
  3023. */
  3024. if (call.ident == callsIdent['inventoryGet']) {
  3025. countPredictionCard = call.result.response.consumable[81] || 0;
  3026. }
  3027. /**
  3028. * Getting subscription status
  3029. * Получение состояния подписки
  3030. */
  3031. if (call.ident == callsIdent['subscriptionGetInfo']) {
  3032. const subscription = call.result.response.subscription;
  3033. if (subscription) {
  3034. subEndTime = subscription.endTime * 1000;
  3035. }
  3036. }
  3037. /**
  3038. * Getting prediction cards
  3039. * Получение карт предсказаний
  3040. */
  3041. if (call.ident == callsIdent['questFarm']) {
  3042. const consumable = call.result.response?.consumable;
  3043. if (consumable && consumable[81]) {
  3044. countPredictionCard += consumable[81];
  3045. console.log(`Cards: ${countPredictionCard}`);
  3046. }
  3047. }
  3048. /**
  3049. * Hiding extra servers
  3050. * Скрытие лишних серверов
  3051. */
  3052. if (call.ident == callsIdent['serverGetAll'] && isChecked('hideServers')) {
  3053. let servers = call.result.response.users.map(s => s.serverId)
  3054. call.result.response.servers = call.result.response.servers.filter(s => servers.includes(s.id));
  3055. isChange = true;
  3056. }
  3057. /**
  3058. * Displays player positions in the adventure
  3059. * Отображает позиции игроков в приключении
  3060. */
  3061. if (call.ident == callsIdent['adventure_getLobbyInfo']) {
  3062. const users = Object.values(call.result.response.users);
  3063. const mapIdent = call.result.response.mapIdent;
  3064. const adventureId = call.result.response.adventureId;
  3065. const maps = {
  3066. adv_strongford_3pl_hell: 9,
  3067. adv_valley_3pl_hell: 10,
  3068. adv_ghirwil_3pl_hell: 11,
  3069. adv_angels_3pl_hell: 12,
  3070. }
  3071. let msg = I18N('MAP') + (mapIdent in maps ? maps[mapIdent] : adventureId);
  3072. msg += '<br>' + I18N('PLAYER_POS');
  3073. for (const user of users) {
  3074. msg += `<br>${user.user.name} - ${user.currentNode}`;
  3075. }
  3076. setProgress(msg, false, hideProgress);
  3077. }
  3078. /**
  3079. * Automatic launch of a raid at the end of the adventure
  3080. * Автоматический запуск рейда при окончании приключения
  3081. */
  3082. if (call.ident == callsIdent['adventure_end']) {
  3083. autoRaidAdventure()
  3084. }
  3085. /** Удаление лавки редкостей */
  3086. if (call.ident == callsIdent['missionRaid']) {
  3087. if (call.result?.heroesMerchant) {
  3088. delete call.result.heroesMerchant;
  3089. isChange = true;
  3090. }
  3091. }
  3092. /** missionTimer */
  3093. if (call.ident == callsIdent['missionStart']) {
  3094. missionBattle = call.result.response;
  3095. }
  3096. /** Награды турнира стихий */
  3097. if (call.ident == callsIdent['hallOfFameGetTrophies']) {
  3098. const trophys = call.result.response;
  3099. const calls = [];
  3100. for (const week in trophys) {
  3101. const trophy = trophys[week];
  3102. if (!trophy.championRewardFarmed) {
  3103. calls.push({
  3104. name: 'hallOfFameFarmTrophyReward',
  3105. args: { trophyId: week, rewardType: 'champion' },
  3106. ident: 'body_champion_' + week,
  3107. });
  3108. }
  3109. if (Object.keys(trophy.clanReward).length && !trophy.clanRewardFarmed) {
  3110. calls.push({
  3111. name: 'hallOfFameFarmTrophyReward',
  3112. args: { trophyId: week, rewardType: 'clan' },
  3113. ident: 'body_clan_' + week,
  3114. });
  3115. }
  3116. }
  3117. if (calls.length) {
  3118. Send({ calls })
  3119. .then((e) => e.results.map((e) => e.result.response))
  3120. .then(async results => {
  3121. let coin18 = 0,
  3122. coin19 = 0,
  3123. gold = 0,
  3124. starmoney = 0;
  3125. for (const r of results) {
  3126. coin18 += r?.coin ? +r.coin[18] : 0;
  3127. coin19 += r?.coin ? +r.coin[19] : 0;
  3128. gold += r?.gold ? +r.gold : 0;
  3129. starmoney += r?.starmoney ? +r.starmoney : 0;
  3130. }
  3131.  
  3132. let msg = I18N('ELEMENT_TOURNAMENT_REWARD') + '<br>';
  3133. if (coin18) {
  3134. msg += cheats.translate('LIB_COIN_NAME_18') + `: ${coin18}<br>`;
  3135. }
  3136. if (coin19) {
  3137. msg += cheats.translate('LIB_COIN_NAME_19') + `: ${coin19}<br>`;
  3138. }
  3139. if (gold) {
  3140. msg += cheats.translate('LIB_PSEUDO_COIN') + `: ${gold}<br>`;
  3141. }
  3142. if (starmoney) {
  3143. msg += cheats.translate('LIB_PSEUDO_STARMONEY') + `: ${starmoney}<br>`;
  3144. }
  3145.  
  3146. await popup.confirm(msg, [{ msg: I18N('BTN_OK'), result: 0 }]);
  3147. });
  3148. }
  3149. }
  3150. if (call.ident == callsIdent['clanDomination_getInfo']) {
  3151. clanDominationGetInfo = call.result.response;
  3152. }
  3153. if (call.ident == callsIdent['clanRaid_endBossBattle']) {
  3154. console.log(call.result.response);
  3155. const damage = Object.values(call.result.response.damage).reduce((a, e) => a + e);
  3156. if (call.result.response.result.afterInvalid) {
  3157. addProgress('<br>' + I18N('SERVER_NOT_ACCEPT'));
  3158. }
  3159. addProgress('<br>Server > ' + I18N('BOSS_DAMAGE') + damage.toLocaleString());
  3160. }
  3161. if (call.ident == callsIdent['invasion_getInfo']) {
  3162. const r = call.result.response;
  3163. if (r?.actions?.length) {
  3164. const boss = r.actions.find((e) => e.payload.id === 225);
  3165. invasionInfo.buff = r.buffAmount;
  3166. invasionInfo.bossLvl = boss.payload.level;
  3167. if (isChecked('tryFixIt_v2')) {
  3168. const pack = invasionDataPacks[invasionInfo.bossLvl];
  3169. setProgress(
  3170. I18N('INVASION_BOSS_BUFF', {
  3171. bossLvl: invasionInfo.bossLvl,
  3172. needBuff: pack.buff,
  3173. haveBuff: invasionInfo.buff
  3174. }),
  3175. false
  3176. );
  3177. }
  3178. }
  3179. }
  3180. if (call.ident == callsIdent['workshopBuff_create']) {
  3181. const r = call.result.response;
  3182. if (r.id == 1) {
  3183. invasionInfo.buff = r.amount;
  3184. if (isChecked('tryFixIt_v2')) {
  3185. const pack = invasionDataPacks[invasionInfo.bossLvl];
  3186. setProgress(
  3187. I18N('INVASION_BOSS_BUFF', {
  3188. bossLvl: invasionInfo.bossLvl,
  3189. needBuff: pack.buff,
  3190. haveBuff: invasionInfo.buff,
  3191. }),
  3192. false
  3193. );
  3194. }
  3195. }
  3196. }
  3197. /*
  3198. if (call.ident == callsIdent['chatGetAll'] && call.args.chatType == 'clanDomination' && !callsIdent['clanDomination_mapState']) {
  3199. this.onReadySuccess = async function () {
  3200. const result = await Send({
  3201. calls: [
  3202. {
  3203. name: 'clanDomination_mapState',
  3204. args: {},
  3205. ident: 'clanDomination_mapState',
  3206. },
  3207. ],
  3208. }).then((e) => e.results[0].result.response);
  3209. let townPositions = result.townPositions;
  3210. let positions = {};
  3211. for (let pos in townPositions) {
  3212. let townPosition = townPositions[pos];
  3213. positions[townPosition.position] = townPosition;
  3214. }
  3215. Object.assign(clanDominationGetInfo, {
  3216. townPositions: positions,
  3217. });
  3218. let userPositions = result.userPositions;
  3219. for (let pos in clanDominationGetInfo.townPositions) {
  3220. let townPosition = clanDominationGetInfo.townPositions[pos];
  3221. if (townPosition.status) {
  3222. userPositions[townPosition.userId] = +pos;
  3223. }
  3224. }
  3225. cheats.updateMap(result);
  3226. };
  3227. }
  3228. if (call.ident == callsIdent['clanDomination_mapState']) {
  3229. const townPositions = call.result.response.townPositions;
  3230. const userPositions = call.result.response.userPositions;
  3231. for (let pos in townPositions) {
  3232. let townPos = townPositions[pos];
  3233. if (townPos.status) {
  3234. userPositions[townPos.userId] = townPos.position;
  3235. }
  3236. }
  3237. isChange = true;
  3238. }
  3239. */
  3240. }
  3241.  
  3242. if (mainReward && artifactChestOpen) {
  3243. console.log(allReward);
  3244. mainReward[artifactChestOpenCallName == 'artifactChestOpen' ? 'chestReward' : 'reward'] = [allReward];
  3245. artifactChestOpen = false;
  3246. artifactChestOpenCallName = '';
  3247. isChange = true;
  3248. }
  3249. } catch(err) {
  3250. console.log("Request(response, " + this.uniqid + "):\n", "Error:\n", response, err);
  3251. }
  3252.  
  3253. if (isChange) {
  3254. Object.defineProperty(this, 'responseText', {
  3255. writable: true
  3256. });
  3257. this.responseText = JSON.stringify(respond);
  3258. }
  3259. }
  3260.  
  3261. /**
  3262. * Request an answer to a question
  3263. *
  3264. * Запрос ответа на вопрос
  3265. */
  3266. async function getAnswer(question) {
  3267. // c29tZSBzdHJhbmdlIHN5bWJvbHM=
  3268. const quizAPI = new ZingerYWebsiteAPI('getAnswer.php', arguments, { question });
  3269. return new Promise((resolve, reject) => {
  3270. quizAPI.request().then((data) => {
  3271. if (data.result) {
  3272. resolve(data.result);
  3273. } else {
  3274. resolve(false);
  3275. }
  3276. }).catch((error) => {
  3277. console.error(error);
  3278. resolve(false);
  3279. });
  3280. })
  3281. }
  3282.  
  3283. /**
  3284. * Submitting a question and answer to a database
  3285. *
  3286. * Отправка вопроса и ответа в базу данных
  3287. */
  3288. function sendAnswerInfo(answerInfo) {
  3289. // c29tZSBub25zZW5zZQ==
  3290. const quizAPI = new ZingerYWebsiteAPI('setAnswer.php', arguments, { answerInfo });
  3291. quizAPI.request().then((data) => {
  3292. if (data.result) {
  3293. console.log(I18N('SENT_QUESTION'));
  3294. }
  3295. });
  3296. }
  3297.  
  3298. /**
  3299. * Returns the battle type by preset type
  3300. *
  3301. * Возвращает тип боя по типу пресета
  3302. */
  3303. function getBattleType(strBattleType) {
  3304. if (!strBattleType) {
  3305. return null;
  3306. }
  3307. switch (strBattleType) {
  3308. case 'titan_pvp':
  3309. return 'get_titanPvp';
  3310. case 'titan_pvp_manual':
  3311. case 'titan_clan_pvp':
  3312. case 'clan_pvp_titan':
  3313. case 'clan_global_pvp_titan':
  3314. case 'brawl_titan':
  3315. case 'challenge_titan':
  3316. case 'titan_mission':
  3317. return 'get_titanPvpManual';
  3318. case 'clan_raid': // Asgard Boss // Босс асгарда
  3319. case 'adventure': // Adventures // Приключения
  3320. case 'clan_global_pvp':
  3321. case 'epic_brawl':
  3322. case 'clan_pvp':
  3323. return 'get_clanPvp';
  3324. case 'dungeon_titan':
  3325. case 'titan_tower':
  3326. return 'get_titan';
  3327. case 'tower':
  3328. case 'clan_dungeon':
  3329. return 'get_tower';
  3330. case 'pve':
  3331. case 'mission':
  3332. return 'get_pve';
  3333. case 'mission_boss':
  3334. return 'get_missionBoss';
  3335. case 'challenge':
  3336. case 'pvp_manual':
  3337. return 'get_pvpManual';
  3338. case 'grand':
  3339. case 'arena':
  3340. case 'pvp':
  3341. case 'clan_domination':
  3342. return 'get_pvp';
  3343. case 'core':
  3344. return 'get_core';
  3345. default: {
  3346. if (strBattleType.includes('invasion')) {
  3347. return 'get_invasion';
  3348. }
  3349. if (strBattleType.includes('boss')) {
  3350. return 'get_boss';
  3351. }
  3352. if (strBattleType.includes('titan_arena')) {
  3353. return 'get_titanPvpManual';
  3354. }
  3355. return 'get_clanPvp';
  3356. }
  3357. }
  3358. }
  3359. /**
  3360. * Returns the class name of the passed object
  3361. *
  3362. * Возвращает название класса переданного объекта
  3363. */
  3364. function getClass(obj) {
  3365. return {}.toString.call(obj).slice(8, -1);
  3366. }
  3367. /**
  3368. * Calculates the request signature
  3369. *
  3370. * Расчитывает сигнатуру запроса
  3371. */
  3372. this.getSignature = function(headers, data) {
  3373. const sign = {
  3374. signature: '',
  3375. length: 0,
  3376. add: function (text) {
  3377. this.signature += text;
  3378. if (this.length < this.signature.length) {
  3379. this.length = 3 * (this.signature.length + 1) >> 1;
  3380. }
  3381. },
  3382. }
  3383. sign.add(headers["X-Request-Id"]);
  3384. sign.add(':');
  3385. sign.add(headers["X-Auth-Token"]);
  3386. sign.add(':');
  3387. sign.add(headers["X-Auth-Session-Id"]);
  3388. sign.add(':');
  3389. sign.add(data);
  3390. sign.add(':');
  3391. sign.add('LIBRARY-VERSION=1');
  3392. sign.add('UNIQUE-SESSION-ID=' + headers["X-Env-Unique-Session-Id"]);
  3393.  
  3394. return md5(sign.signature);
  3395. }
  3396.  
  3397. class HotkeyManager {
  3398. constructor() {
  3399. if (HotkeyManager.instance) {
  3400. return HotkeyManager.instance;
  3401. }
  3402. this.hotkeys = [];
  3403. document.addEventListener('keydown', this.handleKeyDown.bind(this));
  3404. HotkeyManager.instance = this;
  3405. }
  3406.  
  3407. handleKeyDown(event) {
  3408. const key = event.key.toLowerCase();
  3409. const mods = {
  3410. ctrl: event.ctrlKey,
  3411. alt: event.altKey,
  3412. shift: event.shiftKey,
  3413. };
  3414.  
  3415. this.hotkeys.forEach((hotkey) => {
  3416. if (hotkey.key === key && hotkey.ctrl === mods.ctrl && hotkey.alt === mods.alt && hotkey.shift === mods.shift) {
  3417. hotkey.callback(hotkey);
  3418. }
  3419. });
  3420. }
  3421.  
  3422. add(key, opt = {}, callback) {
  3423. this.hotkeys.push({
  3424. key: key.toLowerCase(),
  3425. callback,
  3426. ctrl: opt.ctrl || false,
  3427. alt: opt.alt || false,
  3428. shift: opt.shift || false,
  3429. });
  3430. }
  3431.  
  3432. remove(key, opt = {}) {
  3433. this.hotkeys = this.hotkeys.filter((hotkey) => {
  3434. return !(
  3435. hotkey.key === key.toLowerCase() &&
  3436. hotkey.ctrl === (opt.ctrl || false) &&
  3437. hotkey.alt === (opt.alt || false) &&
  3438. hotkey.shift === (opt.shift || false)
  3439. );
  3440. });
  3441. }
  3442.  
  3443. static getInst() {
  3444. if (!HotkeyManager.instance) {
  3445. new HotkeyManager();
  3446. }
  3447. return HotkeyManager.instance;
  3448. }
  3449. }
  3450.  
  3451. class MouseClicker {
  3452. constructor(element) {
  3453. if (MouseClicker.instance) {
  3454. return MouseClicker.instance;
  3455. }
  3456. this.element = element;
  3457. this.mouse = {
  3458. bubbles: true,
  3459. cancelable: true,
  3460. clientX: 0,
  3461. clientY: 0,
  3462. };
  3463. this.element.addEventListener('mousemove', this.handleMouseMove.bind(this));
  3464. this.clickInfo = {};
  3465. this.nextTimeoutId = 1;
  3466. MouseClicker.instance = this;
  3467. }
  3468.  
  3469. handleMouseMove(event) {
  3470. this.mouse.clientX = event.clientX;
  3471. this.mouse.clientY = event.clientY;
  3472. }
  3473.  
  3474. click(options) {
  3475. options = options || this.mouse;
  3476. this.element.dispatchEvent(new MouseEvent('mousedown', options));
  3477. this.element.dispatchEvent(new MouseEvent('mouseup', options));
  3478. }
  3479.  
  3480. start(interval = 1000, clickCount = Infinity) {
  3481. const currentMouse = { ...this.mouse };
  3482. const timeoutId = this.nextTimeoutId++;
  3483. let count = 0;
  3484.  
  3485. const clickTimeout = () => {
  3486. this.click(currentMouse);
  3487. count++;
  3488. if (count < clickCount) {
  3489. this.clickInfo[timeoutId].timeout = setTimeout(clickTimeout, interval);
  3490. } else {
  3491. delete this.clickInfo[timeoutId];
  3492. }
  3493. };
  3494.  
  3495. this.clickInfo[timeoutId] = {
  3496. timeout: setTimeout(clickTimeout, interval),
  3497. count: clickCount,
  3498. };
  3499. return timeoutId;
  3500. }
  3501.  
  3502. stop(timeoutId) {
  3503. if (this.clickInfo[timeoutId]) {
  3504. clearTimeout(this.clickInfo[timeoutId].timeout);
  3505. delete this.clickInfo[timeoutId];
  3506. }
  3507. }
  3508.  
  3509. stopAll() {
  3510. for (const timeoutId in this.clickInfo) {
  3511. clearTimeout(this.clickInfo[timeoutId].timeout);
  3512. }
  3513. this.clickInfo = {};
  3514. }
  3515.  
  3516. static getInst(element) {
  3517. if (!MouseClicker.instance) {
  3518. new MouseClicker(element);
  3519. }
  3520. return MouseClicker.instance;
  3521. }
  3522. }
  3523.  
  3524. let extintionsList = [];
  3525. /**
  3526. * Creates an interface
  3527. *
  3528. * Создает интерфейс
  3529. */
  3530. function createInterface() {
  3531. popup.init();
  3532. scriptMenu.init({
  3533. showMenu: true
  3534. });
  3535. scriptMenu.addHeader(GM_info.script.name, justInfo);
  3536. const versionHeader = scriptMenu.addHeader('v' + GM_info.script.version);
  3537. if (extintionsList.length) {
  3538. versionHeader.title = '';
  3539. versionHeader.style.color = 'red';
  3540. for (const extintion of extintionsList) {
  3541. const { name, ver, author } = extintion;
  3542. versionHeader.title += name + ', v' + ver + ' by ' + author + '\n';
  3543. }
  3544. }
  3545. // AutoClicker
  3546. const hkm = new HotkeyManager();
  3547. const fc = document.getElementById('flash-content') || document.getElementById('game');
  3548. const mc = new MouseClicker(fc);
  3549. function toggleClicker(self, timeout) {
  3550. if (self.onClick) {
  3551. console.log('Останавливаем клики');
  3552. mc.stop(self.onClick);
  3553. self.onClick = false;
  3554. } else {
  3555. console.log('Стартуем клики');
  3556. self.onClick = mc.start(timeout);
  3557. }
  3558. }
  3559. hkm.add('C', { ctrl: true, alt: true }, (self) => {
  3560. console.log('"Ctrl + Alt + C"');
  3561. toggleClicker(self, 20);
  3562. });
  3563. hkm.add('V', { ctrl: true, alt: true }, (self) => {
  3564. console.log('"Ctrl + Alt + V"');
  3565. toggleClicker(self, 100);
  3566. });
  3567. }
  3568.  
  3569. function addExtentionName(name, ver, author) {
  3570. extintionsList.push({
  3571. name,
  3572. ver,
  3573. author,
  3574. });
  3575. }
  3576.  
  3577. function addControls() {
  3578. createInterface();
  3579. const checkboxDetails = scriptMenu.addDetails(I18N('SETTINGS'));
  3580. for (let name in checkboxes) {
  3581. if (checkboxes[name].hide) {
  3582. continue;
  3583. }
  3584. checkboxes[name].cbox = scriptMenu.addCheckbox(checkboxes[name].label, checkboxes[name].title, checkboxDetails);
  3585. /**
  3586. * Getting the state of checkboxes from storage
  3587. * Получаем состояние чекбоксов из storage
  3588. */
  3589. let val = storage.get(name, null);
  3590. if (val != null) {
  3591. checkboxes[name].cbox.checked = val;
  3592. } else {
  3593. storage.set(name, checkboxes[name].default);
  3594. checkboxes[name].cbox.checked = checkboxes[name].default;
  3595. }
  3596. /**
  3597. * Tracing the change event of the checkbox for writing to storage
  3598. * Отсеживание события изменения чекбокса для записи в storage
  3599. */
  3600. checkboxes[name].cbox.dataset['name'] = name;
  3601. checkboxes[name].cbox.addEventListener('change', async function (event) {
  3602. const nameCheckbox = this.dataset['name'];
  3603. /*
  3604. if (this.checked && nameCheckbox == 'cancelBattle') {
  3605. this.checked = false;
  3606. if (await popup.confirm(I18N('MSG_BAN_ATTENTION'), [
  3607. { msg: I18N('BTN_NO_I_AM_AGAINST'), result: true },
  3608. { msg: I18N('BTN_YES_I_AGREE'), result: false },
  3609. ])) {
  3610. return;
  3611. }
  3612. this.checked = true;
  3613. }
  3614. */
  3615. storage.set(nameCheckbox, this.checked);
  3616. })
  3617. }
  3618.  
  3619. const inputDetails = scriptMenu.addDetails(I18N('VALUES'));
  3620. for (let name in inputs) {
  3621. inputs[name].input = scriptMenu.addInputText(inputs[name].title, false, inputDetails);
  3622. /**
  3623. * Get inputText state from storage
  3624. * Получаем состояние inputText из storage
  3625. */
  3626. let val = storage.get(name, null);
  3627. if (val != null) {
  3628. inputs[name].input.value = val;
  3629. } else {
  3630. storage.set(name, inputs[name].default);
  3631. inputs[name].input.value = inputs[name].default;
  3632. }
  3633. /**
  3634. * Tracing a field change event for a record in storage
  3635. * Отсеживание события изменения поля для записи в storage
  3636. */
  3637. inputs[name].input.dataset['name'] = name;
  3638. inputs[name].input.addEventListener('input', function () {
  3639. const inputName = this.dataset['name'];
  3640. let value = +this.value;
  3641. if (!value || Number.isNaN(value)) {
  3642. value = storage.get(inputName, inputs[inputName].default);
  3643. inputs[name].input.value = value;
  3644. }
  3645. storage.set(inputName, value);
  3646. })
  3647. }
  3648. }
  3649.  
  3650. /**
  3651. * Sending a request
  3652. *
  3653. * Отправка запроса
  3654. */
  3655. function send(json, callback, pr) {
  3656. if (typeof json == 'string') {
  3657. json = JSON.parse(json);
  3658. }
  3659. for (const call of json.calls) {
  3660. if (!call?.context?.actionTs) {
  3661. call.context = {
  3662. actionTs: Math.floor(performance.now())
  3663. }
  3664. }
  3665. }
  3666. json = JSON.stringify(json);
  3667. /**
  3668. * We get the headlines of the previous intercepted request
  3669. * Получаем заголовки предыдущего перехваченого запроса
  3670. */
  3671. let headers = lastHeaders;
  3672. /**
  3673. * We increase the header of the query Certifier by 1
  3674. * Увеличиваем заголовок идетификатора запроса на 1
  3675. */
  3676. headers["X-Request-Id"]++;
  3677. /**
  3678. * We calculate the title with the signature
  3679. * Расчитываем заголовок с сигнатурой
  3680. */
  3681. headers["X-Auth-Signature"] = getSignature(headers, json);
  3682. /**
  3683. * Create a new ajax request
  3684. * Создаем новый AJAX запрос
  3685. */
  3686. let xhr = new XMLHttpRequest;
  3687. /**
  3688. * Indicate the previously saved URL for API queries
  3689. * Указываем ранее сохраненный URL для API запросов
  3690. */
  3691. xhr.open('POST', apiUrl, true);
  3692. /**
  3693. * Add the function to the event change event
  3694. * Добавляем функцию к событию смены статуса запроса
  3695. */
  3696. xhr.onreadystatechange = function() {
  3697. /**
  3698. * If the result of the request is obtained, we call the flask function
  3699. * Если результат запроса получен вызываем колбек функцию
  3700. */
  3701. if(xhr.readyState == 4) {
  3702. callback(xhr.response, pr);
  3703. }
  3704. };
  3705. /**
  3706. * Indicate the type of request
  3707. * Указываем тип запроса
  3708. */
  3709. xhr.responseType = 'json';
  3710. /**
  3711. * We set the request headers
  3712. * Задаем заголовки запроса
  3713. */
  3714. for(let nameHeader in headers) {
  3715. let head = headers[nameHeader];
  3716. xhr.setRequestHeader(nameHeader, head);
  3717. }
  3718. /**
  3719. * Sending a request
  3720. * Отправляем запрос
  3721. */
  3722. xhr.send(json);
  3723. }
  3724.  
  3725. let hideTimeoutProgress = 0;
  3726. /**
  3727. * Hide progress
  3728. *
  3729. * Скрыть прогресс
  3730. */
  3731. function hideProgress(timeout) {
  3732. timeout = timeout || 0;
  3733. clearTimeout(hideTimeoutProgress);
  3734. hideTimeoutProgress = setTimeout(function () {
  3735. scriptMenu.setStatus('');
  3736. }, timeout);
  3737. }
  3738. /**
  3739. * Progress display
  3740. *
  3741. * Отображение прогресса
  3742. */
  3743. function setProgress(text, hide, onclick) {
  3744. scriptMenu.setStatus(text, onclick);
  3745. hide = hide || false;
  3746. if (hide) {
  3747. hideProgress(3000);
  3748. }
  3749. }
  3750.  
  3751. /**
  3752. * Progress added
  3753. *
  3754. * Дополнение прогресса
  3755. */
  3756. function addProgress(text) {
  3757. scriptMenu.addStatus(text);
  3758. }
  3759.  
  3760. /**
  3761. * Returns the timer value depending on the subscription
  3762. *
  3763. * Возвращает значение таймера в зависимости от подписки
  3764. */
  3765. function getTimer(time, div) {
  3766. let speedDiv = 5;
  3767. if (subEndTime < Date.now()) {
  3768. speedDiv = div || 1.5;
  3769. }
  3770. return Math.max(Math.ceil(time / speedDiv + 1.5), 4);
  3771. }
  3772.  
  3773. function startSlave() {
  3774. const { slaveFixBattle } = HWHClasses;
  3775. const sFix = new slaveFixBattle();
  3776. sFix.wsStart();
  3777. }
  3778.  
  3779. this.testFuntions = {
  3780. hideProgress,
  3781. setProgress,
  3782. addProgress,
  3783. masterFix: false,
  3784. startSlave,
  3785. };
  3786.  
  3787. this.HWHFuncs = {
  3788. send,
  3789. I18N,
  3790. isChecked,
  3791. getInput,
  3792. copyText,
  3793. confShow,
  3794. hideProgress,
  3795. setProgress,
  3796. addProgress,
  3797. getTimer,
  3798. addExtentionName,
  3799. getUserInfo,
  3800. setIsCancalBattle,
  3801. random,
  3802. };
  3803.  
  3804. this.HWHClasses = {
  3805. checkChangeSend,
  3806. checkChangeResponse,
  3807. };
  3808. /**
  3809. * Calculates HASH MD5 from string
  3810. *
  3811. * Расчитывает HASH MD5 из строки
  3812. *
  3813. * [js-md5]{@link https://github.com/emn178/js-md5}
  3814. *
  3815. * @namespace md5
  3816. * @version 0.7.3
  3817. * @author Chen, Yi-Cyuan [emn178@gmail.com]
  3818. * @copyright Chen, Yi-Cyuan 2014-2017
  3819. * @license MIT
  3820. */
  3821. !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 _}))}();
  3822.  
  3823. class Caller {
  3824. static globalHooks = {
  3825. onError: null,
  3826. };
  3827.  
  3828. constructor(calls = null) {
  3829. this.calls = [];
  3830. this.results = {};
  3831. if (calls) {
  3832. this.add(calls);
  3833. }
  3834. }
  3835.  
  3836. static setGlobalHook(event, callback) {
  3837. if (this.globalHooks[event] !== undefined) {
  3838. this.globalHooks[event] = callback;
  3839. } else {
  3840. throw new Error(`Unknown event: ${event}`);
  3841. }
  3842. }
  3843.  
  3844. addCall(call) {
  3845. const { name = call, args = {} } = typeof call === 'object' ? call : { name: call };
  3846. this.calls.push({ name, args });
  3847. return this;
  3848. }
  3849.  
  3850. add(name) {
  3851. if (Array.isArray(name)) {
  3852. name.forEach((call) => this.addCall(call));
  3853. } else {
  3854. this.addCall(name);
  3855. }
  3856. return this;
  3857. }
  3858.  
  3859. handleError(error) {
  3860. const errorName = error.name;
  3861. const errorDescription = error.description;
  3862.  
  3863. if (Caller.globalHooks.onError) {
  3864. const shouldThrow = Caller.globalHooks.onError(error);
  3865. if (shouldThrow === false) {
  3866. return;
  3867. }
  3868. }
  3869.  
  3870. if (error.call) {
  3871. const callInfo = error.call;
  3872. throw new Error(`${errorName} in ${callInfo.name}: ${errorDescription}\n` + `Args: ${JSON.stringify(callInfo.args)}\n`);
  3873. } else if (errorName === 'common\\rpc\\exception\\InvalidRequest') {
  3874. throw new Error(`Invalid request: ${errorDescription}`);
  3875. } else {
  3876. throw new Error(`Unknown error: ${errorName} - ${errorDescription}`);
  3877. }
  3878. }
  3879.  
  3880. async send() {
  3881. if (!this.calls.length) {
  3882. throw new Error('No calls to send.');
  3883. }
  3884.  
  3885. const identToNameMap = {};
  3886. const callsWithIdent = this.calls.map((call, index) => {
  3887. const ident = this.calls.length === 1 ? 'body' : `group_${index}_body`;
  3888. identToNameMap[ident] = call.name;
  3889. return { ...call, ident };
  3890. });
  3891.  
  3892. try {
  3893. const response = await Send({ calls: callsWithIdent });
  3894.  
  3895. if (response.error) {
  3896. this.handleError(response.error);
  3897. }
  3898.  
  3899. if (!response.results) {
  3900. throw new Error('Invalid response format: missing "results" field');
  3901. }
  3902.  
  3903. response.results.forEach((result) => {
  3904. const name = identToNameMap[result.ident];
  3905. if (!this.results[name]) {
  3906. this.results[name] = [];
  3907. }
  3908. this.results[name].push(result.result.response);
  3909. });
  3910. } catch (error) {
  3911. throw error;
  3912. }
  3913. return this;
  3914. }
  3915.  
  3916. result(name, forceArray = false) {
  3917. const results = name ? this.results[name] || [] : Object.values(this.results).flat();
  3918. return forceArray || results.length !== 1 ? results : results[0];
  3919. }
  3920.  
  3921. async execute(name) {
  3922. try {
  3923. await this.send();
  3924. return this.result(name);
  3925. } catch (error) {
  3926. throw error;
  3927. }
  3928. }
  3929.  
  3930. clear() {
  3931. this.calls = [];
  3932. this.results = {};
  3933. return this;
  3934. }
  3935.  
  3936. isEmpty() {
  3937. return this.calls.length === 0 && Object.keys(this.results).length === 0;
  3938. }
  3939. }
  3940.  
  3941. this.Caller = Caller;
  3942.  
  3943. /*
  3944. // Примеры использования
  3945. (async () => {
  3946. // Короткий вызов
  3947. await new Caller('inventoryGet').execute();
  3948. // Простой вызов
  3949. let result = await new Caller().add('inventoryGet').execute();
  3950. console.log('Inventory Get Result:', result);
  3951.  
  3952. // Сложный вызов
  3953. let caller = new Caller();
  3954. await caller
  3955. .add([
  3956. {
  3957. name: 'inventoryGet',
  3958. args: {},
  3959. },
  3960. {
  3961. name: 'heroGetAll',
  3962. args: {},
  3963. },
  3964. ])
  3965. .send();
  3966. console.log('Inventory Get Result:', caller.result('inventoryGet'));
  3967. console.log('Hero Get All Result:', caller.result('heroGetAll'));
  3968.  
  3969. // Очистка всех данных
  3970. caller.clear();
  3971. })();
  3972. */
  3973.  
  3974. /**
  3975. * Script for beautiful dialog boxes
  3976. *
  3977. * Скрипт для красивых диалоговых окошек
  3978. */
  3979. const popup = new (function () {
  3980. this.popUp,
  3981. this.downer,
  3982. this.middle,
  3983. this.msgText,
  3984. this.buttons = [];
  3985. this.checkboxes = [];
  3986. this.dialogPromice = null;
  3987. this.isInit = false;
  3988.  
  3989. this.init = function () {
  3990. if (this.isInit) {
  3991. return;
  3992. }
  3993. addStyle();
  3994. addBlocks();
  3995. addEventListeners();
  3996. this.isInit = true;
  3997. }
  3998.  
  3999. const addEventListeners = () => {
  4000. document.addEventListener('keyup', (e) => {
  4001. if (e.key == 'Escape') {
  4002. if (this.dialogPromice) {
  4003. const { func, result } = this.dialogPromice;
  4004. this.dialogPromice = null;
  4005. popup.hide();
  4006. func(result);
  4007. }
  4008. }
  4009. });
  4010. }
  4011.  
  4012. const addStyle = () => {
  4013. let style = document.createElement('style');
  4014. style.innerText = `
  4015. .PopUp_ {
  4016. position: absolute;
  4017. min-width: 300px;
  4018. max-width: 500px;
  4019. max-height: 600px;
  4020. background-color: #190e08e6;
  4021. z-index: 10001;
  4022. top: 169px;
  4023. left: 345px;
  4024. border: 3px #ce9767 solid;
  4025. border-radius: 10px;
  4026. display: flex;
  4027. flex-direction: column;
  4028. justify-content: space-around;
  4029. padding: 15px 9px;
  4030. box-sizing: border-box;
  4031. }
  4032.  
  4033. .PopUp_back {
  4034. position: absolute;
  4035. background-color: #00000066;
  4036. width: 100%;
  4037. height: 100%;
  4038. z-index: 10000;
  4039. top: 0;
  4040. left: 0;
  4041. }
  4042.  
  4043. .PopUp_close {
  4044. width: 40px;
  4045. height: 40px;
  4046. position: absolute;
  4047. right: -18px;
  4048. top: -18px;
  4049. border: 3px solid #c18550;
  4050. border-radius: 20px;
  4051. background: radial-gradient(circle, rgba(190,30,35,1) 0%, rgba(0,0,0,1) 100%);
  4052. background-position-y: 3px;
  4053. box-shadow: -1px 1px 3px black;
  4054. cursor: pointer;
  4055. box-sizing: border-box;
  4056. }
  4057.  
  4058. .PopUp_close:hover {
  4059. filter: brightness(1.2);
  4060. }
  4061.  
  4062. .PopUp_crossClose {
  4063. width: 100%;
  4064. height: 100%;
  4065. background-size: 65%;
  4066. background-position: center;
  4067. background-repeat: no-repeat;
  4068. 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")
  4069. }
  4070.  
  4071. .PopUp_blocks {
  4072. width: 100%;
  4073. height: 50%;
  4074. display: flex;
  4075. justify-content: space-evenly;
  4076. align-items: center;
  4077. flex-wrap: wrap;
  4078. justify-content: center;
  4079. }
  4080.  
  4081. .PopUp_blocks:last-child {
  4082. margin-top: 25px;
  4083. }
  4084.  
  4085. .PopUp_buttons {
  4086. display: flex;
  4087. margin: 7px 10px;
  4088. flex-direction: column;
  4089. }
  4090.  
  4091. .PopUp_button {
  4092. background-color: #52A81C;
  4093. border-radius: 5px;
  4094. box-shadow: inset 0px -4px 10px, inset 0px 3px 2px #99fe20, 0px 0px 4px, 0px -3px 1px #d7b275, 0px 0px 0px 3px #ce9767;
  4095. cursor: pointer;
  4096. padding: 4px 12px 6px;
  4097. }
  4098.  
  4099. .PopUp_input {
  4100. text-align: center;
  4101. font-size: 16px;
  4102. height: 27px;
  4103. border: 1px solid #cf9250;
  4104. border-radius: 9px 9px 0px 0px;
  4105. background: transparent;
  4106. color: #fce1ac;
  4107. padding: 1px 10px;
  4108. box-sizing: border-box;
  4109. box-shadow: 0px 0px 4px, 0px 0px 0px 3px #ce9767;
  4110. }
  4111.  
  4112. .PopUp_checkboxes {
  4113. display: flex;
  4114. flex-direction: column;
  4115. margin: 15px 15px -5px 15px;
  4116. align-items: flex-start;
  4117. }
  4118.  
  4119. .PopUp_ContCheckbox {
  4120. margin: 2px 0px;
  4121. }
  4122.  
  4123. .PopUp_checkbox {
  4124. position: absolute;
  4125. z-index: -1;
  4126. opacity: 0;
  4127. }
  4128. .PopUp_checkbox+label {
  4129. display: inline-flex;
  4130. align-items: center;
  4131. user-select: none;
  4132.  
  4133. font-size: 15px;
  4134. font-family: sans-serif;
  4135. font-weight: 600;
  4136. font-stretch: condensed;
  4137. letter-spacing: 1px;
  4138. color: #fce1ac;
  4139. text-shadow: 0px 0px 1px;
  4140. }
  4141. .PopUp_checkbox+label::before {
  4142. content: '';
  4143. display: inline-block;
  4144. width: 20px;
  4145. height: 20px;
  4146. border: 1px solid #cf9250;
  4147. border-radius: 7px;
  4148. margin-right: 7px;
  4149. }
  4150. .PopUp_checkbox:checked+label::before {
  4151. 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");
  4152. }
  4153.  
  4154. .PopUp_input::placeholder {
  4155. color: #fce1ac75;
  4156. }
  4157.  
  4158. .PopUp_input:focus {
  4159. outline: 0;
  4160. }
  4161.  
  4162. .PopUp_input + .PopUp_button {
  4163. border-radius: 0px 0px 5px 5px;
  4164. padding: 2px 18px 5px;
  4165. }
  4166.  
  4167. .PopUp_button:hover {
  4168. filter: brightness(1.2);
  4169. }
  4170.  
  4171. .PopUp_button:active {
  4172. box-shadow: inset 0px 5px 10px, inset 0px 1px 2px #99fe20, 0px 0px 4px, 0px -3px 1px #d7b275, 0px 0px 0px 3px #ce9767;
  4173. }
  4174.  
  4175. .PopUp_text {
  4176. font-size: 22px;
  4177. font-family: sans-serif;
  4178. font-weight: 600;
  4179. font-stretch: condensed;
  4180. letter-spacing: 1px;
  4181. text-align: center;
  4182. }
  4183.  
  4184. .PopUp_buttonText {
  4185. color: #E4FF4C;
  4186. text-shadow: 0px 1px 2px black;
  4187. }
  4188.  
  4189. .PopUp_msgText {
  4190. color: #FDE5B6;
  4191. text-shadow: 0px 0px 2px;
  4192. }
  4193.  
  4194. .PopUp_hideBlock {
  4195. display: none;
  4196. }
  4197. `;
  4198. document.head.appendChild(style);
  4199. }
  4200.  
  4201. const addBlocks = () => {
  4202. this.back = document.createElement('div');
  4203. this.back.classList.add('PopUp_back');
  4204. this.back.classList.add('PopUp_hideBlock');
  4205. document.body.append(this.back);
  4206.  
  4207. this.popUp = document.createElement('div');
  4208. this.popUp.classList.add('PopUp_');
  4209. this.back.append(this.popUp);
  4210.  
  4211. let upper = document.createElement('div')
  4212. upper.classList.add('PopUp_blocks');
  4213. this.popUp.append(upper);
  4214.  
  4215. this.middle = document.createElement('div')
  4216. this.middle.classList.add('PopUp_blocks');
  4217. this.middle.classList.add('PopUp_checkboxes');
  4218. this.popUp.append(this.middle);
  4219.  
  4220. this.downer = document.createElement('div')
  4221. this.downer.classList.add('PopUp_blocks');
  4222. this.popUp.append(this.downer);
  4223.  
  4224. this.msgText = document.createElement('div');
  4225. this.msgText.classList.add('PopUp_text', 'PopUp_msgText');
  4226. upper.append(this.msgText);
  4227. }
  4228.  
  4229. this.showBack = function () {
  4230. this.back.classList.remove('PopUp_hideBlock');
  4231. }
  4232.  
  4233. this.hideBack = function () {
  4234. this.back.classList.add('PopUp_hideBlock');
  4235. }
  4236.  
  4237. this.show = function () {
  4238. if (this.checkboxes.length) {
  4239. this.middle.classList.remove('PopUp_hideBlock');
  4240. }
  4241. this.showBack();
  4242. this.popUp.classList.remove('PopUp_hideBlock');
  4243. this.popUp.style.left = (window.innerWidth - this.popUp.offsetWidth) / 2 + 'px';
  4244. this.popUp.style.top = (window.innerHeight - this.popUp.offsetHeight) / 3 + 'px';
  4245. }
  4246.  
  4247. this.hide = function () {
  4248. this.hideBack();
  4249. this.popUp.classList.add('PopUp_hideBlock');
  4250. }
  4251.  
  4252. this.addAnyButton = (option) => {
  4253. const contButton = document.createElement('div');
  4254. contButton.classList.add('PopUp_buttons');
  4255. this.downer.append(contButton);
  4256.  
  4257. let inputField = {
  4258. value: option.result || option.default
  4259. }
  4260. if (option.isInput) {
  4261. inputField = document.createElement('input');
  4262. inputField.type = 'text';
  4263. if (option.placeholder) {
  4264. inputField.placeholder = option.placeholder;
  4265. }
  4266. if (option.default) {
  4267. inputField.value = option.default;
  4268. }
  4269. inputField.classList.add('PopUp_input');
  4270. contButton.append(inputField);
  4271. }
  4272.  
  4273. const button = document.createElement('div');
  4274. button.classList.add('PopUp_button');
  4275. button.title = option.title || '';
  4276. contButton.append(button);
  4277.  
  4278. const buttonText = document.createElement('div');
  4279. buttonText.classList.add('PopUp_text', 'PopUp_buttonText');
  4280. buttonText.innerHTML = option.msg;
  4281. button.append(buttonText);
  4282.  
  4283. return { button, contButton, inputField };
  4284. }
  4285.  
  4286. this.addCloseButton = () => {
  4287. let button = document.createElement('div')
  4288. button.classList.add('PopUp_close');
  4289. this.popUp.append(button);
  4290.  
  4291. let crossClose = document.createElement('div')
  4292. crossClose.classList.add('PopUp_crossClose');
  4293. button.append(crossClose);
  4294.  
  4295. return { button, contButton: button };
  4296. }
  4297.  
  4298. this.addButton = (option, buttonClick) => {
  4299.  
  4300. const { button, contButton, inputField } = option.isClose ? this.addCloseButton() : this.addAnyButton(option);
  4301. if (option.isClose) {
  4302. this.dialogPromice = { func: buttonClick, result: option.result };
  4303. }
  4304. button.addEventListener('click', () => {
  4305. let result = '';
  4306. if (option.isInput) {
  4307. result = inputField.value;
  4308. }
  4309. if (option.isClose || option.isCancel) {
  4310. this.dialogPromice = null;
  4311. }
  4312. buttonClick(result);
  4313. });
  4314.  
  4315. this.buttons.push(contButton);
  4316. }
  4317.  
  4318. this.clearButtons = () => {
  4319. while (this.buttons.length) {
  4320. this.buttons.pop().remove();
  4321. }
  4322. }
  4323.  
  4324. this.addCheckBox = (checkBox) => {
  4325. const contCheckbox = document.createElement('div');
  4326. contCheckbox.classList.add('PopUp_ContCheckbox');
  4327. this.middle.append(contCheckbox);
  4328.  
  4329. const checkbox = document.createElement('input');
  4330. checkbox.type = 'checkbox';
  4331. checkbox.id = 'PopUpCheckbox' + this.checkboxes.length;
  4332. checkbox.dataset.name = checkBox.name;
  4333. checkbox.checked = checkBox.checked;
  4334. checkbox.label = checkBox.label;
  4335. checkbox.title = checkBox.title || '';
  4336. checkbox.classList.add('PopUp_checkbox');
  4337. contCheckbox.appendChild(checkbox)
  4338.  
  4339. const checkboxLabel = document.createElement('label');
  4340. checkboxLabel.innerText = checkBox.label;
  4341. checkboxLabel.title = checkBox.title || '';
  4342. checkboxLabel.setAttribute('for', checkbox.id);
  4343. contCheckbox.appendChild(checkboxLabel);
  4344.  
  4345. this.checkboxes.push(checkbox);
  4346. }
  4347.  
  4348. this.clearCheckBox = () => {
  4349. this.middle.classList.add('PopUp_hideBlock');
  4350. while (this.checkboxes.length) {
  4351. this.checkboxes.pop().parentNode.remove();
  4352. }
  4353. }
  4354.  
  4355. this.setMsgText = (text) => {
  4356. this.msgText.innerHTML = text;
  4357. }
  4358.  
  4359. this.getCheckBoxes = () => {
  4360. const checkBoxes = [];
  4361.  
  4362. for (const checkBox of this.checkboxes) {
  4363. checkBoxes.push({
  4364. name: checkBox.dataset.name,
  4365. label: checkBox.label,
  4366. checked: checkBox.checked
  4367. });
  4368. }
  4369.  
  4370. return checkBoxes;
  4371. }
  4372.  
  4373. this.confirm = async (msg, buttOpt, checkBoxes = []) => {
  4374. if (!this.isInit) {
  4375. this.init();
  4376. }
  4377. this.clearButtons();
  4378. this.clearCheckBox();
  4379. return new Promise((complete, failed) => {
  4380. this.setMsgText(msg);
  4381. if (!buttOpt) {
  4382. buttOpt = [{ msg: 'Ok', result: true, isInput: false }];
  4383. }
  4384. for (const checkBox of checkBoxes) {
  4385. this.addCheckBox(checkBox);
  4386. }
  4387. for (let butt of buttOpt) {
  4388. this.addButton(butt, (result) => {
  4389. result = result || butt.result;
  4390. complete(result);
  4391. popup.hide();
  4392. });
  4393. if (butt.isCancel) {
  4394. this.dialogPromice = { func: complete, result: butt.result };
  4395. }
  4396. }
  4397. this.show();
  4398. });
  4399. }
  4400. });
  4401.  
  4402. this.HWHFuncs.popup = popup;
  4403.  
  4404. /**
  4405. * Script control panel
  4406. *
  4407. * Панель управления скриптом
  4408. */
  4409. const scriptMenu = new (function () {
  4410.  
  4411. this.mainMenu,
  4412. this.buttons = [],
  4413. this.checkboxes = [];
  4414. this.option = {
  4415. showMenu: false,
  4416. showDetails: {}
  4417. };
  4418.  
  4419. this.init = function (option = {}) {
  4420. this.option = Object.assign(this.option, option);
  4421. this.option.showDetails = this.loadShowDetails();
  4422. addStyle();
  4423. addBlocks();
  4424. }
  4425.  
  4426. const addStyle = () => {
  4427. style = document.createElement('style');
  4428. style.innerText = `
  4429. .scriptMenu_status {
  4430. position: absolute;
  4431. z-index: 10001;
  4432. /* max-height: 30px; */
  4433. top: -1px;
  4434. left: 30%;
  4435. cursor: pointer;
  4436. border-radius: 0px 0px 10px 10px;
  4437. background: #190e08e6;
  4438. border: 1px #ce9767 solid;
  4439. font-size: 18px;
  4440. font-family: sans-serif;
  4441. font-weight: 600;
  4442. font-stretch: condensed;
  4443. letter-spacing: 1px;
  4444. color: #fce1ac;
  4445. text-shadow: 0px 0px 1px;
  4446. transition: 0.5s;
  4447. padding: 2px 10px 3px;
  4448. }
  4449. .scriptMenu_statusHide {
  4450. top: -35px;
  4451. height: 30px;
  4452. overflow: hidden;
  4453. }
  4454. .scriptMenu_label {
  4455. position: absolute;
  4456. top: 30%;
  4457. left: -4px;
  4458. z-index: 9999;
  4459. cursor: pointer;
  4460. width: 30px;
  4461. height: 30px;
  4462. background: radial-gradient(circle, #47a41b 0%, #1a2f04 100%);
  4463. border: 1px solid #1a2f04;
  4464. border-radius: 5px;
  4465. box-shadow:
  4466. inset 0px 2px 4px #83ce26,
  4467. inset 0px -4px 6px #1a2f04,
  4468. 0px 0px 2px black,
  4469. 0px 0px 0px 2px #ce9767;
  4470. }
  4471. .scriptMenu_label:hover {
  4472. filter: brightness(1.2);
  4473. }
  4474. .scriptMenu_arrowLabel {
  4475. width: 100%;
  4476. height: 100%;
  4477. background-size: 75%;
  4478. background-position: center;
  4479. background-repeat: no-repeat;
  4480. 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");
  4481. box-shadow: 0px 1px 2px #000;
  4482. border-radius: 5px;
  4483. filter: drop-shadow(0px 1px 2px #000D);
  4484. }
  4485. .scriptMenu_main {
  4486. position: absolute;
  4487. max-width: 285px;
  4488. z-index: 9999;
  4489. top: 50%;
  4490. transform: translateY(-40%);
  4491. background: #190e08e6;
  4492. border: 1px #ce9767 solid;
  4493. border-radius: 0px 10px 10px 0px;
  4494. border-left: none;
  4495. padding: 5px 10px 5px 5px;
  4496. box-sizing: border-box;
  4497. font-size: 15px;
  4498. font-family: sans-serif;
  4499. font-weight: 600;
  4500. font-stretch: condensed;
  4501. letter-spacing: 1px;
  4502. color: #fce1ac;
  4503. text-shadow: 0px 0px 1px;
  4504. transition: 1s;
  4505. display: flex;
  4506. flex-direction: column;
  4507. flex-wrap: nowrap;
  4508. }
  4509. .scriptMenu_showMenu {
  4510. display: none;
  4511. }
  4512. .scriptMenu_showMenu:checked~.scriptMenu_main {
  4513. left: 0px;
  4514. }
  4515. .scriptMenu_showMenu:not(:checked)~.scriptMenu_main {
  4516. left: -300px;
  4517. }
  4518. .scriptMenu_divInput {
  4519. margin: 2px;
  4520. }
  4521. .scriptMenu_divInputText {
  4522. margin: 2px;
  4523. align-self: center;
  4524. display: flex;
  4525. }
  4526. .scriptMenu_checkbox {
  4527. position: absolute;
  4528. z-index: -1;
  4529. opacity: 0;
  4530. }
  4531. .scriptMenu_checkbox+label {
  4532. display: inline-flex;
  4533. align-items: center;
  4534. user-select: none;
  4535. }
  4536. .scriptMenu_checkbox+label::before {
  4537. content: '';
  4538. display: inline-block;
  4539. width: 20px;
  4540. height: 20px;
  4541. border: 1px solid #cf9250;
  4542. border-radius: 7px;
  4543. margin-right: 7px;
  4544. }
  4545. .scriptMenu_checkbox:checked+label::before {
  4546. 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");
  4547. }
  4548. .scriptMenu_close {
  4549. width: 40px;
  4550. height: 40px;
  4551. position: absolute;
  4552. right: -18px;
  4553. top: -18px;
  4554. border: 3px solid #c18550;
  4555. border-radius: 20px;
  4556. background: radial-gradient(circle, rgba(190,30,35,1) 0%, rgba(0,0,0,1) 100%);
  4557. background-position-y: 3px;
  4558. box-shadow: -1px 1px 3px black;
  4559. cursor: pointer;
  4560. box-sizing: border-box;
  4561. }
  4562. .scriptMenu_close:hover {
  4563. filter: brightness(1.2);
  4564. }
  4565. .scriptMenu_crossClose {
  4566. width: 100%;
  4567. height: 100%;
  4568. background-size: 65%;
  4569. background-position: center;
  4570. background-repeat: no-repeat;
  4571. 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")
  4572. }
  4573. .scriptMenu_button {
  4574. user-select: none;
  4575. border-radius: 5px;
  4576. cursor: pointer;
  4577. padding: 5px 14px 8px;
  4578. margin: 3px 0;
  4579. background: radial-gradient(circle, rgba(165,120,56,1) 80%, rgba(0,0,0,1) 110%);
  4580. box-shadow: inset 0px -4px 6px #442901, inset 0px 1px 6px #442901, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 2px #ce9767;
  4581. }
  4582. .scriptMenu_button:hover {
  4583. filter: brightness(1.2);
  4584. }
  4585. .scriptMenu_button:active {
  4586. box-shadow: inset 0px 4px 6px #442901, inset 0px 4px 6px #442901, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 2px #ce9767;
  4587. }
  4588. .scriptMenu_buttonText {
  4589. color: #fce5b7;
  4590. text-shadow: 0px 1px 2px black;
  4591. text-align: center;
  4592. }
  4593. .scriptMenu_header {
  4594. text-align: center;
  4595. align-self: center;
  4596. font-size: 15px;
  4597. margin: 0px 15px;
  4598. }
  4599. .scriptMenu_header a {
  4600. color: #fce5b7;
  4601. text-decoration: none;
  4602. }
  4603. .scriptMenu_InputText {
  4604. text-align: center;
  4605. width: 130px;
  4606. height: 24px;
  4607. border: 1px solid #cf9250;
  4608. border-radius: 9px;
  4609. background: transparent;
  4610. color: #fce1ac;
  4611. padding: 0px 10px;
  4612. box-sizing: border-box;
  4613. }
  4614. .scriptMenu_InputText:focus {
  4615. filter: brightness(1.2);
  4616. outline: 0;
  4617. }
  4618. .scriptMenu_InputText::placeholder {
  4619. color: #fce1ac75;
  4620. }
  4621. .scriptMenu_Summary {
  4622. cursor: pointer;
  4623. margin-left: 7px;
  4624. }
  4625. .scriptMenu_Details {
  4626. align-self: center;
  4627. }
  4628. .scriptMenu_buttonGroup {
  4629. display: flex;
  4630. justify-content: center;
  4631.  
  4632. user-select: none;
  4633. cursor: pointer;
  4634. padding: 0;
  4635. margin: 3px 0;
  4636. }
  4637. .scriptMenu_combineButton {
  4638. width: 100%;
  4639. padding: 5px 8px 8px;
  4640. }
  4641. .scriptMenu_combineButtonLeft {
  4642. border-top-left-radius: 5px;
  4643. border-bottom-left-radius: 5px;
  4644. margin-right: 2px;
  4645. }
  4646. .scriptMenu_combineButtonCenter {
  4647. border-radius: 0px;
  4648. margin-right: 2px;
  4649. }
  4650. .scriptMenu_combineButtonRight {
  4651. border-top-right-radius: 5px;
  4652. border-bottom-right-radius: 5px;
  4653. }
  4654. .scriptMenu_combineButton:hover {
  4655. filter: brightness(1.2);
  4656. }
  4657. .scriptMenu_beigeButton {
  4658. border: 1px solid #442901;
  4659. background: radial-gradient(circle, rgba(165,120,56,1) 80%, rgba(0,0,0,1) 110%);
  4660. 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;
  4661. }
  4662. .scriptMenu_beigeButton:active {
  4663. box-shadow: inset 0px 4px 6px #442901, inset 0px 4px 6px #442901, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 1px #ce9767;
  4664. }
  4665. .scriptMenu_greenButton {
  4666. border: 1px solid #1a2f04;
  4667. background: radial-gradient(circle, #47a41b 0%, #1a2f04 150%);
  4668. box-shadow: inset 0px 2px 4px #83ce26, inset 0px -4px 6px #1a2f04, 0px 0px 2px black, 0px 0px 0px 1px #ce9767;
  4669. }
  4670. .scriptMenu_greenButton:active {
  4671. box-shadow: inset 0px 4px 6px #1a2f04, inset 0px 4px 6px #1a2f04, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 1px #ce9767;
  4672. }
  4673. `;
  4674. document.head.appendChild(style);
  4675. }
  4676.  
  4677. const addBlocks = () => {
  4678. const main = document.createElement('div');
  4679. document.body.appendChild(main);
  4680.  
  4681. this.status = document.createElement('div');
  4682. this.status.classList.add('scriptMenu_status');
  4683. this.setStatus('');
  4684. main.appendChild(this.status);
  4685.  
  4686. const label = document.createElement('label');
  4687. label.classList.add('scriptMenu_label');
  4688. label.setAttribute('for', 'checkbox_showMenu');
  4689. main.appendChild(label);
  4690.  
  4691. const arrowLabel = document.createElement('div');
  4692. arrowLabel.classList.add('scriptMenu_arrowLabel');
  4693. label.appendChild(arrowLabel);
  4694.  
  4695. const checkbox = document.createElement('input');
  4696. checkbox.type = 'checkbox';
  4697. checkbox.id = 'checkbox_showMenu';
  4698. checkbox.checked = this.option.showMenu;
  4699. checkbox.classList.add('scriptMenu_showMenu');
  4700. main.appendChild(checkbox);
  4701.  
  4702. this.mainMenu = document.createElement('div');
  4703. this.mainMenu.classList.add('scriptMenu_main');
  4704. main.appendChild(this.mainMenu);
  4705.  
  4706. const closeButton = document.createElement('label');
  4707. closeButton.classList.add('scriptMenu_close');
  4708. closeButton.setAttribute('for', 'checkbox_showMenu');
  4709. this.mainMenu.appendChild(closeButton);
  4710.  
  4711. const crossClose = document.createElement('div');
  4712. crossClose.classList.add('scriptMenu_crossClose');
  4713. closeButton.appendChild(crossClose);
  4714. }
  4715.  
  4716. const getButtonColor = (color) => {
  4717. const buttonColors = {
  4718. green: 'scriptMenu_greenButton',
  4719. beige: 'scriptMenu_beigeButton',
  4720. };
  4721. if (buttonColors[color]) {
  4722. return buttonColors[color];
  4723. }
  4724. return buttonColors['beige'];
  4725. }
  4726.  
  4727. this.setStatus = (text, onclick) => {
  4728. if (!text) {
  4729. this.status.classList.add('scriptMenu_statusHide');
  4730. this.status.innerHTML = '';
  4731. } else {
  4732. this.status.classList.remove('scriptMenu_statusHide');
  4733. this.status.innerHTML = text;
  4734. }
  4735.  
  4736. if (typeof onclick == 'function') {
  4737. this.status.addEventListener("click", onclick, {
  4738. once: true
  4739. });
  4740. }
  4741. }
  4742.  
  4743. this.addStatus = (text) => {
  4744. if (!this.status.innerHTML) {
  4745. this.status.classList.remove('scriptMenu_statusHide');
  4746. }
  4747. this.status.innerHTML += text;
  4748. }
  4749.  
  4750. /**
  4751. * Adding a text element
  4752. *
  4753. * Добавление текстового элемента
  4754. * @param {String} text text // текст
  4755. * @param {Function} func Click function // функция по клику
  4756. * @param {HTMLDivElement} main parent // родитель
  4757. */
  4758. this.addHeader = (text, func, main) => {
  4759. main = main || this.mainMenu;
  4760. const header = document.createElement('div');
  4761. header.classList.add('scriptMenu_header');
  4762. header.innerHTML = text;
  4763. if (typeof func == 'function') {
  4764. header.addEventListener('click', func);
  4765. }
  4766. main.appendChild(header);
  4767. return header;
  4768. }
  4769.  
  4770. /**
  4771. * Adding a button
  4772. *
  4773. * Добавление кнопки
  4774. * @param {String} text
  4775. * @param {Function} func
  4776. * @param {String} title
  4777. * @param {HTMLDivElement} main parent // родитель
  4778. */
  4779. this.addButton = (text, func, title, main) => {
  4780. main = main || this.mainMenu;
  4781. const button = document.createElement('div');
  4782. button.classList.add('scriptMenu_button');
  4783. button.classList.add('scriptMenu_beigeButton');
  4784. button.title = title;
  4785. button.addEventListener('click', func);
  4786. main.appendChild(button);
  4787.  
  4788. const buttonText = document.createElement('div');
  4789. buttonText.classList.add('scriptMenu_buttonText');
  4790. buttonText.innerText = text;
  4791. button.appendChild(buttonText);
  4792. this.buttons.push(button);
  4793.  
  4794. return button;
  4795. }
  4796.  
  4797. /**
  4798. * Adding a button
  4799. *
  4800. * Добавление кнопки
  4801. * @param {Array} buttonList
  4802. */
  4803. this.addCombinedButton = (buttonList, main) => {
  4804. main = main || this.mainMenu;
  4805. const buttonGroup = document.createElement('div');
  4806. buttonGroup.classList.add('scriptMenu_buttonGroup');
  4807. let count = 0;
  4808.  
  4809. for(const btn of buttonList) {
  4810. const { text, func, title, color } = btn;
  4811. const button = document.createElement('div');
  4812. button.classList.add('scriptMenu_combineButton');
  4813. if (count === 0) {
  4814. button.classList.add('scriptMenu_combineButtonLeft');
  4815. } else if (count === buttonList.length - 1) {
  4816. button.classList.add('scriptMenu_combineButtonRight');
  4817. } else {
  4818. button.classList.add('scriptMenu_combineButtonCenter');
  4819. }
  4820. button.classList.add(getButtonColor(color));
  4821. button.title = title;
  4822. button.addEventListener('click', func);
  4823. buttonGroup.appendChild(button);
  4824.  
  4825. const buttonText = document.createElement('div');
  4826. buttonText.classList.add('scriptMenu_buttonText');
  4827. buttonText.innerText = text;
  4828. button.appendChild(buttonText);
  4829. this.buttons.push(button);
  4830. count++;
  4831. }
  4832.  
  4833. main.appendChild(buttonGroup);
  4834.  
  4835. return buttonGroup;
  4836. };
  4837.  
  4838. /**
  4839. * Adding checkbox
  4840. *
  4841. * Добавление чекбокса
  4842. * @param {String} label
  4843. * @param {String} title
  4844. * @param {HTMLDivElement} main parent // родитель
  4845. * @returns
  4846. */
  4847. this.addCheckbox = (label, title, main) => {
  4848. main = main || this.mainMenu;
  4849. const divCheckbox = document.createElement('div');
  4850. divCheckbox.classList.add('scriptMenu_divInput');
  4851. divCheckbox.title = title;
  4852. main.appendChild(divCheckbox);
  4853.  
  4854. const checkbox = document.createElement('input');
  4855. checkbox.type = 'checkbox';
  4856. checkbox.id = 'scriptMenuCheckbox' + this.checkboxes.length;
  4857. checkbox.classList.add('scriptMenu_checkbox');
  4858. divCheckbox.appendChild(checkbox)
  4859.  
  4860. const checkboxLabel = document.createElement('label');
  4861. checkboxLabel.innerText = label;
  4862. checkboxLabel.setAttribute('for', checkbox.id);
  4863. divCheckbox.appendChild(checkboxLabel);
  4864.  
  4865. this.checkboxes.push(checkbox);
  4866. return checkbox;
  4867. }
  4868.  
  4869. /**
  4870. * Adding input field
  4871. *
  4872. * Добавление поля ввода
  4873. * @param {String} title
  4874. * @param {String} placeholder
  4875. * @param {HTMLDivElement} main parent // родитель
  4876. * @returns
  4877. */
  4878. this.addInputText = (title, placeholder, main) => {
  4879. main = main || this.mainMenu;
  4880. const divInputText = document.createElement('div');
  4881. divInputText.classList.add('scriptMenu_divInputText');
  4882. divInputText.title = title;
  4883. main.appendChild(divInputText);
  4884.  
  4885. const newInputText = document.createElement('input');
  4886. newInputText.type = 'text';
  4887. if (placeholder) {
  4888. newInputText.placeholder = placeholder;
  4889. }
  4890. newInputText.classList.add('scriptMenu_InputText');
  4891. divInputText.appendChild(newInputText)
  4892. return newInputText;
  4893. }
  4894.  
  4895. /**
  4896. * Adds a dropdown block
  4897. *
  4898. * Добавляет раскрывающийся блок
  4899. * @param {String} summary
  4900. * @param {String} name
  4901. * @returns
  4902. */
  4903. this.addDetails = (summaryText, name = null) => {
  4904. const details = document.createElement('details');
  4905. details.classList.add('scriptMenu_Details');
  4906. this.mainMenu.appendChild(details);
  4907.  
  4908. const summary = document.createElement('summary');
  4909. summary.classList.add('scriptMenu_Summary');
  4910. summary.innerText = summaryText;
  4911. if (name) {
  4912. const self = this;
  4913. details.open = this.option.showDetails[name];
  4914. details.dataset.name = name;
  4915. summary.addEventListener('click', () => {
  4916. self.option.showDetails[details.dataset.name] = !details.open;
  4917. self.saveShowDetails(self.option.showDetails);
  4918. });
  4919. }
  4920. details.appendChild(summary);
  4921.  
  4922. return details;
  4923. }
  4924.  
  4925. /**
  4926. * Saving the expanded state of the details blocks
  4927. *
  4928. * Сохранение состояния развенутости блоков details
  4929. * @param {*} value
  4930. */
  4931. this.saveShowDetails = (value) => {
  4932. try {
  4933. localStorage.setItem('scriptMenu_showDetails', JSON.stringify(value));
  4934. } catch (e) {
  4935. console.log("¯\\_(ツ)_/¯")
  4936. }
  4937. }
  4938.  
  4939. /**
  4940. * Loading the state of expanded blocks details
  4941. *
  4942. * Загрузка состояния развенутости блоков details
  4943. * @returns
  4944. */
  4945. this.loadShowDetails = () => {
  4946. let showDetails = null;
  4947. try {
  4948. showDetails = localStorage.getItem('scriptMenu_showDetails');
  4949. } catch (e) {
  4950. console.log('¯\\_(ツ)_/¯');
  4951. }
  4952.  
  4953. if (!showDetails) {
  4954. return {};
  4955. }
  4956.  
  4957. try {
  4958. showDetails = JSON.parse(showDetails);
  4959. } catch (e) {
  4960. return {};
  4961. }
  4962.  
  4963. return showDetails;
  4964. }
  4965. });
  4966.  
  4967. /**
  4968. * Пример использования
  4969. scriptMenu.init();
  4970. scriptMenu.addHeader('v1.508');
  4971. scriptMenu.addCheckbox('testHack', 'Тестовый взлом игры!');
  4972. scriptMenu.addButton('Запуск!', () => console.log('click'), 'подсказака');
  4973. scriptMenu.addInputText('input подсказака');
  4974. */
  4975. /**
  4976. * Game Library
  4977. *
  4978. * Игровая библиотека
  4979. */
  4980. class Library {
  4981. defaultLibUrl = 'https://heroesru-a.akamaihd.net/vk/v1101/lib/lib.json';
  4982.  
  4983. constructor() {
  4984. if (!Library.instance) {
  4985. Library.instance = this;
  4986. }
  4987.  
  4988. return Library.instance;
  4989. }
  4990.  
  4991. async load() {
  4992. try {
  4993. await this.getUrlLib();
  4994. console.log(this.defaultLibUrl);
  4995. this.data = await fetch(this.defaultLibUrl).then(e => e.json())
  4996. } catch (error) {
  4997. console.error('Не удалось загрузить библиотеку', error)
  4998. }
  4999. }
  5000.  
  5001. async getUrlLib() {
  5002. try {
  5003. const db = new Database('hw_cache', 'cache');
  5004. await db.open();
  5005. const cacheLibFullUrl = await db.get('lib/lib.json.gz', false);
  5006. this.defaultLibUrl = cacheLibFullUrl.fullUrl.split('.gz').shift();
  5007. } catch(e) {}
  5008. }
  5009.  
  5010. getData(id) {
  5011. return this.data[id];
  5012. }
  5013.  
  5014. setData(data) {
  5015. this.data = data;
  5016. }
  5017. }
  5018.  
  5019. this.lib = new Library();
  5020. /**
  5021. * Database
  5022. *
  5023. * База данных
  5024. */
  5025. class Database {
  5026. constructor(dbName, storeName) {
  5027. this.dbName = dbName;
  5028. this.storeName = storeName;
  5029. this.db = null;
  5030. }
  5031.  
  5032. async open() {
  5033. return new Promise((resolve, reject) => {
  5034. const request = indexedDB.open(this.dbName);
  5035.  
  5036. request.onerror = () => {
  5037. reject(new Error(`Failed to open database ${this.dbName}`));
  5038. };
  5039.  
  5040. request.onsuccess = () => {
  5041. this.db = request.result;
  5042. resolve();
  5043. };
  5044.  
  5045. request.onupgradeneeded = (event) => {
  5046. const db = event.target.result;
  5047. if (!db.objectStoreNames.contains(this.storeName)) {
  5048. db.createObjectStore(this.storeName);
  5049. }
  5050. };
  5051. });
  5052. }
  5053.  
  5054. async set(key, value) {
  5055. return new Promise((resolve, reject) => {
  5056. const transaction = this.db.transaction([this.storeName], 'readwrite');
  5057. const store = transaction.objectStore(this.storeName);
  5058. const request = store.put(value, key);
  5059.  
  5060. request.onerror = () => {
  5061. reject(new Error(`Failed to save value with key ${key}`));
  5062. };
  5063.  
  5064. request.onsuccess = () => {
  5065. resolve();
  5066. };
  5067. });
  5068. }
  5069.  
  5070. async get(key, def) {
  5071. return new Promise((resolve, reject) => {
  5072. const transaction = this.db.transaction([this.storeName], 'readonly');
  5073. const store = transaction.objectStore(this.storeName);
  5074. const request = store.get(key);
  5075.  
  5076. request.onerror = () => {
  5077. resolve(def);
  5078. };
  5079.  
  5080. request.onsuccess = () => {
  5081. resolve(request.result);
  5082. };
  5083. });
  5084. }
  5085.  
  5086. async delete(key) {
  5087. return new Promise((resolve, reject) => {
  5088. const transaction = this.db.transaction([this.storeName], 'readwrite');
  5089. const store = transaction.objectStore(this.storeName);
  5090. const request = store.delete(key);
  5091.  
  5092. request.onerror = () => {
  5093. reject(new Error(`Failed to delete value with key ${key}`));
  5094. };
  5095.  
  5096. request.onsuccess = () => {
  5097. resolve();
  5098. };
  5099. });
  5100. }
  5101. }
  5102.  
  5103. /**
  5104. * Returns the stored value
  5105. *
  5106. * Возвращает сохраненное значение
  5107. */
  5108. function getSaveVal(saveName, def) {
  5109. const result = storage.get(saveName, def);
  5110. return result;
  5111. }
  5112. this.HWHFuncs.getSaveVal = getSaveVal;
  5113.  
  5114. /**
  5115. * Stores value
  5116. *
  5117. * Сохраняет значение
  5118. */
  5119. function setSaveVal(saveName, value) {
  5120. storage.set(saveName, value);
  5121. }
  5122. this.HWHFuncs.setSaveVal = setSaveVal;
  5123.  
  5124. /**
  5125. * Database initialization
  5126. *
  5127. * Инициализация базы данных
  5128. */
  5129. const db = new Database(GM_info.script.name, 'settings');
  5130.  
  5131. /**
  5132. * Data store
  5133. *
  5134. * Хранилище данных
  5135. */
  5136. const storage = {
  5137. userId: 0,
  5138. /**
  5139. * Default values
  5140. *
  5141. * Значения по умолчанию
  5142. */
  5143. values: [
  5144. ...Object.entries(checkboxes).map(e => ({ [e[0]]: e[1].default })),
  5145. ...Object.entries(inputs).map(e => ({ [e[0]]: e[1].default })),
  5146. ].reduce((acc, obj) => ({ ...acc, ...obj }), {}),
  5147. name: GM_info.script.name,
  5148. get: function (key, def) {
  5149. if (key in this.values) {
  5150. return this.values[key];
  5151. }
  5152. return def;
  5153. },
  5154. set: function (key, value) {
  5155. this.values[key] = value;
  5156. db.set(this.userId, this.values).catch(
  5157. e => null
  5158. );
  5159. localStorage[this.name + ':' + key] = value;
  5160. },
  5161. delete: function (key) {
  5162. delete this.values[key];
  5163. db.set(this.userId, this.values);
  5164. delete localStorage[this.name + ':' + key];
  5165. }
  5166. }
  5167.  
  5168. /**
  5169. * Returns all keys from localStorage that start with prefix (for migration)
  5170. *
  5171. * Возвращает все ключи из localStorage которые начинаются с prefix (для миграции)
  5172. */
  5173. function getAllValuesStartingWith(prefix) {
  5174. const values = [];
  5175. for (let i = 0; i < localStorage.length; i++) {
  5176. const key = localStorage.key(i);
  5177. if (key.startsWith(prefix)) {
  5178. const val = localStorage.getItem(key);
  5179. const keyValue = key.split(':')[1];
  5180. values.push({ key: keyValue, val });
  5181. }
  5182. }
  5183. return values;
  5184. }
  5185.  
  5186. /**
  5187. * Opens or migrates to a database
  5188. *
  5189. * Открывает или мигрирует в базу данных
  5190. */
  5191. async function openOrMigrateDatabase(userId) {
  5192. storage.userId = userId;
  5193. try {
  5194. await db.open();
  5195. } catch(e) {
  5196. return;
  5197. }
  5198. let settings = await db.get(userId, false);
  5199.  
  5200. if (settings) {
  5201. storage.values = settings;
  5202. return;
  5203. }
  5204.  
  5205. const values = getAllValuesStartingWith(GM_info.script.name);
  5206. for (const value of values) {
  5207. let val = null;
  5208. try {
  5209. val = JSON.parse(value.val);
  5210. } catch {
  5211. break;
  5212. }
  5213. storage.values[value.key] = val;
  5214. }
  5215. await db.set(userId, storage.values);
  5216. }
  5217.  
  5218. class ZingerYWebsiteAPI {
  5219. /**
  5220. * Class for interaction with the API of the zingery.ru website
  5221. * Intended only for use with the HeroWarsHelper script:
  5222. * https://greasyfork.org/ru/scripts/450693-herowarshelper
  5223. * Copyright ZingerY
  5224. */
  5225. url = 'https://zingery.ru/heroes/';
  5226. // YWJzb2x1dGVseSB1c2VsZXNzIGxpbmU=
  5227. constructor(urn, env, data = {}) {
  5228. this.urn = urn;
  5229. this.fd = {
  5230. now: Date.now(),
  5231. fp: this.constructor.toString().replaceAll(/\s/g, ''),
  5232. env: env.callee.toString().replaceAll(/\s/g, ''),
  5233. info: (({ name, version, author }) => [name, version, author])(GM_info.script),
  5234. ...data,
  5235. };
  5236. }
  5237.  
  5238. sign() {
  5239. return md5([...this.fd.info, ~(this.fd.now % 1e3), this.fd.fp].join('_'));
  5240. }
  5241.  
  5242. encode(data) {
  5243. return btoa(encodeURIComponent(JSON.stringify(data)));
  5244. }
  5245.  
  5246. decode(data) {
  5247. return JSON.parse(decodeURIComponent(atob(data)));
  5248. }
  5249.  
  5250. headers() {
  5251. return {
  5252. 'X-Request-Signature': this.sign(),
  5253. 'X-Script-Name': GM_info.script.name,
  5254. 'X-Script-Version': GM_info.script.version,
  5255. 'X-Script-Author': GM_info.script.author,
  5256. 'X-Script-ZingerY': 42,
  5257. };
  5258. }
  5259.  
  5260. async request() {
  5261. try {
  5262. const response = await fetch(this.url + this.urn, {
  5263. method: 'POST',
  5264. headers: this.headers(),
  5265. body: this.encode(this.fd),
  5266. });
  5267. const text = await response.text();
  5268. return this.decode(text);
  5269. } catch (e) {
  5270. console.error(e);
  5271. return [];
  5272. }
  5273. }
  5274. /**
  5275. * Класс для взаимодействия с API сайта zingery.ru
  5276. * Предназначен только для использования со скриптом HeroWarsHelper:
  5277. * https://greasyfork.org/ru/scripts/450693-herowarshelper
  5278. * Copyright ZingerY
  5279. */
  5280. }
  5281.  
  5282. /**
  5283. * Sending expeditions
  5284. *
  5285. * Отправка экспедиций
  5286. */
  5287. function checkExpedition() {
  5288. const { Expedition } = HWHClasses;
  5289. return new Promise((resolve, reject) => {
  5290. const expedition = new Expedition(resolve, reject);
  5291. expedition.start();
  5292. });
  5293. }
  5294.  
  5295. class Expedition {
  5296. checkExpedInfo = {
  5297. calls: [
  5298. {
  5299. name: 'expeditionGet',
  5300. args: {},
  5301. ident: 'expeditionGet',
  5302. },
  5303. {
  5304. name: 'heroGetAll',
  5305. args: {},
  5306. ident: 'heroGetAll',
  5307. },
  5308. ],
  5309. };
  5310.  
  5311. constructor(resolve, reject) {
  5312. this.resolve = resolve;
  5313. this.reject = reject;
  5314. }
  5315.  
  5316. async start() {
  5317. const data = await Send(JSON.stringify(this.checkExpedInfo));
  5318.  
  5319. const expedInfo = data.results[0].result.response;
  5320. const dataHeroes = data.results[1].result.response;
  5321. const dataExped = { useHeroes: [], exped: [] };
  5322. const calls = [];
  5323.  
  5324. /**
  5325. * Adding expeditions to collect
  5326. * Добавляем экспедиции для сбора
  5327. */
  5328. let countGet = 0;
  5329. for (var n in expedInfo) {
  5330. const exped = expedInfo[n];
  5331. const dateNow = Date.now() / 1000;
  5332. if (exped.status == 2 && exped.endTime != 0 && dateNow > exped.endTime) {
  5333. countGet++;
  5334. calls.push({
  5335. name: 'expeditionFarm',
  5336. args: { expeditionId: exped.id },
  5337. ident: 'expeditionFarm_' + exped.id,
  5338. });
  5339. } else {
  5340. dataExped.useHeroes = dataExped.useHeroes.concat(exped.heroes);
  5341. }
  5342. if (exped.status == 1) {
  5343. dataExped.exped.push({ id: exped.id, power: exped.power });
  5344. }
  5345. }
  5346. dataExped.exped = dataExped.exped.sort((a, b) => b.power - a.power);
  5347.  
  5348. /**
  5349. * Putting together a list of heroes
  5350. * Собираем список героев
  5351. */
  5352. const heroesArr = [];
  5353. for (let n in dataHeroes) {
  5354. const hero = dataHeroes[n];
  5355. if (hero.power > 0 && !dataExped.useHeroes.includes(hero.id)) {
  5356. let heroPower = hero.power;
  5357. // Лара Крофт * 3
  5358. if (hero.id == 63 && hero.color >= 16) {
  5359. heroPower *= 3;
  5360. }
  5361. heroesArr.push({ id: hero.id, power: heroPower });
  5362. }
  5363. }
  5364.  
  5365. /**
  5366. * Adding expeditions to send
  5367. * Добавляем экспедиции для отправки
  5368. */
  5369. let countSend = 0;
  5370. heroesArr.sort((a, b) => a.power - b.power);
  5371. for (const exped of dataExped.exped) {
  5372. let heroesIds = this.selectionHeroes(heroesArr, exped.power);
  5373. if (heroesIds && heroesIds.length > 4) {
  5374. for (let q in heroesArr) {
  5375. if (heroesIds.includes(heroesArr[q].id)) {
  5376. delete heroesArr[q];
  5377. }
  5378. }
  5379. countSend++;
  5380. calls.push({
  5381. name: 'expeditionSendHeroes',
  5382. args: {
  5383. expeditionId: exped.id,
  5384. heroes: heroesIds,
  5385. },
  5386. ident: 'expeditionSendHeroes_' + exped.id,
  5387. });
  5388. }
  5389. }
  5390.  
  5391. if (calls.length) {
  5392. await Send({ calls });
  5393. this.end(I18N('EXPEDITIONS_SENT', {countGet, countSend}));
  5394. return;
  5395. }
  5396.  
  5397. this.end(I18N('EXPEDITIONS_NOTHING'));
  5398. }
  5399.  
  5400. /**
  5401. * Selection of heroes for expeditions
  5402. *
  5403. * Подбор героев для экспедиций
  5404. */
  5405. selectionHeroes(heroes, power) {
  5406. const resultHeroers = [];
  5407. const heroesIds = [];
  5408. for (let q = 0; q < 5; q++) {
  5409. for (let i in heroes) {
  5410. let hero = heroes[i];
  5411. if (heroesIds.includes(hero.id)) {
  5412. continue;
  5413. }
  5414.  
  5415. const summ = resultHeroers.reduce((acc, hero) => acc + hero.power, 0);
  5416. const need = Math.round((power - summ) / (5 - resultHeroers.length));
  5417. if (hero.power > need) {
  5418. resultHeroers.push(hero);
  5419. heroesIds.push(hero.id);
  5420. break;
  5421. }
  5422. }
  5423. }
  5424.  
  5425. const summ = resultHeroers.reduce((acc, hero) => acc + hero.power, 0);
  5426. if (summ < power) {
  5427. return false;
  5428. }
  5429. return heroesIds;
  5430. }
  5431.  
  5432. /**
  5433. * Ends expedition script
  5434. *
  5435. * Завершает скрипт экспедиции
  5436. */
  5437. end(msg) {
  5438. setProgress(msg, true);
  5439. this.resolve();
  5440. }
  5441. }
  5442.  
  5443. this.HWHClasses.Expedition = Expedition;
  5444.  
  5445. /**
  5446. * Walkthrough of the dungeon
  5447. *
  5448. * Прохождение подземелья
  5449. */
  5450. function testDungeon() {
  5451. const { executeDungeon } = HWHClasses;
  5452. return new Promise((resolve, reject) => {
  5453. const dung = new executeDungeon(resolve, reject);
  5454. const titanit = getInput('countTitanit');
  5455. dung.start(titanit);
  5456. });
  5457. }
  5458.  
  5459. /**
  5460. * Walkthrough of the dungeon
  5461. *
  5462. * Прохождение подземелья
  5463. */
  5464. function executeDungeon(resolve, reject) {
  5465. dungeonActivity = 0;
  5466. maxDungeonActivity = 150;
  5467.  
  5468. titanGetAll = [];
  5469.  
  5470. teams = {
  5471. heroes: [],
  5472. earth: [],
  5473. fire: [],
  5474. neutral: [],
  5475. water: [],
  5476. }
  5477.  
  5478. titanStats = [];
  5479.  
  5480. titansStates = {};
  5481.  
  5482. let talentMsg = '';
  5483. let talentMsgReward = '';
  5484.  
  5485. callsExecuteDungeon = {
  5486. calls: [{
  5487. name: "dungeonGetInfo",
  5488. args: {},
  5489. ident: "dungeonGetInfo"
  5490. }, {
  5491. name: "teamGetAll",
  5492. args: {},
  5493. ident: "teamGetAll"
  5494. }, {
  5495. name: "teamGetFavor",
  5496. args: {},
  5497. ident: "teamGetFavor"
  5498. }, {
  5499. name: "clanGetInfo",
  5500. args: {},
  5501. ident: "clanGetInfo"
  5502. }, {
  5503. name: "titanGetAll",
  5504. args: {},
  5505. ident: "titanGetAll"
  5506. }, {
  5507. name: "inventoryGet",
  5508. args: {},
  5509. ident: "inventoryGet"
  5510. }]
  5511. }
  5512.  
  5513. this.start = function(titanit) {
  5514. maxDungeonActivity = titanit || getInput('countTitanit');
  5515. send(JSON.stringify(callsExecuteDungeon), startDungeon);
  5516. }
  5517.  
  5518. /**
  5519. * Getting data on the dungeon
  5520. *
  5521. * Получаем данные по подземелью
  5522. */
  5523. function startDungeon(e) {
  5524. res = e.results;
  5525. dungeonGetInfo = res[0].result.response;
  5526. if (!dungeonGetInfo) {
  5527. endDungeon('noDungeon', res);
  5528. return;
  5529. }
  5530. teamGetAll = res[1].result.response;
  5531. teamGetFavor = res[2].result.response;
  5532. dungeonActivity = res[3].result.response.stat.todayDungeonActivity;
  5533. titanGetAll = Object.values(res[4].result.response);
  5534. countPredictionCard = res[5].result.response.consumable[81];
  5535.  
  5536. teams.hero = {
  5537. favor: teamGetFavor.dungeon_hero,
  5538. heroes: teamGetAll.dungeon_hero.filter(id => id < 6000),
  5539. teamNum: 0,
  5540. }
  5541. heroPet = teamGetAll.dungeon_hero.filter(id => id >= 6000).pop();
  5542. if (heroPet) {
  5543. teams.hero.pet = heroPet;
  5544. }
  5545.  
  5546. teams.neutral = {
  5547. favor: {},
  5548. heroes: getTitanTeam(titanGetAll, 'neutral'),
  5549. teamNum: 0,
  5550. };
  5551. teams.water = {
  5552. favor: {},
  5553. heroes: getTitanTeam(titanGetAll, 'water'),
  5554. teamNum: 0,
  5555. };
  5556. teams.fire = {
  5557. favor: {},
  5558. heroes: getTitanTeam(titanGetAll, 'fire'),
  5559. teamNum: 0,
  5560. };
  5561. teams.earth = {
  5562. favor: {},
  5563. heroes: getTitanTeam(titanGetAll, 'earth'),
  5564. teamNum: 0,
  5565. };
  5566.  
  5567.  
  5568. checkFloor(dungeonGetInfo);
  5569. }
  5570.  
  5571. function getTitanTeam(titans, type) {
  5572. switch (type) {
  5573. case 'neutral':
  5574. return titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5575. case 'water':
  5576. return titans.filter(e => e.id.toString().slice(2, 3) == '0').map(e => e.id);
  5577. case 'fire':
  5578. return titans.filter(e => e.id.toString().slice(2, 3) == '1').map(e => e.id);
  5579. case 'earth':
  5580. return titans.filter(e => e.id.toString().slice(2, 3) == '2').map(e => e.id);
  5581. }
  5582. }
  5583.  
  5584. function getNeutralTeam() {
  5585. const titans = titanGetAll.filter(e => !titansStates[e.id]?.isDead)
  5586. return titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5587. }
  5588.  
  5589. function fixTitanTeam(titans) {
  5590. titans.heroes = titans.heroes.filter(e => !titansStates[e]?.isDead);
  5591. return titans;
  5592. }
  5593.  
  5594. /**
  5595. * Checking the floor
  5596. *
  5597. * Проверяем этаж
  5598. */
  5599. async function checkFloor(dungeonInfo) {
  5600. if (!('floor' in dungeonInfo) || dungeonInfo.floor?.state == 2) {
  5601. saveProgress();
  5602. return;
  5603. }
  5604. checkTalent(dungeonInfo);
  5605. // console.log(dungeonInfo, dungeonActivity);
  5606. setProgress(`${I18N('DUNGEON')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity} ${talentMsg}`);
  5607. if (dungeonActivity >= maxDungeonActivity) {
  5608. endDungeon('endDungeon', 'maxActive ' + dungeonActivity + '/' + maxDungeonActivity);
  5609. return;
  5610. }
  5611. titansStates = dungeonInfo.states.titans;
  5612. titanStats = titanObjToArray(titansStates);
  5613. const floorChoices = dungeonInfo.floor.userData;
  5614. const floorType = dungeonInfo.floorType;
  5615. //const primeElement = dungeonInfo.elements.prime;
  5616. if (floorType == "battle") {
  5617. const calls = [];
  5618. for (let teamNum in floorChoices) {
  5619. attackerType = floorChoices[teamNum].attackerType;
  5620. const args = fixTitanTeam(teams[attackerType]);
  5621. if (attackerType == 'neutral') {
  5622. args.heroes = getNeutralTeam();
  5623. }
  5624. if (!args.heroes.length) {
  5625. continue;
  5626. }
  5627. args.teamNum = teamNum;
  5628. calls.push({
  5629. name: "dungeonStartBattle",
  5630. args,
  5631. ident: "body_" + teamNum
  5632. })
  5633. }
  5634. if (!calls.length) {
  5635. endDungeon('endDungeon', 'All Dead');
  5636. return;
  5637. }
  5638. const battleDatas = await Send(JSON.stringify({ calls }))
  5639. .then(e => e.results.map(n => n.result.response))
  5640. const battleResults = [];
  5641. for (n in battleDatas) {
  5642. battleData = battleDatas[n]
  5643. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  5644. battleResults.push(await Calc(battleData).then(result => {
  5645. result.teamNum = n;
  5646. result.attackerType = floorChoices[n].attackerType;
  5647. return result;
  5648. }));
  5649. }
  5650. processingPromises(battleResults)
  5651. }
  5652. }
  5653.  
  5654. async function checkTalent(dungeonInfo) {
  5655. const talent = dungeonInfo.talent;
  5656. if (!talent) {
  5657. return;
  5658. }
  5659. const dungeonFloor = +dungeonInfo.floorNumber;
  5660. const talentFloor = +talent.floorRandValue;
  5661. let doorsAmount = 3 - talent.conditions.doorsAmount;
  5662.  
  5663. if (dungeonFloor === talentFloor && (!doorsAmount || !talent.conditions?.farmedDoors[dungeonFloor])) {
  5664. const reward = await Send({
  5665. calls: [
  5666. { name: 'heroTalent_getReward', args: { talentType: 'tmntDungeonTalent', reroll: false }, ident: 'group_0_body' },
  5667. { name: 'heroTalent_farmReward', args: { talentType: 'tmntDungeonTalent' }, ident: 'group_1_body' },
  5668. ],
  5669. }).then((e) => e.results[0].result.response);
  5670. const type = Object.keys(reward).pop();
  5671. const itemId = Object.keys(reward[type]).pop();
  5672. const count = reward[type][itemId];
  5673. const itemName = cheats.translate(`LIB_${type.toUpperCase()}_NAME_${itemId}`);
  5674. talentMsgReward += `<br> ${count} ${itemName}`;
  5675. doorsAmount++;
  5676. }
  5677. talentMsg = `<br>TMNT Talent: ${doorsAmount}/3 ${talentMsgReward}<br>`;
  5678. }
  5679.  
  5680. function processingPromises(results) {
  5681. let selectBattle = results[0];
  5682. if (results.length < 2) {
  5683. // console.log(selectBattle);
  5684. if (!selectBattle.result.win) {
  5685. endDungeon('dungeonEndBattle\n', selectBattle);
  5686. return;
  5687. }
  5688. endBattle(selectBattle);
  5689. return;
  5690. }
  5691.  
  5692. selectBattle = false;
  5693. let bestState = -1000;
  5694. for (const result of results) {
  5695. const recovery = getState(result);
  5696. if (recovery > bestState) {
  5697. bestState = recovery;
  5698. selectBattle = result
  5699. }
  5700. }
  5701. // console.log(selectBattle.teamNum, results);
  5702. if (!selectBattle || bestState <= -1000) {
  5703. endDungeon('dungeonEndBattle\n', results);
  5704. return;
  5705. }
  5706.  
  5707. startBattle(selectBattle.teamNum, selectBattle.attackerType)
  5708. .then(endBattle);
  5709. }
  5710.  
  5711. /**
  5712. * Let's start the fight
  5713. *
  5714. * Начинаем бой
  5715. */
  5716. function startBattle(teamNum, attackerType) {
  5717. return new Promise(function (resolve, reject) {
  5718. args = fixTitanTeam(teams[attackerType]);
  5719. args.teamNum = teamNum;
  5720. if (attackerType == 'neutral') {
  5721. const titans = titanGetAll.filter(e => !titansStates[e.id]?.isDead)
  5722. args.heroes = titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5723. }
  5724. startBattleCall = {
  5725. calls: [{
  5726. name: "dungeonStartBattle",
  5727. args,
  5728. ident: "body"
  5729. }]
  5730. }
  5731. send(JSON.stringify(startBattleCall), resultBattle, {
  5732. resolve,
  5733. teamNum,
  5734. attackerType
  5735. });
  5736. });
  5737. }
  5738. /**
  5739. * Returns the result of the battle in a promise
  5740. *
  5741. * Возращает резульат боя в промис
  5742. */
  5743. function resultBattle(resultBattles, args) {
  5744. battleData = resultBattles.results[0].result.response;
  5745. battleType = "get_tower";
  5746. if (battleData.type == "dungeon_titan") {
  5747. battleType = "get_titan";
  5748. }
  5749. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  5750. BattleCalc(battleData, battleType, function (result) {
  5751. result.teamNum = args.teamNum;
  5752. result.attackerType = args.attackerType;
  5753. args.resolve(result);
  5754. });
  5755. }
  5756. /**
  5757. * Finishing the fight
  5758. *
  5759. * Заканчиваем бой
  5760. */
  5761. async function endBattle(battleInfo) {
  5762. if (battleInfo.result.win) {
  5763. const args = {
  5764. result: battleInfo.result,
  5765. progress: battleInfo.progress,
  5766. }
  5767. if (countPredictionCard > 0) {
  5768. args.isRaid = true;
  5769. } else {
  5770. const timer = getTimer(battleInfo.battleTime);
  5771. console.log(timer);
  5772. await countdownTimer(timer, `${I18N('DUNGEON')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity} ${talentMsg}`);
  5773. }
  5774. const calls = [{
  5775. name: "dungeonEndBattle",
  5776. args,
  5777. ident: "body"
  5778. }];
  5779. lastDungeonBattleData = null;
  5780. send(JSON.stringify({ calls }), resultEndBattle);
  5781. } else {
  5782. endDungeon('dungeonEndBattle win: false\n', battleInfo);
  5783. }
  5784. }
  5785.  
  5786. /**
  5787. * Getting and processing battle results
  5788. *
  5789. * Получаем и обрабатываем результаты боя
  5790. */
  5791. function resultEndBattle(e) {
  5792. if ('error' in e) {
  5793. popup.confirm(I18N('ERROR_MSG', {
  5794. name: e.error.name,
  5795. description: e.error.description,
  5796. }));
  5797. endDungeon('errorRequest', e);
  5798. return;
  5799. }
  5800. battleResult = e.results[0].result.response;
  5801. if ('error' in battleResult) {
  5802. endDungeon('errorBattleResult', battleResult);
  5803. return;
  5804. }
  5805. dungeonGetInfo = battleResult.dungeon ?? battleResult;
  5806. dungeonActivity += battleResult.reward.dungeonActivity ?? 0;
  5807. checkFloor(dungeonGetInfo);
  5808. }
  5809.  
  5810. /**
  5811. * Returns the coefficient of condition of the
  5812. * difference in titanium before and after the battle
  5813. *
  5814. * Возвращает коэффициент состояния титанов после боя
  5815. */
  5816. function getState(result) {
  5817. if (!result.result.win) {
  5818. return -1000;
  5819. }
  5820.  
  5821. let beforeSumFactor = 0;
  5822. const beforeTitans = result.battleData.attackers;
  5823. for (let titanId in beforeTitans) {
  5824. const titan = beforeTitans[titanId];
  5825. const state = titan.state;
  5826. let factor = 1;
  5827. if (state) {
  5828. const hp = state.hp / titan.hp;
  5829. const energy = state.energy / 1e3;
  5830. factor = hp + energy / 20
  5831. }
  5832. beforeSumFactor += factor;
  5833. }
  5834.  
  5835. let afterSumFactor = 0;
  5836. const afterTitans = result.progress[0].attackers.heroes;
  5837. for (let titanId in afterTitans) {
  5838. const titan = afterTitans[titanId];
  5839. const hp = titan.hp / beforeTitans[titanId].hp;
  5840. const energy = titan.energy / 1e3;
  5841. const factor = hp + energy / 20;
  5842. afterSumFactor += factor;
  5843. }
  5844. return afterSumFactor - beforeSumFactor;
  5845. }
  5846.  
  5847. /**
  5848. * Converts an object with IDs to an array with IDs
  5849. *
  5850. * Преобразует объект с идетификаторами в массив с идетификаторами
  5851. */
  5852. function titanObjToArray(obj) {
  5853. let titans = [];
  5854. for (let id in obj) {
  5855. obj[id].id = id;
  5856. titans.push(obj[id]);
  5857. }
  5858. return titans;
  5859. }
  5860.  
  5861. function saveProgress() {
  5862. let saveProgressCall = {
  5863. calls: [{
  5864. name: "dungeonSaveProgress",
  5865. args: {},
  5866. ident: "body"
  5867. }]
  5868. }
  5869. send(JSON.stringify(saveProgressCall), resultEndBattle);
  5870. }
  5871.  
  5872. function endDungeon(reason, info) {
  5873. console.warn(reason, info);
  5874. setProgress(`${I18N('DUNGEON')} ${I18N('COMPLETED')}`, true);
  5875. resolve();
  5876. }
  5877. }
  5878.  
  5879. this.HWHClasses.executeDungeon = executeDungeon;
  5880.  
  5881. /**
  5882. * Passing the tower
  5883. *
  5884. * Прохождение башни
  5885. */
  5886. function testTower() {
  5887. const { executeTower } = HWHClasses;
  5888. return new Promise((resolve, reject) => {
  5889. tower = new executeTower(resolve, reject);
  5890. tower.start();
  5891. });
  5892. }
  5893.  
  5894. /**
  5895. * Passing the tower
  5896. *
  5897. * Прохождение башни
  5898. */
  5899. function executeTower(resolve, reject) {
  5900. lastTowerInfo = {};
  5901.  
  5902. scullCoin = 0;
  5903.  
  5904. heroGetAll = [];
  5905.  
  5906. heroesStates = {};
  5907.  
  5908. argsBattle = {
  5909. heroes: [],
  5910. favor: {},
  5911. };
  5912.  
  5913. callsExecuteTower = {
  5914. calls: [{
  5915. name: "towerGetInfo",
  5916. args: {},
  5917. ident: "towerGetInfo"
  5918. }, {
  5919. name: "teamGetAll",
  5920. args: {},
  5921. ident: "teamGetAll"
  5922. }, {
  5923. name: "teamGetFavor",
  5924. args: {},
  5925. ident: "teamGetFavor"
  5926. }, {
  5927. name: "inventoryGet",
  5928. args: {},
  5929. ident: "inventoryGet"
  5930. }, {
  5931. name: "heroGetAll",
  5932. args: {},
  5933. ident: "heroGetAll"
  5934. }]
  5935. }
  5936.  
  5937. buffIds = [
  5938. {id: 0, cost: 0, isBuy: false}, // plug // заглушка
  5939. {id: 1, cost: 1, isBuy: true}, // 3% attack // 3% атака
  5940. {id: 2, cost: 6, isBuy: true}, // 2% attack // 2% атака
  5941. {id: 3, cost: 16, isBuy: true}, // 4% attack // 4% атака
  5942. {id: 4, cost: 40, isBuy: true}, // 8% attack // 8% атака
  5943. {id: 5, cost: 1, isBuy: true}, // 10% armor // 10% броня
  5944. {id: 6, cost: 6, isBuy: true}, // 5% armor // 5% броня
  5945. {id: 7, cost: 16, isBuy: true}, // 10% armor // 10% броня
  5946. {id: 8, cost: 40, isBuy: true}, // 20% armor // 20% броня
  5947. { id: 9, cost: 1, isBuy: true }, // 10% protection from magic // 10% защита от магии
  5948. { id: 10, cost: 6, isBuy: true }, // 5% protection from magic // 5% защита от магии
  5949. { id: 11, cost: 16, isBuy: true }, // 10% protection from magic // 10% защита от магии
  5950. { id: 12, cost: 40, isBuy: true }, // 20% protection from magic // 20% защита от магии
  5951. { id: 13, cost: 1, isBuy: false }, // 40% health hero // 40% здоровья герою
  5952. { id: 14, cost: 6, isBuy: false }, // 40% health hero // 40% здоровья герою
  5953. { id: 15, cost: 16, isBuy: false }, // 80% health hero // 80% здоровья герою
  5954. { id: 16, cost: 40, isBuy: false }, // 40% health to all heroes // 40% здоровья всем героям
  5955. { id: 17, cost: 1, isBuy: false }, // 40% energy to the hero // 40% энергии герою
  5956. { id: 18, cost: 3, isBuy: false }, // 40% energy to the hero // 40% энергии герою
  5957. { id: 19, cost: 8, isBuy: false }, // 80% energy to the hero // 80% энергии герою
  5958. { id: 20, cost: 20, isBuy: false }, // 40% energy to all heroes // 40% энергии всем героям
  5959. { id: 21, cost: 40, isBuy: false }, // Hero Resurrection // Воскрешение героя
  5960. ]
  5961.  
  5962. this.start = function () {
  5963. send(JSON.stringify(callsExecuteTower), startTower);
  5964. }
  5965.  
  5966. /**
  5967. * Getting data on the Tower
  5968. *
  5969. * Получаем данные по башне
  5970. */
  5971. function startTower(e) {
  5972. res = e.results;
  5973. towerGetInfo = res[0].result.response;
  5974. if (!towerGetInfo) {
  5975. endTower('noTower', res);
  5976. return;
  5977. }
  5978. teamGetAll = res[1].result.response;
  5979. teamGetFavor = res[2].result.response;
  5980. inventoryGet = res[3].result.response;
  5981. heroGetAll = Object.values(res[4].result.response);
  5982.  
  5983. scullCoin = inventoryGet.coin[7] ?? 0;
  5984.  
  5985. argsBattle.favor = teamGetFavor.tower;
  5986. argsBattle.heroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5987. pet = teamGetAll.tower.filter(id => id >= 6000).pop();
  5988. if (pet) {
  5989. argsBattle.pet = pet;
  5990. }
  5991.  
  5992. checkFloor(towerGetInfo);
  5993. }
  5994.  
  5995. function fixHeroesTeam(argsBattle) {
  5996. let fixHeroes = argsBattle.heroes.filter(e => !heroesStates[e]?.isDead);
  5997. if (fixHeroes.length < 5) {
  5998. heroGetAll = heroGetAll.filter(e => !heroesStates[e.id]?.isDead);
  5999. fixHeroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  6000. Object.keys(argsBattle.favor).forEach(e => {
  6001. if (!fixHeroes.includes(+e)) {
  6002. delete argsBattle.favor[e];
  6003. }
  6004. })
  6005. }
  6006. argsBattle.heroes = fixHeroes;
  6007. return argsBattle;
  6008. }
  6009.  
  6010. /**
  6011. * Check the floor
  6012. *
  6013. * Проверяем этаж
  6014. */
  6015. function checkFloor(towerInfo) {
  6016. lastTowerInfo = towerInfo;
  6017. maySkipFloor = +towerInfo.maySkipFloor;
  6018. floorNumber = +towerInfo.floorNumber;
  6019. heroesStates = towerInfo.states.heroes;
  6020. floorInfo = towerInfo.floor;
  6021.  
  6022. /**
  6023. * Is there at least one chest open on the floor
  6024. * Открыт ли на этаже хоть один сундук
  6025. */
  6026. isOpenChest = false;
  6027. if (towerInfo.floorType == "chest") {
  6028. isOpenChest = towerInfo.floor.chests.reduce((n, e) => n + e.opened, 0);
  6029. }
  6030.  
  6031. setProgress(`${I18N('TOWER')}: ${I18N('FLOOR')} ${floorNumber}`);
  6032. if (floorNumber > 49) {
  6033. if (isOpenChest) {
  6034. endTower('alreadyOpenChest 50 floor', floorNumber);
  6035. return;
  6036. }
  6037. }
  6038. /**
  6039. * If the chest is open and you can skip floors, then move on
  6040. * Если сундук открыт и можно скипать этажи, то переходим дальше
  6041. */
  6042. if (towerInfo.mayFullSkip && +towerInfo.teamLevel == 130) {
  6043. if (floorNumber == 1) {
  6044. fullSkipTower();
  6045. return;
  6046. }
  6047. if (isOpenChest) {
  6048. nextOpenChest(floorNumber);
  6049. } else {
  6050. nextChestOpen(floorNumber);
  6051. }
  6052. return;
  6053. }
  6054.  
  6055. // console.log(towerInfo, scullCoin);
  6056. switch (towerInfo.floorType) {
  6057. case "battle":
  6058. if (floorNumber <= maySkipFloor) {
  6059. skipFloor();
  6060. return;
  6061. }
  6062. if (floorInfo.state == 2) {
  6063. nextFloor();
  6064. return;
  6065. }
  6066. startBattle().then(endBattle);
  6067. return;
  6068. case "buff":
  6069. checkBuff(towerInfo);
  6070. return;
  6071. case "chest":
  6072. openChest(floorNumber);
  6073. return;
  6074. default:
  6075. console.log('!', towerInfo.floorType, towerInfo);
  6076. break;
  6077. }
  6078. }
  6079.  
  6080. /**
  6081. * Let's start the fight
  6082. *
  6083. * Начинаем бой
  6084. */
  6085. function startBattle() {
  6086. return new Promise(function (resolve, reject) {
  6087. towerStartBattle = {
  6088. calls: [{
  6089. name: "towerStartBattle",
  6090. args: fixHeroesTeam(argsBattle),
  6091. ident: "body"
  6092. }]
  6093. }
  6094. send(JSON.stringify(towerStartBattle), resultBattle, resolve);
  6095. });
  6096. }
  6097. /**
  6098. * Returns the result of the battle in a promise
  6099. *
  6100. * Возращает резульат боя в промис
  6101. */
  6102. function resultBattle(resultBattles, resolve) {
  6103. battleData = resultBattles.results[0].result.response;
  6104. battleType = "get_tower";
  6105. BattleCalc(battleData, battleType, function (result) {
  6106. resolve(result);
  6107. });
  6108. }
  6109. /**
  6110. * Finishing the fight
  6111. *
  6112. * Заканчиваем бой
  6113. */
  6114. function endBattle(battleInfo) {
  6115. if (battleInfo.result.stars >= 3) {
  6116. endBattleCall = {
  6117. calls: [{
  6118. name: "towerEndBattle",
  6119. args: {
  6120. result: battleInfo.result,
  6121. progress: battleInfo.progress,
  6122. },
  6123. ident: "body"
  6124. }]
  6125. }
  6126. send(JSON.stringify(endBattleCall), resultEndBattle);
  6127. } else {
  6128. endTower('towerEndBattle win: false\n', battleInfo);
  6129. }
  6130. }
  6131.  
  6132. /**
  6133. * Getting and processing battle results
  6134. *
  6135. * Получаем и обрабатываем результаты боя
  6136. */
  6137. function resultEndBattle(e) {
  6138. battleResult = e.results[0].result.response;
  6139. if ('error' in battleResult) {
  6140. endTower('errorBattleResult', battleResult);
  6141. return;
  6142. }
  6143. if ('reward' in battleResult) {
  6144. scullCoin += battleResult.reward?.coin[7] ?? 0;
  6145. }
  6146. nextFloor();
  6147. }
  6148.  
  6149. function nextFloor() {
  6150. nextFloorCall = {
  6151. calls: [{
  6152. name: "towerNextFloor",
  6153. args: {},
  6154. ident: "body"
  6155. }]
  6156. }
  6157. send(JSON.stringify(nextFloorCall), checkDataFloor);
  6158. }
  6159.  
  6160. function openChest(floorNumber) {
  6161. floorNumber = floorNumber || 0;
  6162. openChestCall = {
  6163. calls: [{
  6164. name: "towerOpenChest",
  6165. args: {
  6166. num: 2
  6167. },
  6168. ident: "body"
  6169. }]
  6170. }
  6171. send(JSON.stringify(openChestCall), floorNumber < 50 ? nextFloor : lastChest);
  6172. }
  6173.  
  6174. function lastChest() {
  6175. endTower('openChest 50 floor', floorNumber);
  6176. }
  6177.  
  6178. function skipFloor() {
  6179. skipFloorCall = {
  6180. calls: [{
  6181. name: "towerSkipFloor",
  6182. args: {},
  6183. ident: "body"
  6184. }]
  6185. }
  6186. send(JSON.stringify(skipFloorCall), checkDataFloor);
  6187. }
  6188.  
  6189. function checkBuff(towerInfo) {
  6190. buffArr = towerInfo.floor;
  6191. promises = [];
  6192. for (let buff of buffArr) {
  6193. buffInfo = buffIds[buff.id];
  6194. if (buffInfo.isBuy && buffInfo.cost <= scullCoin) {
  6195. scullCoin -= buffInfo.cost;
  6196. promises.push(buyBuff(buff.id));
  6197. }
  6198. }
  6199. Promise.all(promises).then(nextFloor);
  6200. }
  6201.  
  6202. function buyBuff(buffId) {
  6203. return new Promise(function (resolve, reject) {
  6204. buyBuffCall = {
  6205. calls: [{
  6206. name: "towerBuyBuff",
  6207. args: {
  6208. buffId
  6209. },
  6210. ident: "body"
  6211. }]
  6212. }
  6213. send(JSON.stringify(buyBuffCall), resolve);
  6214. });
  6215. }
  6216.  
  6217. function checkDataFloor(result) {
  6218. towerInfo = result.results[0].result.response;
  6219. if ('reward' in towerInfo && towerInfo.reward?.coin) {
  6220. scullCoin += towerInfo.reward?.coin[7] ?? 0;
  6221. }
  6222. if ('tower' in towerInfo) {
  6223. towerInfo = towerInfo.tower;
  6224. }
  6225. if ('skullReward' in towerInfo) {
  6226. scullCoin += towerInfo.skullReward?.coin[7] ?? 0;
  6227. }
  6228. checkFloor(towerInfo);
  6229. }
  6230. /**
  6231. * Getting tower rewards
  6232. *
  6233. * Получаем награды башни
  6234. */
  6235. function farmTowerRewards(reason) {
  6236. let { pointRewards, points } = lastTowerInfo;
  6237. let pointsAll = Object.getOwnPropertyNames(pointRewards);
  6238. let farmPoints = pointsAll.filter(e => +e <= +points && !pointRewards[e]);
  6239. if (!farmPoints.length) {
  6240. return;
  6241. }
  6242. let farmTowerRewardsCall = {
  6243. calls: [{
  6244. name: "tower_farmPointRewards",
  6245. args: {
  6246. points: farmPoints
  6247. },
  6248. ident: "tower_farmPointRewards"
  6249. }]
  6250. }
  6251.  
  6252. if (scullCoin > 0) {
  6253. farmTowerRewardsCall.calls.push({
  6254. name: "tower_farmSkullReward",
  6255. args: {},
  6256. ident: "tower_farmSkullReward"
  6257. });
  6258. }
  6259.  
  6260. send(JSON.stringify(farmTowerRewardsCall), () => { });
  6261. }
  6262.  
  6263. function fullSkipTower() {
  6264. /**
  6265. * Next chest
  6266. *
  6267. * Следующий сундук
  6268. */
  6269. function nextChest(n) {
  6270. return {
  6271. name: "towerNextChest",
  6272. args: {},
  6273. ident: "group_" + n + "_body"
  6274. }
  6275. }
  6276. /**
  6277. * Open chest
  6278. *
  6279. * Открыть сундук
  6280. */
  6281. function openChest(n) {
  6282. return {
  6283. name: "towerOpenChest",
  6284. args: {
  6285. "num": 2
  6286. },
  6287. ident: "group_" + n + "_body"
  6288. }
  6289. }
  6290.  
  6291. const fullSkipTowerCall = {
  6292. calls: []
  6293. }
  6294.  
  6295. let n = 0;
  6296. for (let i = 0; i < 15; i++) {
  6297. // 15 сундуков
  6298. fullSkipTowerCall.calls.push(nextChest(++n));
  6299. fullSkipTowerCall.calls.push(openChest(++n));
  6300. // +5 сундуков, 250 изюма // towerOpenChest
  6301. // if (i < 5) {
  6302. // fullSkipTowerCall.calls.push(openChest(++n, 2));
  6303. // }
  6304. }
  6305.  
  6306. fullSkipTowerCall.calls.push({
  6307. name: 'towerGetInfo',
  6308. args: {},
  6309. ident: 'group_' + ++n + '_body',
  6310. });
  6311.  
  6312. send(JSON.stringify(fullSkipTowerCall), data => {
  6313. for (const r of data.results) {
  6314. const towerInfo = r?.result?.response;
  6315. if (towerInfo && 'skullReward' in towerInfo) {
  6316. scullCoin += towerInfo.skullReward?.coin[7] ?? 0;
  6317. }
  6318. }
  6319. data.results[0] = data.results[data.results.length - 1];
  6320. checkDataFloor(data);
  6321. });
  6322. }
  6323.  
  6324. function nextChestOpen(floorNumber) {
  6325. const calls = [{
  6326. name: "towerOpenChest",
  6327. args: {
  6328. num: 2
  6329. },
  6330. ident: "towerOpenChest"
  6331. }];
  6332.  
  6333. Send(JSON.stringify({ calls })).then(e => {
  6334. nextOpenChest(floorNumber);
  6335. });
  6336. }
  6337.  
  6338. function nextOpenChest(floorNumber) {
  6339. if (floorNumber > 49) {
  6340. endTower('openChest 50 floor', floorNumber);
  6341. return;
  6342. }
  6343.  
  6344. let nextOpenChestCall = {
  6345. calls: [{
  6346. name: "towerNextChest",
  6347. args: {},
  6348. ident: "towerNextChest"
  6349. }, {
  6350. name: "towerOpenChest",
  6351. args: {
  6352. num: 2
  6353. },
  6354. ident: "towerOpenChest"
  6355. }]
  6356. }
  6357. send(JSON.stringify(nextOpenChestCall), checkDataFloor);
  6358. }
  6359.  
  6360. function endTower(reason, info) {
  6361. console.log(reason, info);
  6362. if (reason != 'noTower') {
  6363. farmTowerRewards(reason);
  6364. }
  6365. setProgress(`${I18N('TOWER')} ${I18N('COMPLETED')}!`, true);
  6366. resolve();
  6367. }
  6368. }
  6369.  
  6370. this.HWHClasses.executeTower = executeTower;
  6371.  
  6372. /**
  6373. * Passage of the arena of the titans
  6374. *
  6375. * Прохождение арены титанов
  6376. */
  6377. function testTitanArena() {
  6378. const { executeTitanArena } = HWHClasses;
  6379. return new Promise((resolve, reject) => {
  6380. titAren = new executeTitanArena(resolve, reject);
  6381. titAren.start();
  6382. });
  6383. }
  6384.  
  6385. /**
  6386. * Passage of the arena of the titans
  6387. *
  6388. * Прохождение арены титанов
  6389. */
  6390. function executeTitanArena(resolve, reject) {
  6391. let titan_arena = [];
  6392. let finishListBattle = [];
  6393. /**
  6394. * ID of the current batch
  6395. *
  6396. * Идетификатор текущей пачки
  6397. */
  6398. let currentRival = 0;
  6399. /**
  6400. * Number of attempts to finish off the pack
  6401. *
  6402. * Количество попыток добития пачки
  6403. */
  6404. let attempts = 0;
  6405. /**
  6406. * Was there an attempt to finish off the current shooting range
  6407. *
  6408. * Была ли попытка добития текущего тира
  6409. */
  6410. let isCheckCurrentTier = false;
  6411. /**
  6412. * Current shooting range
  6413. *
  6414. * Текущий тир
  6415. */
  6416. let currTier = 0;
  6417. /**
  6418. * Number of battles on the current dash
  6419. *
  6420. * Количество битв на текущем тире
  6421. */
  6422. let countRivalsTier = 0;
  6423.  
  6424. let callsStart = {
  6425. calls: [{
  6426. name: "titanArenaGetStatus",
  6427. args: {},
  6428. ident: "titanArenaGetStatus"
  6429. }, {
  6430. name: "teamGetAll",
  6431. args: {},
  6432. ident: "teamGetAll"
  6433. }]
  6434. }
  6435.  
  6436. this.start = function () {
  6437. send(JSON.stringify(callsStart), startTitanArena);
  6438. }
  6439.  
  6440. function startTitanArena(data) {
  6441. let titanArena = data.results[0].result.response;
  6442. if (titanArena.status == 'disabled') {
  6443. endTitanArena('disabled', titanArena);
  6444. return;
  6445. }
  6446.  
  6447. let teamGetAll = data.results[1].result.response;
  6448. titan_arena = teamGetAll.titan_arena;
  6449.  
  6450. checkTier(titanArena)
  6451. }
  6452.  
  6453. function checkTier(titanArena) {
  6454. if (titanArena.status == "peace_time") {
  6455. endTitanArena('Peace_time', titanArena);
  6456. return;
  6457. }
  6458. currTier = titanArena.tier;
  6459. if (currTier) {
  6460. setProgress(`${I18N('TITAN_ARENA')}: ${I18N('LEVEL')} ${currTier}`);
  6461. }
  6462.  
  6463. if (titanArena.status == "completed_tier") {
  6464. titanArenaCompleteTier();
  6465. return;
  6466. }
  6467. /**
  6468. * Checking for the possibility of a raid
  6469. * Проверка на возможность рейда
  6470. */
  6471. if (titanArena.canRaid) {
  6472. titanArenaStartRaid();
  6473. return;
  6474. }
  6475. /**
  6476. * Check was an attempt to achieve the current shooting range
  6477. * Проверка была ли попытка добития текущего тира
  6478. */
  6479. if (!isCheckCurrentTier) {
  6480. checkRivals(titanArena.rivals);
  6481. return;
  6482. }
  6483.  
  6484. endTitanArena('Done or not canRaid', titanArena);
  6485. }
  6486. /**
  6487. * Submit dash information for verification
  6488. *
  6489. * Отправка информации о тире на проверку
  6490. */
  6491. function checkResultInfo(data) {
  6492. let titanArena = data.results[0].result.response;
  6493. checkTier(titanArena);
  6494. }
  6495. /**
  6496. * Finish the current tier
  6497. *
  6498. * Завершить текущий тир
  6499. */
  6500. function titanArenaCompleteTier() {
  6501. isCheckCurrentTier = false;
  6502. let calls = [{
  6503. name: "titanArenaCompleteTier",
  6504. args: {},
  6505. ident: "body"
  6506. }];
  6507. send(JSON.stringify({calls}), checkResultInfo);
  6508. }
  6509. /**
  6510. * Gathering points to be completed
  6511. *
  6512. * Собираем точки которые нужно добить
  6513. */
  6514. function checkRivals(rivals) {
  6515. finishListBattle = [];
  6516. for (let n in rivals) {
  6517. if (rivals[n].attackScore < 250) {
  6518. finishListBattle.push(n);
  6519. }
  6520. }
  6521. console.log('checkRivals', finishListBattle);
  6522. countRivalsTier = finishListBattle.length;
  6523. roundRivals();
  6524. }
  6525. /**
  6526. * Selecting the next point to finish off
  6527. *
  6528. * Выбор следующей точки для добития
  6529. */
  6530. function roundRivals() {
  6531. let countRivals = finishListBattle.length;
  6532. if (!countRivals) {
  6533. /**
  6534. * Whole range checked
  6535. *
  6536. * Весь тир проверен
  6537. */
  6538. isCheckCurrentTier = true;
  6539. titanArenaGetStatus();
  6540. return;
  6541. }
  6542. // setProgress('TitanArena: Уровень ' + currTier + ' Бои: ' + (countRivalsTier - countRivals + 1) + '/' + countRivalsTier);
  6543. currentRival = finishListBattle.pop();
  6544. attempts = +currentRival;
  6545. // console.log('roundRivals', currentRival);
  6546. titanArenaStartBattle(currentRival);
  6547. }
  6548. /**
  6549. * The start of a solo battle
  6550. *
  6551. * Начало одиночной битвы
  6552. */
  6553. function titanArenaStartBattle(rivalId) {
  6554. let calls = [{
  6555. name: "titanArenaStartBattle",
  6556. args: {
  6557. rivalId: rivalId,
  6558. titans: titan_arena
  6559. },
  6560. ident: "body"
  6561. }];
  6562. send(JSON.stringify({calls}), calcResult);
  6563. }
  6564. /**
  6565. * Calculation of the results of the battle
  6566. *
  6567. * Расчет результатов боя
  6568. */
  6569. function calcResult(data) {
  6570. let battlesInfo = data.results[0].result.response.battle;
  6571. /**
  6572. * If attempts are equal to the current battle number we make
  6573. * Если попытки равны номеру текущего боя делаем прерасчет
  6574. */
  6575. if (attempts == currentRival) {
  6576. preCalcBattle(battlesInfo);
  6577. return;
  6578. }
  6579. /**
  6580. * If there are still attempts, we calculate a new battle
  6581. * Если попытки еще есть делаем расчет нового боя
  6582. */
  6583. if (attempts > 0) {
  6584. attempts--;
  6585. calcBattleResult(battlesInfo)
  6586. .then(resultCalcBattle);
  6587. return;
  6588. }
  6589. /**
  6590. * Otherwise, go to the next opponent
  6591. * Иначе переходим к следующему сопернику
  6592. */
  6593. roundRivals();
  6594. }
  6595. /**
  6596. * Processing the results of the battle calculation
  6597. *
  6598. * Обработка результатов расчета битвы
  6599. */
  6600. function resultCalcBattle(resultBattle) {
  6601. // console.log('resultCalcBattle', currentRival, attempts, resultBattle.result.win);
  6602. /**
  6603. * If the current calculation of victory is not a chance or the attempt ended with the finish the battle
  6604. * Если текущий расчет победа или шансов нет или попытки кончились завершаем бой
  6605. */
  6606. if (resultBattle.result.win || !attempts) {
  6607. titanArenaEndBattle({
  6608. progress: resultBattle.progress,
  6609. result: resultBattle.result,
  6610. rivalId: resultBattle.battleData.typeId
  6611. });
  6612. return;
  6613. }
  6614. /**
  6615. * If not victory and there are attempts we start a new battle
  6616. * Если не победа и есть попытки начинаем новый бой
  6617. */
  6618. titanArenaStartBattle(resultBattle.battleData.typeId);
  6619. }
  6620. /**
  6621. * Returns the promise of calculating the results of the battle
  6622. *
  6623. * Возращает промис расчета результатов битвы
  6624. */
  6625. function getBattleInfo(battle, isRandSeed) {
  6626. return new Promise(function (resolve) {
  6627. if (isRandSeed) {
  6628. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  6629. }
  6630. // console.log(battle.seed);
  6631. BattleCalc(battle, "get_titanClanPvp", e => resolve(e));
  6632. });
  6633. }
  6634. /**
  6635. * Recalculate battles
  6636. *
  6637. * Прерасчтет битвы
  6638. */
  6639. function preCalcBattle(battle) {
  6640. let actions = [getBattleInfo(battle, false)];
  6641. const countTestBattle = getInput('countTestBattle');
  6642. for (let i = 0; i < countTestBattle; i++) {
  6643. actions.push(getBattleInfo(battle, true));
  6644. }
  6645. Promise.all(actions)
  6646. .then(resultPreCalcBattle);
  6647. }
  6648. /**
  6649. * Processing the results of the battle recalculation
  6650. *
  6651. * Обработка результатов прерасчета битвы
  6652. */
  6653. function resultPreCalcBattle(e) {
  6654. let wins = e.map(n => n.result.win);
  6655. let firstBattle = e.shift();
  6656. let countWin = wins.reduce((w, s) => w + s);
  6657. const countTestBattle = getInput('countTestBattle');
  6658. console.log('resultPreCalcBattle', `${countWin}/${countTestBattle}`)
  6659. if (countWin > 0) {
  6660. attempts = getInput('countAutoBattle');
  6661. } else {
  6662. attempts = 0;
  6663. }
  6664. resultCalcBattle(firstBattle);
  6665. }
  6666.  
  6667. /**
  6668. * Complete an arena battle
  6669. *
  6670. * Завершить битву на арене
  6671. */
  6672. function titanArenaEndBattle(args) {
  6673. let calls = [{
  6674. name: "titanArenaEndBattle",
  6675. args,
  6676. ident: "body"
  6677. }];
  6678. send(JSON.stringify({calls}), resultTitanArenaEndBattle);
  6679. }
  6680.  
  6681. function resultTitanArenaEndBattle(e) {
  6682. let attackScore = e.results[0].result.response.attackScore;
  6683. let numReval = countRivalsTier - finishListBattle.length;
  6684. setProgress(`${I18N('TITAN_ARENA')}: ${I18N('LEVEL')} ${currTier} </br>${I18N('BATTLES')}: ${numReval}/${countRivalsTier} - ${attackScore}`);
  6685. /**
  6686. * TODO: Might need to improve the results.
  6687. * TODO: Возможно стоит сделать улучшение результатов
  6688. */
  6689. // console.log('resultTitanArenaEndBattle', e)
  6690. console.log('resultTitanArenaEndBattle', numReval + '/' + countRivalsTier, attempts)
  6691. roundRivals();
  6692. }
  6693. /**
  6694. * Arena State
  6695. *
  6696. * Состояние арены
  6697. */
  6698. function titanArenaGetStatus() {
  6699. let calls = [{
  6700. name: "titanArenaGetStatus",
  6701. args: {},
  6702. ident: "body"
  6703. }];
  6704. send(JSON.stringify({calls}), checkResultInfo);
  6705. }
  6706. /**
  6707. * Arena Raid Request
  6708. *
  6709. * Запрос рейда арены
  6710. */
  6711. function titanArenaStartRaid() {
  6712. let calls = [{
  6713. name: "titanArenaStartRaid",
  6714. args: {
  6715. titans: titan_arena
  6716. },
  6717. ident: "body"
  6718. }];
  6719. send(JSON.stringify({calls}), calcResults);
  6720. }
  6721.  
  6722. function calcResults(data) {
  6723. let battlesInfo = data.results[0].result.response;
  6724. let {attackers, rivals} = battlesInfo;
  6725.  
  6726. let promises = [];
  6727. for (let n in rivals) {
  6728. rival = rivals[n];
  6729. promises.push(calcBattleResult({
  6730. attackers: attackers,
  6731. defenders: [rival.team],
  6732. seed: rival.seed,
  6733. typeId: n,
  6734. }));
  6735. }
  6736.  
  6737. Promise.all(promises)
  6738. .then(results => {
  6739. const endResults = {};
  6740. for (let info of results) {
  6741. let id = info.battleData.typeId;
  6742. endResults[id] = {
  6743. progress: info.progress,
  6744. result: info.result,
  6745. }
  6746. }
  6747. titanArenaEndRaid(endResults);
  6748. });
  6749. }
  6750.  
  6751. function calcBattleResult(battleData) {
  6752. return new Promise(function (resolve, reject) {
  6753. BattleCalc(battleData, "get_titanClanPvp", resolve);
  6754. });
  6755. }
  6756.  
  6757. /**
  6758. * Sending Raid Results
  6759. *
  6760. * Отправка результатов рейда
  6761. */
  6762. function titanArenaEndRaid(results) {
  6763. titanArenaEndRaidCall = {
  6764. calls: [{
  6765. name: "titanArenaEndRaid",
  6766. args: {
  6767. results
  6768. },
  6769. ident: "body"
  6770. }]
  6771. }
  6772. send(JSON.stringify(titanArenaEndRaidCall), checkRaidResults);
  6773. }
  6774.  
  6775. function checkRaidResults(data) {
  6776. results = data.results[0].result.response.results;
  6777. isSucsesRaid = true;
  6778. for (let i in results) {
  6779. isSucsesRaid &&= (results[i].attackScore >= 250);
  6780. }
  6781.  
  6782. if (isSucsesRaid) {
  6783. titanArenaCompleteTier();
  6784. } else {
  6785. titanArenaGetStatus();
  6786. }
  6787. }
  6788.  
  6789. function titanArenaFarmDailyReward() {
  6790. titanArenaFarmDailyRewardCall = {
  6791. calls: [{
  6792. name: "titanArenaFarmDailyReward",
  6793. args: {},
  6794. ident: "body"
  6795. }]
  6796. }
  6797. send(JSON.stringify(titanArenaFarmDailyRewardCall), () => {console.log('Done farm daily reward')});
  6798. }
  6799.  
  6800. function endTitanArena(reason, info) {
  6801. if (!['Peace_time', 'disabled'].includes(reason)) {
  6802. titanArenaFarmDailyReward();
  6803. }
  6804. console.log(reason, info);
  6805. setProgress(`${I18N('TITAN_ARENA')} ${I18N('COMPLETED')}!`, true);
  6806. resolve();
  6807. }
  6808. }
  6809.  
  6810. this.HWHClasses.executeTitanArena = executeTitanArena;
  6811.  
  6812. function hackGame() {
  6813. const self = this;
  6814. selfGame = null;
  6815. bindId = 1e9;
  6816. this.libGame = null;
  6817. this.doneLibLoad = () => {};
  6818.  
  6819. /**
  6820. * List of correspondence of used classes to their names
  6821. *
  6822. * Список соответствия используемых классов их названиям
  6823. */
  6824. ObjectsList = [
  6825. { name: 'BattlePresets', prop: 'game.battle.controller.thread.BattlePresets' },
  6826. { name: 'DataStorage', prop: 'game.data.storage.DataStorage' },
  6827. { name: 'BattleConfigStorage', prop: 'game.data.storage.battle.BattleConfigStorage' },
  6828. { name: 'BattleInstantPlay', prop: 'game.battle.controller.instant.BattleInstantPlay' },
  6829. { name: 'MultiBattleInstantReplay', prop: 'game.battle.controller.instant.MultiBattleInstantReplay' },
  6830. { name: 'MultiBattleResult', prop: 'game.battle.controller.MultiBattleResult' },
  6831.  
  6832. { name: 'PlayerMissionData', prop: 'game.model.user.mission.PlayerMissionData' },
  6833. { name: 'PlayerMissionBattle', prop: 'game.model.user.mission.PlayerMissionBattle' },
  6834. { name: 'GameModel', prop: 'game.model.GameModel' },
  6835. { name: 'CommandManager', prop: 'game.command.CommandManager' },
  6836. { name: 'MissionCommandList', prop: 'game.command.rpc.mission.MissionCommandList' },
  6837. { name: 'RPCCommandBase', prop: 'game.command.rpc.RPCCommandBase' },
  6838. { name: 'PlayerTowerData', prop: 'game.model.user.tower.PlayerTowerData' },
  6839. { name: 'TowerCommandList', prop: 'game.command.tower.TowerCommandList' },
  6840. { name: 'PlayerHeroTeamResolver', prop: 'game.model.user.hero.PlayerHeroTeamResolver' },
  6841. { name: 'BattlePausePopup', prop: 'game.view.popup.battle.BattlePausePopup' },
  6842. { name: 'BattlePopup', prop: 'game.view.popup.battle.BattlePopup' },
  6843. { name: 'DisplayObjectContainer', prop: 'starling.display.DisplayObjectContainer' },
  6844. { name: 'GuiClipContainer', prop: 'engine.core.clipgui.GuiClipContainer' },
  6845. { name: 'BattlePausePopupClip', prop: 'game.view.popup.battle.BattlePausePopupClip' },
  6846. { name: 'ClipLabel', prop: 'game.view.gui.components.ClipLabel' },
  6847. { name: 'ClipLabelBase', prop: 'game.view.gui.components.ClipLabelBase' },
  6848. { name: 'Translate', prop: 'com.progrestar.common.lang.Translate' },
  6849. { name: 'ClipButtonLabeledCentered', prop: 'game.view.gui.components.ClipButtonLabeledCentered' },
  6850. { name: 'BattlePausePopupMediator', prop: 'game.mediator.gui.popup.battle.BattlePausePopupMediator' },
  6851. { name: 'SettingToggleButton', prop: 'game.mechanics.settings.popup.view.SettingToggleButton' },
  6852. { name: 'PlayerDungeonData', prop: 'game.mechanics.dungeon.model.PlayerDungeonData' },
  6853. { name: 'NextDayUpdatedManager', prop: 'game.model.user.NextDayUpdatedManager' },
  6854. { name: 'BattleController', prop: 'game.battle.controller.BattleController' },
  6855. { name: 'BattleSettingsModel', prop: 'game.battle.controller.BattleSettingsModel' },
  6856. { name: 'BooleanProperty', prop: 'engine.core.utils.property.BooleanProperty' },
  6857. { name: 'RuleStorage', prop: 'game.data.storage.rule.RuleStorage' },
  6858. { name: 'BattleConfig', prop: 'battle.BattleConfig' },
  6859. { name: 'BattleGuiMediator', prop: 'game.battle.gui.BattleGuiMediator' },
  6860. { name: 'BooleanPropertyWriteable', prop: 'engine.core.utils.property.BooleanPropertyWriteable' },
  6861. { name: 'BattleLogEncoder', prop: 'battle.log.BattleLogEncoder' },
  6862. { name: 'BattleLogReader', prop: 'battle.log.BattleLogReader' },
  6863. { name: 'PlayerSubscriptionInfoValueObject', prop: 'game.model.user.subscription.PlayerSubscriptionInfoValueObject' },
  6864. { name: 'AdventureMapCamera', prop: 'game.mechanics.adventure.popup.map.AdventureMapCamera' },
  6865. ];
  6866.  
  6867. /**
  6868. * Contains the game classes needed to write and override game methods
  6869. *
  6870. * Содержит классы игры необходимые для написания и подмены методов игры
  6871. */
  6872. Game = {
  6873. /**
  6874. * Function 'e'
  6875. * Функция 'e'
  6876. */
  6877. bindFunc: function (a, b) {
  6878. if (null == b) return null;
  6879. null == b.__id__ && (b.__id__ = bindId++);
  6880. var c;
  6881. null == a.hx__closures__ ? (a.hx__closures__ = {}) : (c = a.hx__closures__[b.__id__]);
  6882. null == c && ((c = b.bind(a)), (a.hx__closures__[b.__id__] = c));
  6883. return c;
  6884. },
  6885. };
  6886.  
  6887. /**
  6888. * Connects to game objects via the object creation event
  6889. *
  6890. * Подключается к объектам игры через событие создания объекта
  6891. */
  6892. function connectGame() {
  6893. for (let obj of ObjectsList) {
  6894. /**
  6895. * https: //stackoverflow.com/questions/42611719/how-to-intercept-and-modify-a-specific-property-for-any-object
  6896. */
  6897. Object.defineProperty(Object.prototype, obj.prop, {
  6898. set: function (value) {
  6899. if (!selfGame) {
  6900. selfGame = this;
  6901. }
  6902. if (!Game[obj.name]) {
  6903. Game[obj.name] = value;
  6904. }
  6905. // console.log('set ' + obj.prop, this, value);
  6906. this[obj.prop + '_'] = value;
  6907. },
  6908. get: function () {
  6909. // console.log('get ' + obj.prop, this);
  6910. return this[obj.prop + '_'];
  6911. },
  6912. });
  6913. }
  6914. }
  6915.  
  6916. /**
  6917. * Game.BattlePresets
  6918. * @param {bool} a isReplay
  6919. * @param {bool} b autoToggleable
  6920. * @param {bool} c auto On Start
  6921. * @param {object} d config
  6922. * @param {bool} f showBothTeams
  6923. */
  6924. /**
  6925. * Returns the results of the battle to the callback function
  6926. * Возвращает в функцию callback результаты боя
  6927. * @param {*} battleData battle data данные боя
  6928. * @param {*} battleConfig combat configuration type options:
  6929. *
  6930. * тип конфигурации боя варианты:
  6931. *
  6932. * "get_invasion", "get_titanPvpManual", "get_titanPvp",
  6933. * "get_titanClanPvp","get_clanPvp","get_titan","get_boss",
  6934. * "get_tower","get_pve","get_pvpManual","get_pvp","get_core"
  6935. *
  6936. * You can specify the xYc function in the game.assets.storage.BattleAssetStorage class
  6937. *
  6938. * Можно уточнить в классе game.assets.storage.BattleAssetStorage функция xYc
  6939. * @param {*} callback функция в которую вернуться результаты боя
  6940. */
  6941. this.BattleCalc = function (battleData, battleConfig, callback) {
  6942. // battleConfig = battleConfig || getBattleType(battleData.type)
  6943. if (!Game.BattlePresets) throw Error('Use connectGame');
  6944. battlePresets = new Game.BattlePresets(
  6945. battleData.progress,
  6946. !1,
  6947. !0,
  6948. Game.DataStorage[getFn(Game.DataStorage, 24)][getF(Game.BattleConfigStorage, battleConfig)](),
  6949. !1
  6950. );
  6951. let battleInstantPlay;
  6952. if (battleData.progress?.length > 1) {
  6953. battleInstantPlay = new Game.MultiBattleInstantReplay(battleData, battlePresets);
  6954. } else {
  6955. battleInstantPlay = new Game.BattleInstantPlay(battleData, battlePresets);
  6956. }
  6957. battleInstantPlay[getProtoFn(Game.BattleInstantPlay, 9)].add((battleInstant) => {
  6958. const MBR_2 = getProtoFn(Game.MultiBattleResult, 2);
  6959. const battleResults = battleInstant[getF(Game.BattleInstantPlay, 'get_result')]();
  6960. const battleData = battleInstant[getF(Game.BattleInstantPlay, 'get_rawBattleInfo')]();
  6961. const battleLogs = [];
  6962. const timeLimit = battlePresets[getF(Game.BattlePresets, 'get_timeLimit')]();
  6963. let battleTime = 0;
  6964. let battleTimer = 0;
  6965. for (const battleResult of battleResults[MBR_2]) {
  6966. const battleLog = Game.BattleLogEncoder.read(new Game.BattleLogReader(battleResult));
  6967. battleLogs.push(battleLog);
  6968. const maxTime = Math.max(...battleLog.map((e) => (e.time < timeLimit && e.time !== 168.8 ? e.time : 0)));
  6969. battleTimer += getTimer(maxTime);
  6970. battleTime += maxTime;
  6971. }
  6972. callback({
  6973. battleLogs,
  6974. battleTime,
  6975. battleTimer,
  6976. battleData,
  6977. progress: battleResults[getF(Game.MultiBattleResult, 'get_progress')](),
  6978. result: battleResults[getF(Game.MultiBattleResult, 'get_result')](),
  6979. });
  6980. });
  6981. battleInstantPlay.start();
  6982. };
  6983.  
  6984. /**
  6985. * Returns a function with the specified name from the class
  6986. *
  6987. * Возвращает из класса функцию с указанным именем
  6988. * @param {Object} classF Class // класс
  6989. * @param {String} nameF function name // имя функции
  6990. * @param {String} pos name and alias order // порядок имени и псевдонима
  6991. * @returns
  6992. */
  6993. function getF(classF, nameF, pos) {
  6994. pos = pos || false;
  6995. let prop = Object.entries(classF.prototype.__properties__);
  6996. if (!pos) {
  6997. return prop.filter((e) => e[1] == nameF).pop()[0];
  6998. } else {
  6999. return prop.filter((e) => e[0] == nameF).pop()[1];
  7000. }
  7001. }
  7002.  
  7003. /**
  7004. * Returns a function with the specified name from the class
  7005. *
  7006. * Возвращает из класса функцию с указанным именем
  7007. * @param {Object} classF Class // класс
  7008. * @param {String} nameF function name // имя функции
  7009. * @returns
  7010. */
  7011. function getFnP(classF, nameF) {
  7012. let prop = Object.entries(classF.__properties__);
  7013. return prop.filter((e) => e[1] == nameF).pop()[0];
  7014. }
  7015.  
  7016. /**
  7017. * Returns the function name with the specified ordinal from the class
  7018. *
  7019. * Возвращает имя функции с указаным порядковым номером из класса
  7020. * @param {Object} classF Class // класс
  7021. * @param {Number} nF Order number of function // порядковый номер функции
  7022. * @returns
  7023. */
  7024. function getFn(classF, nF) {
  7025. let prop = Object.keys(classF);
  7026. return prop[nF];
  7027. }
  7028.  
  7029. /**
  7030. * Returns the name of the function with the specified serial number from the prototype of the class
  7031. *
  7032. * Возвращает имя функции с указаным порядковым номером из прототипа класса
  7033. * @param {Object} classF Class // класс
  7034. * @param {Number} nF Order number of function // порядковый номер функции
  7035. * @returns
  7036. */
  7037. function getProtoFn(classF, nF) {
  7038. let prop = Object.keys(classF.prototype);
  7039. return prop[nF];
  7040. }
  7041. /**
  7042. * Description of replaced functions
  7043. *
  7044. * Описание подменяемых функций
  7045. */
  7046. replaceFunction = {
  7047. company: function () {
  7048. let PMD_12 = getProtoFn(Game.PlayerMissionData, 12);
  7049. let oldSkipMisson = Game.PlayerMissionData.prototype[PMD_12];
  7050. Game.PlayerMissionData.prototype[PMD_12] = function (a, b, c) {
  7051. if (!isChecked('passBattle')) {
  7052. oldSkipMisson.call(this, a, b, c);
  7053. return;
  7054. }
  7055.  
  7056. try {
  7057. this[getProtoFn(Game.PlayerMissionData, 9)] = new Game.PlayerMissionBattle(a, b, c);
  7058.  
  7059. var a = new Game.BattlePresets(
  7060. !1,
  7061. !1,
  7062. !0,
  7063. Game.DataStorage[getFn(Game.DataStorage, 24)][getProtoFn(Game.BattleConfigStorage, 20)](),
  7064. !1
  7065. );
  7066. a = new Game.BattleInstantPlay(c, a);
  7067. a[getProtoFn(Game.BattleInstantPlay, 9)].add(Game.bindFunc(this, this.P$h));
  7068. a.start();
  7069. } catch (error) {
  7070. console.error('company', error);
  7071. oldSkipMisson.call(this, a, b, c);
  7072. }
  7073. };
  7074.  
  7075. Game.PlayerMissionData.prototype.P$h = function (a) {
  7076. let GM_2 = getFn(Game.GameModel, 2);
  7077. let GM_P2 = getProtoFn(Game.GameModel, 2);
  7078. let CM_20 = getProtoFn(Game.CommandManager, 20);
  7079. let MCL_2 = getProtoFn(Game.MissionCommandList, 2);
  7080. let MBR_15 = getF(Game.MultiBattleResult, 'get_result');
  7081. let RPCCB_15 = getProtoFn(Game.RPCCommandBase, 16);
  7082. let PMD_32 = getProtoFn(Game.PlayerMissionData, 32);
  7083. Game.GameModel[GM_2]()[GM_P2][CM_20][MCL_2](a[MBR_15]())[RPCCB_15](Game.bindFunc(this, this[PMD_32]));
  7084. };
  7085. },
  7086. /*
  7087. tower: function () {
  7088. let PTD_67 = getProtoFn(Game.PlayerTowerData, 67);
  7089. let oldSkipTower = Game.PlayerTowerData.prototype[PTD_67];
  7090. Game.PlayerTowerData.prototype[PTD_67] = function (a) {
  7091. if (!isChecked('passBattle')) {
  7092. oldSkipTower.call(this, a);
  7093. return;
  7094. }
  7095. try {
  7096. var p = new Game.BattlePresets(
  7097. !1,
  7098. !1,
  7099. !0,
  7100. Game.DataStorage[getFn(Game.DataStorage, 24)][getProtoFn(Game.BattleConfigStorage, 20)](),
  7101. !1
  7102. );
  7103. a = new Game.BattleInstantPlay(a, p);
  7104. a[getProtoFn(Game.BattleInstantPlay, 9)].add(Game.bindFunc(this, this.P$h));
  7105. a.start();
  7106. } catch (error) {
  7107. console.error('tower', error);
  7108. oldSkipMisson.call(this, a, b, c);
  7109. }
  7110. };
  7111.  
  7112. Game.PlayerTowerData.prototype.P$h = function (a) {
  7113. const GM_2 = getFnP(Game.GameModel, 'get_instance');
  7114. const GM_P2 = getProtoFn(Game.GameModel, 2);
  7115. const CM_29 = getProtoFn(Game.CommandManager, 29);
  7116. const TCL_5 = getProtoFn(Game.TowerCommandList, 5);
  7117. const MBR_15 = getF(Game.MultiBattleResult, 'get_result');
  7118. const RPCCB_15 = getProtoFn(Game.RPCCommandBase, 17);
  7119. const PTD_78 = getProtoFn(Game.PlayerTowerData, 78);
  7120. Game.GameModel[GM_2]()[GM_P2][CM_29][TCL_5](a[MBR_15]())[RPCCB_15](Game.bindFunc(this, this[PTD_78]));
  7121. };
  7122. },
  7123. */
  7124. // skipSelectHero: function() {
  7125. // if (!HOST) throw Error('Use connectGame');
  7126. // Game.PlayerHeroTeamResolver.prototype[getProtoFn(Game.PlayerHeroTeamResolver, 3)] = () => false;
  7127. // },
  7128. passBattle: function () {
  7129. let BPP_4 = getProtoFn(Game.BattlePausePopup, 4);
  7130. let oldPassBattle = Game.BattlePausePopup.prototype[BPP_4];
  7131. Game.BattlePausePopup.prototype[BPP_4] = function (a) {
  7132. if (!isChecked('passBattle')) {
  7133. oldPassBattle.call(this, a);
  7134. return;
  7135. }
  7136. try {
  7137. Game.BattlePopup.prototype[getProtoFn(Game.BattlePausePopup, 4)].call(this, a);
  7138. this[getProtoFn(Game.BattlePausePopup, 3)]();
  7139. this[getProtoFn(Game.DisplayObjectContainer, 3)](this.clip[getProtoFn(Game.GuiClipContainer, 2)]());
  7140. this.clip[getProtoFn(Game.BattlePausePopupClip, 1)][getProtoFn(Game.ClipLabelBase, 9)](
  7141. Game.Translate.translate('UI_POPUP_BATTLE_PAUSE')
  7142. );
  7143.  
  7144. this.clip[getProtoFn(Game.BattlePausePopupClip, 2)][getProtoFn(Game.ClipButtonLabeledCentered, 2)](
  7145. Game.Translate.translate('UI_POPUP_BATTLE_RETREAT'),
  7146. ((q = this[getProtoFn(Game.BattlePausePopup, 1)]), Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 17)]))
  7147. );
  7148. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 2)](
  7149. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 14)](),
  7150. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 13)]()
  7151. ? ((q = this[getProtoFn(Game.BattlePausePopup, 1)]), Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 18)]))
  7152. : ((q = this[getProtoFn(Game.BattlePausePopup, 1)]), Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 18)]))
  7153. );
  7154.  
  7155. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 0)][
  7156. getProtoFn(Game.ClipLabelBase, 24)
  7157. ]();
  7158. this.clip[getProtoFn(Game.BattlePausePopupClip, 3)][getProtoFn(Game.SettingToggleButton, 3)](
  7159. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 9)]()
  7160. );
  7161. this.clip[getProtoFn(Game.BattlePausePopupClip, 4)][getProtoFn(Game.SettingToggleButton, 3)](
  7162. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 10)]()
  7163. );
  7164. this.clip[getProtoFn(Game.BattlePausePopupClip, 6)][getProtoFn(Game.SettingToggleButton, 3)](
  7165. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 11)]()
  7166. );
  7167. } catch (error) {
  7168. console.error('passBattle', error);
  7169. oldPassBattle.call(this, a);
  7170. }
  7171. };
  7172.  
  7173. let retreatButtonLabel = getF(Game.BattlePausePopupMediator, 'get_retreatButtonLabel');
  7174. let oldFunc = Game.BattlePausePopupMediator.prototype[retreatButtonLabel];
  7175. Game.BattlePausePopupMediator.prototype[retreatButtonLabel] = function () {
  7176. if (isChecked('passBattle')) {
  7177. return I18N('BTN_PASS');
  7178. } else {
  7179. return oldFunc.call(this);
  7180. }
  7181. };
  7182. },
  7183. endlessCards: function () {
  7184. let PDD_21 = getProtoFn(Game.PlayerDungeonData, 21);
  7185. let oldEndlessCards = Game.PlayerDungeonData.prototype[PDD_21];
  7186. Game.PlayerDungeonData.prototype[PDD_21] = function () {
  7187. if (countPredictionCard <= 0) {
  7188. return true;
  7189. } else {
  7190. return oldEndlessCards.call(this);
  7191. }
  7192. };
  7193. },
  7194. speedBattle: function () {
  7195. const get_timeScale = getF(Game.BattleController, 'get_timeScale');
  7196. const oldSpeedBattle = Game.BattleController.prototype[get_timeScale];
  7197. Game.BattleController.prototype[get_timeScale] = function () {
  7198. const speedBattle = Number.parseFloat(getInput('speedBattle'));
  7199. if (!speedBattle) {
  7200. return oldSpeedBattle.call(this);
  7201. }
  7202. try {
  7203. const BC_12 = getProtoFn(Game.BattleController, 12);
  7204. const BSM_12 = getProtoFn(Game.BattleSettingsModel, 12);
  7205. const BP_get_value = getF(Game.BooleanProperty, 'get_value');
  7206. if (this[BC_12][BSM_12][BP_get_value]()) {
  7207. return 0;
  7208. }
  7209. const BSM_2 = getProtoFn(Game.BattleSettingsModel, 2);
  7210. const BC_49 = getProtoFn(Game.BattleController, 49);
  7211. const BSM_1 = getProtoFn(Game.BattleSettingsModel, 1);
  7212. const BC_14 = getProtoFn(Game.BattleController, 14);
  7213. const BC_3 = getFn(Game.BattleController, 3);
  7214. if (this[BC_12][BSM_2][BP_get_value]()) {
  7215. var a = speedBattle * this[BC_49]();
  7216. } else {
  7217. a = this[BC_12][BSM_1][BP_get_value]();
  7218. const maxSpeed = Math.max(...this[BC_14]);
  7219. const multiple = a == this[BC_14].indexOf(maxSpeed) ? (maxSpeed >= 4 ? speedBattle : this[BC_14][a]) : this[BC_14][a];
  7220. a = multiple * Game.BattleController[BC_3][BP_get_value]() * this[BC_49]();
  7221. }
  7222. const BSM_24 = getProtoFn(Game.BattleSettingsModel, 24);
  7223. a > this[BC_12][BSM_24][BP_get_value]() && (a = this[BC_12][BSM_24][BP_get_value]());
  7224. const DS_23 = getFn(Game.DataStorage, 23);
  7225. const get_battleSpeedMultiplier = getF(Game.RuleStorage, 'get_battleSpeedMultiplier', true);
  7226. var b = Game.DataStorage[DS_23][get_battleSpeedMultiplier]();
  7227. const R_1 = getFn(selfGame.Reflect, 1);
  7228. const BC_1 = getFn(Game.BattleController, 1);
  7229. const get_config = getF(Game.BattlePresets, 'get_config');
  7230. null != b &&
  7231. (a = selfGame.Reflect[R_1](b, this[BC_1][get_config]().ident)
  7232. ? a * selfGame.Reflect[R_1](b, this[BC_1][get_config]().ident)
  7233. : a * selfGame.Reflect[R_1](b, 'default'));
  7234. return a;
  7235. } catch (error) {
  7236. console.error('passBatspeedBattletle', error);
  7237. return oldSpeedBattle.call(this);
  7238. }
  7239. };
  7240. },
  7241.  
  7242. /**
  7243. * Acceleration button without Valkyries favor
  7244. *
  7245. * Кнопка ускорения без Покровительства Валькирий
  7246. */
  7247. battleFastKey: function () {
  7248. const BGM_44 = getProtoFn(Game.BattleGuiMediator, 44);
  7249. const oldBattleFastKey = Game.BattleGuiMediator.prototype[BGM_44];
  7250. Game.BattleGuiMediator.prototype[BGM_44] = function () {
  7251. let flag = true;
  7252. //console.log(flag)
  7253. if (!flag) {
  7254. return oldBattleFastKey.call(this);
  7255. }
  7256. try {
  7257. const BGM_9 = getProtoFn(Game.BattleGuiMediator, 9);
  7258. const BGM_10 = getProtoFn(Game.BattleGuiMediator, 10);
  7259. const BPW_0 = getProtoFn(Game.BooleanPropertyWriteable, 0);
  7260. this[BGM_9][BPW_0](true);
  7261. this[BGM_10][BPW_0](true);
  7262. } catch (error) {
  7263. console.error(error);
  7264. return oldBattleFastKey.call(this);
  7265. }
  7266. };
  7267. },
  7268. fastSeason: function () {
  7269. const GameNavigator = selfGame['game.screen.navigator.GameNavigator'];
  7270. const oldFuncName = getProtoFn(GameNavigator, 18);
  7271. const newFuncName = getProtoFn(GameNavigator, 16);
  7272. const oldFastSeason = GameNavigator.prototype[oldFuncName];
  7273. const newFastSeason = GameNavigator.prototype[newFuncName];
  7274. GameNavigator.prototype[oldFuncName] = function (a, b) {
  7275. if (isChecked('fastSeason')) {
  7276. return newFastSeason.apply(this, [a]);
  7277. } else {
  7278. return oldFastSeason.apply(this, [a, b]);
  7279. }
  7280. };
  7281. },
  7282. ShowChestReward: function () {
  7283. const TitanArtifactChest = selfGame['game.mechanics.titan_arena.mediator.chest.TitanArtifactChestRewardPopupMediator'];
  7284. const getOpenAmountTitan = getF(TitanArtifactChest, 'get_openAmount');
  7285. const oldGetOpenAmountTitan = TitanArtifactChest.prototype[getOpenAmountTitan];
  7286. TitanArtifactChest.prototype[getOpenAmountTitan] = function () {
  7287. if (correctShowOpenArtifact) {
  7288. correctShowOpenArtifact--;
  7289. return 100;
  7290. }
  7291. return oldGetOpenAmountTitan.call(this);
  7292. };
  7293.  
  7294. const ArtifactChest = selfGame['game.view.popup.artifactchest.rewardpopup.ArtifactChestRewardPopupMediator'];
  7295. const getOpenAmount = getF(ArtifactChest, 'get_openAmount');
  7296. const oldGetOpenAmount = ArtifactChest.prototype[getOpenAmount];
  7297. ArtifactChest.prototype[getOpenAmount] = function () {
  7298. if (correctShowOpenArtifact) {
  7299. correctShowOpenArtifact--;
  7300. return 100;
  7301. }
  7302. return oldGetOpenAmount.call(this);
  7303. };
  7304. },
  7305. fixCompany: function () {
  7306. const GameBattleView = selfGame['game.mediator.gui.popup.battle.GameBattleView'];
  7307. const BattleThread = selfGame['game.battle.controller.thread.BattleThread'];
  7308. const getOnViewDisposed = getF(BattleThread, 'get_onViewDisposed');
  7309. const getThread = getF(GameBattleView, 'get_thread');
  7310. const oldFunc = GameBattleView.prototype[getThread];
  7311. GameBattleView.prototype[getThread] = function () {
  7312. return (
  7313. oldFunc.call(this) || {
  7314. [getOnViewDisposed]: async () => {},
  7315. }
  7316. );
  7317. };
  7318. },
  7319. BuyTitanArtifact: function () {
  7320. const BIP_4 = getProtoFn(selfGame['game.view.popup.shop.buy.BuyItemPopup'], 4);
  7321. const BuyItemPopup = selfGame['game.view.popup.shop.buy.BuyItemPopup'];
  7322. const oldFunc = BuyItemPopup.prototype[BIP_4];
  7323. BuyItemPopup.prototype[BIP_4] = function () {
  7324. if (isChecked('countControl')) {
  7325. const BuyTitanArtifactItemPopup = selfGame['game.view.popup.shop.buy.BuyTitanArtifactItemPopup'];
  7326. const BTAP_0 = getProtoFn(BuyTitanArtifactItemPopup, 0);
  7327. if (this[BTAP_0]) {
  7328. const BuyTitanArtifactPopupMediator = selfGame['game.mediator.gui.popup.shop.buy.BuyTitanArtifactItemPopupMediator'];
  7329. const BTAM_1 = getProtoFn(BuyTitanArtifactPopupMediator, 1);
  7330. const BuyItemPopupMediator = selfGame['game.mediator.gui.popup.shop.buy.BuyItemPopupMediator'];
  7331. const BIPM_5 = getProtoFn(BuyItemPopupMediator, 5);
  7332. const BIPM_7 = getProtoFn(BuyItemPopupMediator, 7);
  7333. const BIPM_9 = getProtoFn(BuyItemPopupMediator, 9);
  7334.  
  7335. let need = Math.min(this[BTAP_0][BTAM_1](), this[BTAP_0][BIPM_7]);
  7336. need = need ? need : 60;
  7337. this[BTAP_0][BIPM_9] = need;
  7338. this[BTAP_0][BIPM_5] = 10;
  7339. }
  7340. }
  7341. oldFunc.call(this);
  7342. };
  7343. },
  7344. ClanQuestsFastFarm: function () {
  7345. const VipRuleValueObject = selfGame['game.data.storage.rule.VipRuleValueObject'];
  7346. const getClanQuestsFastFarm = getF(VipRuleValueObject, 'get_clanQuestsFastFarm', 1);
  7347. VipRuleValueObject.prototype[getClanQuestsFastFarm] = function () {
  7348. return 0;
  7349. };
  7350. },
  7351. adventureCamera: function () {
  7352. const AMC_40 = getProtoFn(Game.AdventureMapCamera, 40);
  7353. const AMC_5 = getProtoFn(Game.AdventureMapCamera, 5);
  7354. const oldFunc = Game.AdventureMapCamera.prototype[AMC_40];
  7355. Game.AdventureMapCamera.prototype[AMC_40] = function (a) {
  7356. this[AMC_5] = 0.4;
  7357. oldFunc.bind(this)(a);
  7358. };
  7359. },
  7360. unlockMission: function () {
  7361. const WorldMapStoryDrommerHelper = selfGame['game.mediator.gui.worldmap.WorldMapStoryDrommerHelper'];
  7362. const WMSDH_4 = getFn(WorldMapStoryDrommerHelper, 4);
  7363. const WMSDH_7 = getFn(WorldMapStoryDrommerHelper, 7);
  7364. WorldMapStoryDrommerHelper[WMSDH_4] = function () {
  7365. return true;
  7366. };
  7367. WorldMapStoryDrommerHelper[WMSDH_7] = function () {
  7368. return true;
  7369. };
  7370. },
  7371. };
  7372.  
  7373. /**
  7374. * Starts replacing recorded functions
  7375. *
  7376. * Запускает замену записанных функций
  7377. */
  7378. this.activateHacks = function () {
  7379. if (!selfGame) throw Error('Use connectGame');
  7380. for (let func in replaceFunction) {
  7381. try {
  7382. replaceFunction[func]();
  7383. } catch (error) {
  7384. console.error(error);
  7385. }
  7386. }
  7387. };
  7388.  
  7389. /**
  7390. * Returns the game object
  7391. *
  7392. * Возвращает объект игры
  7393. */
  7394. this.getSelfGame = function () {
  7395. return selfGame;
  7396. };
  7397.  
  7398. /**
  7399. * Updates game data
  7400. *
  7401. * Обновляет данные игры
  7402. */
  7403. this.refreshGame = function () {
  7404. new Game.NextDayUpdatedManager()[getProtoFn(Game.NextDayUpdatedManager, 5)]();
  7405. try {
  7406. cheats.refreshInventory();
  7407. } catch (e) {}
  7408. };
  7409.  
  7410. /**
  7411. * Update inventory
  7412. *
  7413. * Обновляет инвентарь
  7414. */
  7415. this.refreshInventory = async function () {
  7416. const GM_INST = getFnP(Game.GameModel, 'get_instance');
  7417. const GM_0 = getProtoFn(Game.GameModel, 0);
  7418. const P_24 = getProtoFn(selfGame['game.model.user.Player'], 24);
  7419. const Player = Game.GameModel[GM_INST]()[GM_0];
  7420. Player[P_24] = new selfGame['game.model.user.inventory.PlayerInventory']();
  7421. Player[P_24].init(await Send({ calls: [{ name: 'inventoryGet', args: {}, ident: 'body' }] }).then((e) => e.results[0].result.response));
  7422. };
  7423. this.updateInventory = function (reward) {
  7424. const GM_INST = getFnP(Game.GameModel, 'get_instance');
  7425. const GM_0 = getProtoFn(Game.GameModel, 0);
  7426. const P_24 = getProtoFn(selfGame['game.model.user.Player'], 24);
  7427. const Player = Game.GameModel[GM_INST]()[GM_0];
  7428. Player[P_24].init(reward);
  7429. };
  7430.  
  7431. this.updateMap = function (data) {
  7432. const PCDD_21 = getProtoFn(selfGame['game.mechanics.clanDomination.model.PlayerClanDominationData'], 21);
  7433. const P_60 = getProtoFn(selfGame['game.model.user.Player'], 60);
  7434. const GM_0 = getProtoFn(Game.GameModel, 0);
  7435. const getInstance = getFnP(selfGame['Game'], 'get_instance');
  7436. const PlayerClanDominationData = Game.GameModel[getInstance]()[GM_0];
  7437. PlayerClanDominationData[P_60][PCDD_21].update(data);
  7438. };
  7439.  
  7440. /**
  7441. * Change the play screen on windowName
  7442. *
  7443. * Сменить экран игры на windowName
  7444. *
  7445. * Possible options:
  7446. *
  7447. * Возможные варианты:
  7448. *
  7449. * 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
  7450. */
  7451. this.goNavigtor = function (windowName) {
  7452. let mechanicStorage = selfGame['game.data.storage.mechanic.MechanicStorage'];
  7453. let window = mechanicStorage[windowName];
  7454. let event = new selfGame['game.mediator.gui.popup.PopupStashEventParams']();
  7455. let Game = selfGame['Game'];
  7456. let navigator = getF(Game, 'get_navigator');
  7457. let navigate = getProtoFn(selfGame['game.screen.navigator.GameNavigator'], 20);
  7458. let instance = getFnP(Game, 'get_instance');
  7459. Game[instance]()[navigator]()[navigate](window, event);
  7460. };
  7461.  
  7462. /**
  7463. * Move to the sanctuary cheats.goSanctuary()
  7464. *
  7465. * Переместиться в святилище cheats.goSanctuary()
  7466. */
  7467. this.goSanctuary = () => {
  7468. this.goNavigtor('SANCTUARY');
  7469. };
  7470.  
  7471. /** Перейти в Долину титанов */
  7472. this.goTitanValley = () => {
  7473. this.goNavigtor('TITAN_VALLEY');
  7474. };
  7475.  
  7476. /**
  7477. * Go to Guild War
  7478. *
  7479. * Перейти к Войне Гильдий
  7480. */
  7481. this.goClanWar = function () {
  7482. let instance = getFnP(Game.GameModel, 'get_instance');
  7483. let player = Game.GameModel[instance]().A;
  7484. let clanWarSelect = selfGame['game.mechanics.cross_clan_war.popup.selectMode.CrossClanWarSelectModeMediator'];
  7485. new clanWarSelect(player).open();
  7486. };
  7487.  
  7488. /** Перейти к Острову гильдии */
  7489. this.goClanIsland = function () {
  7490. let instance = getFnP(Game.GameModel, 'get_instance');
  7491. let player = Game.GameModel[instance]().A;
  7492. let clanIslandSelect = selfGame['game.view.gui.ClanIslandPopupMediator'];
  7493. new clanIslandSelect(player).open();
  7494. };
  7495.  
  7496. /**
  7497. * Go to BrawlShop
  7498. *
  7499. * Переместиться в BrawlShop
  7500. */
  7501. this.goBrawlShop = () => {
  7502. const instance = getFnP(Game.GameModel, 'get_instance');
  7503. const P_36 = getProtoFn(selfGame['game.model.user.Player'], 36);
  7504. const PSD_0 = getProtoFn(selfGame['game.model.user.shop.PlayerShopData'], 0);
  7505. const IM_0 = getProtoFn(selfGame['haxe.ds.IntMap'], 0);
  7506. const PSDE_4 = getProtoFn(selfGame['game.model.user.shop.PlayerShopDataEntry'], 4);
  7507.  
  7508. const player = Game.GameModel[instance]().A;
  7509. const shop = player[P_36][PSD_0][IM_0][1038][PSDE_4];
  7510. const shopPopup = new selfGame['game.mechanics.brawl.mediator.BrawlShopPopupMediator'](player, shop);
  7511. shopPopup.open(new selfGame['game.mediator.gui.popup.PopupStashEventParams']());
  7512. };
  7513.  
  7514. /**
  7515. * Returns all stores from game data
  7516. *
  7517. * Возвращает все магазины из данных игры
  7518. */
  7519. this.getShops = () => {
  7520. const instance = getFnP(Game.GameModel, 'get_instance');
  7521. const P_36 = getProtoFn(selfGame['game.model.user.Player'], 36);
  7522. const PSD_0 = getProtoFn(selfGame['game.model.user.shop.PlayerShopData'], 0);
  7523. const IM_0 = getProtoFn(selfGame['haxe.ds.IntMap'], 0);
  7524.  
  7525. const player = Game.GameModel[instance]().A;
  7526. return player[P_36][PSD_0][IM_0];
  7527. };
  7528.  
  7529. /**
  7530. * Returns the store from the game data by ID
  7531. *
  7532. * Возвращает магазин из данных игры по идетификатору
  7533. */
  7534. this.getShop = (id) => {
  7535. const PSDE_4 = getProtoFn(selfGame['game.model.user.shop.PlayerShopDataEntry'], 4);
  7536. const shops = this.getShops();
  7537. const shop = shops[id]?.[PSDE_4];
  7538. return shop;
  7539. };
  7540.  
  7541. /**
  7542. * Change island map
  7543. *
  7544. * Сменить карту острова
  7545. */
  7546. this.changeIslandMap = (mapId = 2) => {
  7547. const GameInst = getFnP(selfGame['Game'], 'get_instance');
  7548. const GM_0 = getProtoFn(Game.GameModel, 0);
  7549. const P_59 = getProtoFn(selfGame['game.model.user.Player'], 60);
  7550. const PSAD_31 = getProtoFn(selfGame['game.mechanics.season_adventure.model.PlayerSeasonAdventureData'], 31);
  7551. const Player = Game.GameModel[GameInst]()[GM_0];
  7552. Player[P_59][PSAD_31]({ id: mapId, seasonAdventure: { id: mapId, startDate: 1701914400, endDate: 1709690400, closed: false } });
  7553.  
  7554. const GN_15 = getProtoFn(selfGame['game.screen.navigator.GameNavigator'], 17);
  7555. const navigator = getF(selfGame['Game'], 'get_navigator');
  7556. selfGame['Game'][GameInst]()[navigator]()[GN_15](new selfGame['game.mediator.gui.popup.PopupStashEventParams']());
  7557. };
  7558.  
  7559. /**
  7560. * Game library availability tracker
  7561. *
  7562. * Отслеживание доступности игровой библиотеки
  7563. */
  7564. function checkLibLoad() {
  7565. timeout = setTimeout(() => {
  7566. if (Game.GameModel) {
  7567. changeLib();
  7568. } else {
  7569. checkLibLoad();
  7570. }
  7571. }, 100);
  7572. }
  7573.  
  7574. /**
  7575. * Game library data spoofing
  7576. *
  7577. * Подмена данных игровой библиотеки
  7578. */
  7579. function changeLib() {
  7580. console.log('lib connect');
  7581. const originalStartFunc = Game.GameModel.prototype.start;
  7582. Game.GameModel.prototype.start = function (a, b, c) {
  7583. self.libGame = b.raw;
  7584. self.doneLibLoad(self.libGame);
  7585. try {
  7586. const levels = b.raw.seasonAdventure.level;
  7587. for (const id in levels) {
  7588. const level = levels[id];
  7589. level.clientData.graphics.fogged = level.clientData.graphics.visible;
  7590. }
  7591. const adv = b.raw.seasonAdventure.list[1];
  7592. adv.clientData.asset = 'dialog_season_adventure_tiles';
  7593. } catch (e) {
  7594. console.warn(e);
  7595. }
  7596. originalStartFunc.call(this, a, b, c);
  7597. };
  7598. }
  7599.  
  7600. this.LibLoad = function () {
  7601. return new Promise((e) => {
  7602. this.doneLibLoad = e;
  7603. });
  7604. };
  7605.  
  7606. /**
  7607. * Returns the value of a language constant
  7608. *
  7609. * Возвращает значение языковой константы
  7610. * @param {*} langConst language constant // языковая константа
  7611. * @returns
  7612. */
  7613. this.translate = function (langConst) {
  7614. return Game.Translate.translate(langConst);
  7615. };
  7616.  
  7617. connectGame();
  7618. checkLibLoad();
  7619. }
  7620.  
  7621. /**
  7622. * Auto collection of gifts
  7623. *
  7624. * Автосбор подарков
  7625. */
  7626. function getAutoGifts() {
  7627. // c3ltYm9scyB0aGF0IG1lYW4gbm90aGluZw==
  7628. let valName = 'giftSendIds_' + userInfo.id;
  7629.  
  7630. if (!localStorage['clearGift' + userInfo.id]) {
  7631. localStorage[valName] = '';
  7632. localStorage['clearGift' + userInfo.id] = '+';
  7633. }
  7634.  
  7635. if (!localStorage[valName]) {
  7636. localStorage[valName] = '';
  7637. }
  7638.  
  7639. const giftsAPI = new ZingerYWebsiteAPI('getGifts.php', arguments);
  7640. /**
  7641. * Submit a request to receive gift codes
  7642. *
  7643. * Отправка запроса для получения кодов подарков
  7644. */
  7645. giftsAPI.request().then((data) => {
  7646. let freebieCheckCalls = {
  7647. calls: [],
  7648. };
  7649. data.forEach((giftId, n) => {
  7650. if (localStorage[valName].includes(giftId)) return;
  7651. freebieCheckCalls.calls.push({
  7652. name: 'registration',
  7653. args: {
  7654. user: { referrer: {} },
  7655. giftId,
  7656. },
  7657. context: {
  7658. actionTs: Math.floor(performance.now()),
  7659. cookie: window?.NXAppInfo?.session_id || null,
  7660. },
  7661. ident: giftId,
  7662. });
  7663. });
  7664.  
  7665. if (!freebieCheckCalls.calls.length) {
  7666. return;
  7667. }
  7668.  
  7669. send(JSON.stringify(freebieCheckCalls), (e) => {
  7670. let countGetGifts = 0;
  7671. const gifts = [];
  7672. for (check of e.results) {
  7673. gifts.push(check.ident);
  7674. if (check.result.response != null) {
  7675. countGetGifts++;
  7676. }
  7677. }
  7678. const saveGifts = localStorage[valName].split(';');
  7679. localStorage[valName] = [...saveGifts, ...gifts].slice(-50).join(';');
  7680. console.log(`${I18N('GIFTS')}: ${countGetGifts}`);
  7681. });
  7682. });
  7683. }
  7684.  
  7685. /**
  7686. * To fill the kills in the Forge of Souls
  7687. *
  7688. * Набить килов в горниле душ
  7689. */
  7690. async function bossRatingEvent() {
  7691. const topGet = await Send(JSON.stringify({ calls: [{ name: "topGet", args: { type: "bossRatingTop", extraId: 0 }, ident: "body" }] }));
  7692. if (!topGet || !topGet.results[0].result.response[0]) {
  7693. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  7694. return;
  7695. }
  7696. const replayId = topGet.results[0].result.response[0].userData.replayId;
  7697. const result = await Send(JSON.stringify({
  7698. calls: [
  7699. { name: "battleGetReplay", args: { id: replayId }, ident: "battleGetReplay" },
  7700. { name: "heroGetAll", args: {}, ident: "heroGetAll" },
  7701. { name: "pet_getAll", args: {}, ident: "pet_getAll" },
  7702. { name: "offerGetAll", args: {}, ident: "offerGetAll" }
  7703. ]
  7704. }));
  7705. const bossEventInfo = result.results[3].result.response.find(e => e.offerType == "bossEvent");
  7706. if (!bossEventInfo) {
  7707. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  7708. return;
  7709. }
  7710. const usedHeroes = bossEventInfo.progress.usedHeroes;
  7711. const party = Object.values(result.results[0].result.response.replay.attackers);
  7712. const availableHeroes = Object.values(result.results[1].result.response).map(e => e.id);
  7713. const availablePets = Object.values(result.results[2].result.response).map(e => e.id);
  7714. const calls = [];
  7715. /**
  7716. * First pack
  7717. *
  7718. * Первая пачка
  7719. */
  7720. const args = {
  7721. heroes: [],
  7722. favor: {}
  7723. }
  7724. for (let hero of party) {
  7725. if (hero.id >= 6000 && availablePets.includes(hero.id)) {
  7726. args.pet = hero.id;
  7727. continue;
  7728. }
  7729. if (!availableHeroes.includes(hero.id) || usedHeroes.includes(hero.id)) {
  7730. continue;
  7731. }
  7732. args.heroes.push(hero.id);
  7733. if (hero.favorPetId) {
  7734. args.favor[hero.id] = hero.favorPetId;
  7735. }
  7736. }
  7737. if (args.heroes.length) {
  7738. calls.push({
  7739. name: "bossRatingEvent_startBattle",
  7740. args,
  7741. ident: "body_0"
  7742. });
  7743. }
  7744. /**
  7745. * Other packs
  7746. *
  7747. * Другие пачки
  7748. */
  7749. let heroes = [];
  7750. let count = 1;
  7751. while (heroId = availableHeroes.pop()) {
  7752. if (args.heroes.includes(heroId) || usedHeroes.includes(heroId)) {
  7753. continue;
  7754. }
  7755. heroes.push(heroId);
  7756. if (heroes.length == 5) {
  7757. calls.push({
  7758. name: "bossRatingEvent_startBattle",
  7759. args: {
  7760. heroes: [...heroes],
  7761. pet: availablePets[Math.floor(Math.random() * availablePets.length)]
  7762. },
  7763. ident: "body_" + count
  7764. });
  7765. heroes = [];
  7766. count++;
  7767. }
  7768. }
  7769.  
  7770. if (!calls.length) {
  7771. setProgress(`${I18N('NO_HEROES')}`, true);
  7772. return;
  7773. }
  7774.  
  7775. const resultBattles = await Send(JSON.stringify({ calls }));
  7776. console.log(resultBattles);
  7777. rewardBossRatingEvent();
  7778. }
  7779.  
  7780. /**
  7781. * Collecting Rewards from the Forge of Souls
  7782. *
  7783. * Сбор награды из Горнила Душ
  7784. */
  7785. function rewardBossRatingEvent() {
  7786. let rewardBossRatingCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  7787. send(rewardBossRatingCall, function (data) {
  7788. let bossEventInfo = data.results[0].result.response.find(e => e.offerType == "bossEvent");
  7789. if (!bossEventInfo) {
  7790. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  7791. return;
  7792. }
  7793.  
  7794. let farmedChests = bossEventInfo.progress.farmedChests;
  7795. let score = bossEventInfo.progress.score;
  7796. setProgress(`${I18N('DAMAGE_AMOUNT')}: ${score}`);
  7797. let revard = bossEventInfo.reward;
  7798.  
  7799. let getRewardCall = {
  7800. calls: []
  7801. }
  7802.  
  7803. let count = 0;
  7804. for (let i = 1; i < 10; i++) {
  7805. if (farmedChests.includes(i)) {
  7806. continue;
  7807. }
  7808. if (score < revard[i].score) {
  7809. break;
  7810. }
  7811. getRewardCall.calls.push({
  7812. name: "bossRatingEvent_getReward",
  7813. args: {
  7814. rewardId: i
  7815. },
  7816. ident: "body_" + i
  7817. });
  7818. count++;
  7819. }
  7820. if (!count) {
  7821. setProgress(`${I18N('NOTHING_TO_COLLECT')}`, true);
  7822. return;
  7823. }
  7824.  
  7825. send(JSON.stringify(getRewardCall), e => {
  7826. console.log(e);
  7827. setProgress(`${I18N('COLLECTED')} ${e?.results?.length} ${I18N('REWARD')}`, true);
  7828. });
  7829. });
  7830. }
  7831.  
  7832. /**
  7833. * Collect Easter eggs and event rewards
  7834. *
  7835. * Собрать пасхалки и награды событий
  7836. */
  7837. function offerFarmAllReward() {
  7838. const offerGetAllCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  7839. return Send(offerGetAllCall).then((data) => {
  7840. const offerGetAll = data.results[0].result.response.filter(e => e.type == "reward" && !e?.freeRewardObtained && e.reward);
  7841. if (!offerGetAll.length) {
  7842. setProgress(`${I18N('NOTHING_TO_COLLECT')}`, true);
  7843. return;
  7844. }
  7845.  
  7846. const calls = [];
  7847. for (let reward of offerGetAll) {
  7848. calls.push({
  7849. name: "offerFarmReward",
  7850. args: {
  7851. offerId: reward.id
  7852. },
  7853. ident: "offerFarmReward_" + reward.id
  7854. });
  7855. }
  7856.  
  7857. return Send(JSON.stringify({ calls })).then(e => {
  7858. console.log(e);
  7859. setProgress(`${I18N('COLLECTED')} ${e?.results?.length} ${I18N('REWARD')}`, true);
  7860. });
  7861. });
  7862. }
  7863.  
  7864. /**
  7865. * Assemble Outland
  7866. *
  7867. * Собрать запределье
  7868. */
  7869. function getOutland() {
  7870. return new Promise(function (resolve, reject) {
  7871. send('{"calls":[{"name":"bossGetAll","args":{},"ident":"bossGetAll"}]}', e => {
  7872. let bosses = e.results[0].result.response;
  7873.  
  7874. let bossRaidOpenChestCall = {
  7875. calls: []
  7876. };
  7877.  
  7878. for (let boss of bosses) {
  7879. if (boss.mayRaid) {
  7880. bossRaidOpenChestCall.calls.push({
  7881. name: "bossRaid",
  7882. args: {
  7883. bossId: boss.id
  7884. },
  7885. ident: "bossRaid_" + boss.id
  7886. });
  7887. bossRaidOpenChestCall.calls.push({
  7888. name: "bossOpenChest",
  7889. args: {
  7890. bossId: boss.id,
  7891. amount: 1,
  7892. starmoney: 0
  7893. },
  7894. ident: "bossOpenChest_" + boss.id
  7895. });
  7896. } else if (boss.chestId == 1) {
  7897. bossRaidOpenChestCall.calls.push({
  7898. name: "bossOpenChest",
  7899. args: {
  7900. bossId: boss.id,
  7901. amount: 1,
  7902. starmoney: 0
  7903. },
  7904. ident: "bossOpenChest_" + boss.id
  7905. });
  7906. }
  7907. }
  7908.  
  7909. if (!bossRaidOpenChestCall.calls.length) {
  7910. setProgress(`${I18N('OUTLAND')} ${I18N('NOTHING_TO_COLLECT')}`, true);
  7911. resolve();
  7912. return;
  7913. }
  7914.  
  7915. send(JSON.stringify(bossRaidOpenChestCall), e => {
  7916. setProgress(`${I18N('OUTLAND')} ${I18N('COLLECTED')}`, true);
  7917. resolve();
  7918. });
  7919. });
  7920. });
  7921. }
  7922.  
  7923. /**
  7924. * Collect all rewards
  7925. *
  7926. * Собрать все награды
  7927. */
  7928. function questAllFarm() {
  7929. return new Promise(function (resolve, reject) {
  7930. let questGetAllCall = {
  7931. calls: [{
  7932. name: "questGetAll",
  7933. args: {},
  7934. ident: "body"
  7935. }]
  7936. }
  7937. send(JSON.stringify(questGetAllCall), function (data) {
  7938. let questGetAll = data.results[0].result.response;
  7939. const questAllFarmCall = {
  7940. calls: []
  7941. }
  7942. let number = 0;
  7943. for (let quest of questGetAll) {
  7944. if (quest.id < 1e6 && quest.state == 2) {
  7945. questAllFarmCall.calls.push({
  7946. name: "questFarm",
  7947. args: {
  7948. questId: quest.id
  7949. },
  7950. ident: `group_${number}_body`
  7951. });
  7952. number++;
  7953. }
  7954. }
  7955.  
  7956. if (!questAllFarmCall.calls.length) {
  7957. setProgress(`${I18N('COLLECTED')} ${number} ${I18N('REWARD')}`, true);
  7958. resolve();
  7959. return;
  7960. }
  7961.  
  7962. send(JSON.stringify(questAllFarmCall), function (res) {
  7963. console.log(res);
  7964. setProgress(`${I18N('COLLECTED')} ${number} ${I18N('REWARD')}`, true);
  7965. resolve();
  7966. });
  7967. });
  7968. })
  7969. }
  7970.  
  7971. /**
  7972. * Mission auto repeat
  7973. *
  7974. * Автоповтор миссии
  7975. * isStopSendMission = false;
  7976. * isSendsMission = true;
  7977. **/
  7978. this.sendsMission = async function (param) {
  7979. if (isStopSendMission) {
  7980. isSendsMission = false;
  7981. console.log(I18N('STOPPED'));
  7982. setProgress('');
  7983. await popup.confirm(`${I18N('STOPPED')}<br>${I18N('REPETITIONS')}: ${param.count}`, [{
  7984. msg: 'Ok',
  7985. result: true
  7986. }, ])
  7987. return;
  7988. }
  7989. lastMissionBattleStart = Date.now();
  7990. let missionStartCall = {
  7991. "calls": [{
  7992. "name": "missionStart",
  7993. "args": lastMissionStart,
  7994. "ident": "body"
  7995. }]
  7996. }
  7997. /**
  7998. * Mission Request
  7999. *
  8000. * Запрос на выполнение мисии
  8001. */
  8002. SendRequest(JSON.stringify(missionStartCall), async e => {
  8003. if (e['error']) {
  8004. isSendsMission = false;
  8005. console.log(e['error']);
  8006. setProgress('');
  8007. let msg = e['error'].name + ' ' + e['error'].description + `<br>${I18N('REPETITIONS')}: ${param.count}`;
  8008. await popup.confirm(msg, [
  8009. {msg: 'Ok', result: true},
  8010. ])
  8011. return;
  8012. }
  8013. /**
  8014. * Mission data calculation
  8015. *
  8016. * Расчет данных мисии
  8017. */
  8018. BattleCalc(e.results[0].result.response, 'get_tower', async r => {
  8019. /** missionTimer */
  8020. let timer = getTimer(r.battleTime) + 5;
  8021. const period = Math.ceil((Date.now() - lastMissionBattleStart) / 1000);
  8022. if (period < timer) {
  8023. timer = timer - period;
  8024. await countdownTimer(timer, `${I18N('MISSIONS_PASSED')}: ${param.count}`);
  8025. }
  8026.  
  8027. let missionEndCall = {
  8028. "calls": [{
  8029. "name": "missionEnd",
  8030. "args": {
  8031. "id": param.id,
  8032. "result": r.result,
  8033. "progress": r.progress
  8034. },
  8035. "ident": "body"
  8036. }]
  8037. }
  8038. /**
  8039. * Mission Completion Request
  8040. *
  8041. * Запрос на завершение миссии
  8042. */
  8043. SendRequest(JSON.stringify(missionEndCall), async (e) => {
  8044. if (e['error']) {
  8045. isSendsMission = false;
  8046. console.log(e['error']);
  8047. setProgress('');
  8048. let msg = e['error'].name + ' ' + e['error'].description + `<br>${I18N('REPETITIONS')}: ${param.count}`;
  8049. await popup.confirm(msg, [
  8050. {msg: 'Ok', result: true},
  8051. ])
  8052. return;
  8053. }
  8054. r = e.results[0].result.response;
  8055. if (r['error']) {
  8056. isSendsMission = false;
  8057. console.log(r['error']);
  8058. setProgress('');
  8059. await popup.confirm(`<br>${I18N('REPETITIONS')}: ${param.count}` + ' 3 ' + r['error'], [
  8060. {msg: 'Ok', result: true},
  8061. ])
  8062. return;
  8063. }
  8064.  
  8065. param.count++;
  8066. setProgress(`${I18N('MISSIONS_PASSED')}: ${param.count} (${I18N('STOP')})`, false, () => {
  8067. isStopSendMission = true;
  8068. });
  8069. setTimeout(sendsMission, 1, param);
  8070. });
  8071. })
  8072. });
  8073. }
  8074.  
  8075. /**
  8076. * Opening of russian dolls
  8077. *
  8078. * Открытие матрешек
  8079. */
  8080. async function openRussianDolls(libId, amount) {
  8081. let sum = 0;
  8082. const sumResult = {};
  8083. let count = 0;
  8084.  
  8085. while (amount) {
  8086. sum += amount;
  8087. setProgress(`${I18N('TOTAL_OPEN')} ${sum}`);
  8088. const calls = [
  8089. {
  8090. name: 'consumableUseLootBox',
  8091. args: { libId, amount },
  8092. ident: 'body',
  8093. },
  8094. ];
  8095. const response = await Send(JSON.stringify({ calls })).then((e) => e.results[0].result.response);
  8096. let [countLootBox, result] = Object.entries(response).pop();
  8097. count += +countLootBox;
  8098. let newCount = 0;
  8099.  
  8100. if (result?.consumable && result.consumable[libId]) {
  8101. newCount = result.consumable[libId];
  8102. delete result.consumable[libId];
  8103. }
  8104.  
  8105. mergeItemsObj(sumResult, result);
  8106. amount = newCount;
  8107. }
  8108.  
  8109. setProgress(`${I18N('TOTAL_OPEN')} ${sum}`, 5000);
  8110. return [count, sumResult];
  8111. }
  8112.  
  8113. function mergeItemsObj(obj1, obj2) {
  8114. for (const key in obj2) {
  8115. if (obj1[key]) {
  8116. if (typeof obj1[key] == 'object') {
  8117. for (const innerKey in obj2[key]) {
  8118. obj1[key][innerKey] = (obj1[key][innerKey] || 0) + obj2[key][innerKey];
  8119. }
  8120. } else {
  8121. obj1[key] += obj2[key] || 0;
  8122. }
  8123. } else {
  8124. obj1[key] = obj2[key];
  8125. }
  8126. }
  8127.  
  8128. return obj1;
  8129. }
  8130.  
  8131. /**
  8132. * Collect all mail, except letters with energy and charges of the portal
  8133. *
  8134. * Собрать всю почту, кроме писем с энергией и зарядами портала
  8135. */
  8136. function mailGetAll() {
  8137. const getMailInfo = '{"calls":[{"name":"mailGetAll","args":{},"ident":"body"}]}';
  8138.  
  8139. return Send(getMailInfo).then(dataMail => {
  8140. const letters = dataMail.results[0].result.response.letters;
  8141. const letterIds = lettersFilter(letters);
  8142. if (!letterIds.length) {
  8143. setProgress(I18N('NOTHING_TO_COLLECT'), true);
  8144. return;
  8145. }
  8146.  
  8147. const calls = [
  8148. { name: "mailFarm", args: { letterIds }, ident: "body" }
  8149. ];
  8150.  
  8151. return Send(JSON.stringify({ calls })).then(res => {
  8152. const lettersIds = res.results[0].result.response;
  8153. if (lettersIds) {
  8154. const countLetters = Object.keys(lettersIds).length;
  8155. setProgress(`${I18N('RECEIVED')} ${countLetters} ${I18N('LETTERS')}`, true);
  8156. }
  8157. });
  8158. });
  8159. }
  8160.  
  8161. /**
  8162. * Filters received emails
  8163. *
  8164. * Фильтрует получаемые письма
  8165. */
  8166. function lettersFilter(letters) {
  8167. const lettersIds = [];
  8168. for (let l in letters) {
  8169. letter = letters[l];
  8170. const reward = letter?.reward;
  8171. if (!reward || !Object.keys(reward).length) {
  8172. continue;
  8173. }
  8174. /**
  8175. * Mail Collection Exceptions
  8176. *
  8177. * Исключения на сбор писем
  8178. */
  8179. const isFarmLetter = !(
  8180. /** Portals // сферы портала */
  8181. (reward?.refillable ? reward.refillable[45] : false) ||
  8182. /** Energy // энергия */
  8183. (reward?.stamina ? reward.stamina : false) ||
  8184. /** accelerating energy gain // ускорение набора энергии */
  8185. (reward?.buff ? true : false) ||
  8186. /** VIP Points // вип очки */
  8187. (reward?.vipPoints ? reward.vipPoints : false) ||
  8188. /** souls of heroes // душы героев */
  8189. (reward?.fragmentHero ? true : false) ||
  8190. /** heroes // герои */
  8191. (reward?.bundleHeroReward ? true : false)
  8192. );
  8193. if (isFarmLetter) {
  8194. lettersIds.push(~~letter.id);
  8195. continue;
  8196. }
  8197. /**
  8198. * Если до окончания годности письма менее 24 часов,
  8199. * то оно собирается не смотря на исключения
  8200. */
  8201. const availableUntil = +letter?.availableUntil;
  8202. if (availableUntil) {
  8203. const maxTimeLeft = 24 * 60 * 60 * 1000;
  8204. const timeLeft = (new Date(availableUntil * 1000) - new Date())
  8205. console.log('Time left:', timeLeft)
  8206. if (timeLeft < maxTimeLeft) {
  8207. lettersIds.push(~~letter.id);
  8208. continue;
  8209. }
  8210. }
  8211. }
  8212. return lettersIds;
  8213. }
  8214.  
  8215. /**
  8216. * Displaying information about the areas of the portal and attempts on the VG
  8217. *
  8218. * Отображение информации о сферах портала и попытках на ВГ
  8219. */
  8220. async function justInfo() {
  8221. return new Promise(async (resolve, reject) => {
  8222. const calls = [{
  8223. name: "userGetInfo",
  8224. args: {},
  8225. ident: "userGetInfo"
  8226. },
  8227. {
  8228. name: "clanWarGetInfo",
  8229. args: {},
  8230. ident: "clanWarGetInfo"
  8231. },
  8232. {
  8233. name: "titanArenaGetStatus",
  8234. args: {},
  8235. ident: "titanArenaGetStatus"
  8236. }];
  8237. const result = await Send(JSON.stringify({ calls }));
  8238. const infos = result.results;
  8239. const portalSphere = infos[0].result.response.refillable.find(n => n.id == 45);
  8240. const clanWarMyTries = infos[1].result.response?.myTries ?? 0;
  8241. const arePointsMax = infos[1].result.response?.arePointsMax;
  8242. const titansLevel = +(infos[2].result.response?.tier ?? 0);
  8243. const titansStatus = infos[2].result.response?.status; //peace_time || battle
  8244.  
  8245. const sanctuaryButton = buttons['testAdventure'].button;
  8246. const clanWarButton = buttons['goToClanWar'].button;
  8247. const titansArenaButton = buttons['testTitanArena'].button;
  8248. const shadow = ' 0px 0px 3px 2px';
  8249.  
  8250. if (portalSphere.amount) {
  8251. sanctuaryButton.style.boxShadow = (portalSphere.amount >= 3 ? 'red' : 'brown') + shadow;
  8252. sanctuaryButton.title = `${I18N('SANCTUARY_TITLE')}\n${portalSphere.amount} ${I18N('PORTALS')}`;
  8253. } else {
  8254. sanctuaryButton.style.boxShadow = '';
  8255. sanctuaryButton.title = I18N('SANCTUARY_TITLE');
  8256. }
  8257. if (clanWarMyTries && !arePointsMax) {
  8258. clanWarButton.style.filter = 'drop-shadow(red 0px 0px 2px)';
  8259. clanWarButton.title = `${I18N('GUILD_WAR_TITLE')}\n${clanWarMyTries}${I18N('ATTEMPTS')}`;
  8260. } else {
  8261. clanWarButton.style.filter = '';
  8262. clanWarButton.title = I18N('GUILD_WAR_TITLE');
  8263. }
  8264.  
  8265. if (titansLevel < 7 && titansStatus == 'battle') { ;
  8266. const partColor = Math.floor(125 * titansLevel / 7);
  8267. titansArenaButton.style.boxShadow = `rgb(255,${partColor},${partColor})` + shadow;
  8268. titansArenaButton.title = `${I18N('TITAN_ARENA_TITLE')}\n${titansLevel} ${I18N('LEVEL')}`;
  8269. } else {
  8270. titansArenaButton.style.boxShadow = '';
  8271. titansArenaButton.title = I18N('TITAN_ARENA_TITLE');
  8272. }
  8273.  
  8274. const imgPortal =
  8275. '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';
  8276.  
  8277. setProgress('<img src="' + imgPortal + '" style="height: 25px;position: relative;top: 5px;"> ' + `${portalSphere.amount} </br> ${I18N('GUILD_WAR')}: ${clanWarMyTries}`, true);
  8278. resolve();
  8279. });
  8280. }
  8281.  
  8282. async function getDailyBonus() {
  8283. const dailyBonusInfo = await Send(JSON.stringify({
  8284. calls: [{
  8285. name: "dailyBonusGetInfo",
  8286. args: {},
  8287. ident: "body"
  8288. }]
  8289. })).then(e => e.results[0].result.response);
  8290. const { availableToday, availableVip, currentDay } = dailyBonusInfo;
  8291.  
  8292. if (!availableToday) {
  8293. console.log('Уже собрано');
  8294. return;
  8295. }
  8296.  
  8297. const currentVipPoints = +userInfo.vipPoints;
  8298. const dailyBonusStat = lib.getData('dailyBonusStatic');
  8299. const vipInfo = lib.getData('level').vip;
  8300. let currentVipLevel = 0;
  8301. for (let i in vipInfo) {
  8302. vipLvl = vipInfo[i];
  8303. if (currentVipPoints >= vipLvl.vipPoints) {
  8304. currentVipLevel = vipLvl.level;
  8305. }
  8306. }
  8307. const vipLevelDouble = dailyBonusStat[`${currentDay}_0_0`].vipLevelDouble;
  8308.  
  8309. const calls = [{
  8310. name: "dailyBonusFarm",
  8311. args: {
  8312. vip: availableVip && currentVipLevel >= vipLevelDouble ? 1 : 0
  8313. },
  8314. ident: "body"
  8315. }];
  8316.  
  8317. const result = await Send(JSON.stringify({ calls }));
  8318. if (result.error) {
  8319. console.error(result.error);
  8320. return;
  8321. }
  8322.  
  8323. const reward = result.results[0].result.response;
  8324. const type = Object.keys(reward).pop();
  8325. const itemId = Object.keys(reward[type]).pop();
  8326. const count = reward[type][itemId];
  8327. const itemName = cheats.translate(`LIB_${type.toUpperCase()}_NAME_${itemId}`);
  8328.  
  8329. console.log(`Ежедневная награда: Получено ${count} ${itemName}`, reward);
  8330. }
  8331.  
  8332. async function farmStamina(lootBoxId = 148) {
  8333. const lootBox = await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"}]}')
  8334. .then(e => e.results[0].result.response.consumable[148]);
  8335.  
  8336. /** Добавить другие ящики */
  8337. /**
  8338. * 144 - медная шкатулка
  8339. * 145 - бронзовая шкатулка
  8340. * 148 - платиновая шкатулка
  8341. */
  8342. if (!lootBox) {
  8343. setProgress(I18N('NO_BOXES'), true);
  8344. return;
  8345. }
  8346.  
  8347. let maxFarmEnergy = getSaveVal('maxFarmEnergy', 100);
  8348. const result = await popup.confirm(I18N('OPEN_LOOTBOX', { lootBox }), [
  8349. { result: false, isClose: true },
  8350. { msg: I18N('BTN_YES'), result: true },
  8351. { msg: I18N('STAMINA'), isInput: true, default: maxFarmEnergy },
  8352. ]);
  8353. if (!+result) {
  8354. return;
  8355. }
  8356.  
  8357. if ((typeof result) !== 'boolean' && Number.parseInt(result)) {
  8358. maxFarmEnergy = +result;
  8359. setSaveVal('maxFarmEnergy', maxFarmEnergy);
  8360. } else {
  8361. maxFarmEnergy = 0;
  8362. }
  8363.  
  8364. let collectEnergy = 0;
  8365. for (let count = lootBox; count > 0; count--) {
  8366. const response = await Send('{"calls":[{"name":"consumableUseLootBox","args":{"libId":148,"amount":1},"ident":"body"}]}').then(
  8367. (e) => e.results[0].result.response
  8368. );
  8369. const result = Object.values(response).pop();
  8370. if ('stamina' in result) {
  8371. setProgress(`${I18N('OPEN')}: ${lootBox - count}/${lootBox} ${I18N('STAMINA')} +${result.stamina}<br>${I18N('STAMINA')}: ${collectEnergy}`, false);
  8372. console.log(`${ I18N('STAMINA') } + ${ result.stamina }`);
  8373. if (!maxFarmEnergy) {
  8374. return;
  8375. }
  8376. collectEnergy += +result.stamina;
  8377. if (collectEnergy >= maxFarmEnergy) {
  8378. console.log(`${I18N('STAMINA')} + ${ collectEnergy }`);
  8379. setProgress(`${I18N('STAMINA')} + ${ collectEnergy }`, false);
  8380. return;
  8381. }
  8382. } else {
  8383. setProgress(`${I18N('OPEN')}: ${lootBox - count}/${lootBox}<br>${I18N('STAMINA')}: ${collectEnergy}`, false);
  8384. console.log(result);
  8385. }
  8386. }
  8387.  
  8388. setProgress(I18N('BOXES_OVER'), true);
  8389. }
  8390.  
  8391. async function fillActive() {
  8392. const data = await Send(JSON.stringify({
  8393. calls: [{
  8394. name: "questGetAll",
  8395. args: {},
  8396. ident: "questGetAll"
  8397. }, {
  8398. name: "inventoryGet",
  8399. args: {},
  8400. ident: "inventoryGet"
  8401. }, {
  8402. name: "clanGetInfo",
  8403. args: {},
  8404. ident: "clanGetInfo"
  8405. }
  8406. ]
  8407. })).then(e => e.results.map(n => n.result.response));
  8408.  
  8409. const quests = data[0];
  8410. const inv = data[1];
  8411. const stat = data[2].stat;
  8412. const maxActive = 2000 - stat.todayItemsActivity;
  8413. if (maxActive <= 0) {
  8414. setProgress(I18N('NO_MORE_ACTIVITY'), true);
  8415. return;
  8416. }
  8417. let countGetActive = 0;
  8418. const quest = quests.find(e => e.id > 10046 && e.id < 10051);
  8419. if (quest) {
  8420. countGetActive = 1750 - quest.progress;
  8421. }
  8422. if (countGetActive <= 0) {
  8423. countGetActive = maxActive;
  8424. }
  8425. console.log(countGetActive);
  8426.  
  8427. countGetActive = +(await popup.confirm(I18N('EXCHANGE_ITEMS', { maxActive }), [
  8428. { result: false, isClose: true },
  8429. { msg: I18N('GET_ACTIVITY'), isInput: true, default: countGetActive.toString() },
  8430. ]));
  8431.  
  8432. if (!countGetActive) {
  8433. return;
  8434. }
  8435.  
  8436. if (countGetActive > maxActive) {
  8437. countGetActive = maxActive;
  8438. }
  8439.  
  8440. const items = lib.getData('inventoryItem');
  8441.  
  8442. let itemsInfo = [];
  8443. for (let type of ['gear', 'scroll']) {
  8444. for (let i in inv[type]) {
  8445. const v = items[type][i]?.enchantValue || 0;
  8446. itemsInfo.push({
  8447. id: i,
  8448. count: inv[type][i],
  8449. v,
  8450. type
  8451. })
  8452. }
  8453. const invType = 'fragment' + type.toLowerCase().charAt(0).toUpperCase() + type.slice(1);
  8454. for (let i in inv[invType]) {
  8455. const v = items[type][i]?.fragmentEnchantValue || 0;
  8456. itemsInfo.push({
  8457. id: i,
  8458. count: inv[invType][i],
  8459. v,
  8460. type: invType
  8461. })
  8462. }
  8463. }
  8464. itemsInfo = itemsInfo.filter(e => e.v < 4 && e.count > 200);
  8465. itemsInfo = itemsInfo.sort((a, b) => b.count - a.count);
  8466. console.log(itemsInfo);
  8467. const activeItem = itemsInfo.shift();
  8468. console.log(activeItem);
  8469. const countItem = Math.ceil(countGetActive / activeItem.v);
  8470. if (countItem > activeItem.count) {
  8471. setProgress(I18N('NOT_ENOUGH_ITEMS'), true);
  8472. console.log(activeItem);
  8473. return;
  8474. }
  8475.  
  8476. await Send(JSON.stringify({
  8477. calls: [{
  8478. name: "clanItemsForActivity",
  8479. args: {
  8480. items: {
  8481. [activeItem.type]: {
  8482. [activeItem.id]: countItem
  8483. }
  8484. }
  8485. },
  8486. ident: "body"
  8487. }]
  8488. })).then(e => {
  8489. /** TODO: Вывести потраченые предметы */
  8490. console.log(e);
  8491. setProgress(`${I18N('ACTIVITY_RECEIVED')}: ` + e.results[0].result.response, true);
  8492. });
  8493. }
  8494.  
  8495. async function buyHeroFragments() {
  8496. const result = await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"},{"name":"shopGetAll","args":{},"ident":"shopGetAll"}]}')
  8497. .then(e => e.results.map(n => n.result.response));
  8498. const inv = result[0];
  8499. const shops = Object.values(result[1]).filter(shop => [4, 5, 6, 8, 9, 10, 17].includes(shop.id));
  8500. const calls = [];
  8501.  
  8502. for (let shop of shops) {
  8503. const slots = Object.values(shop.slots);
  8504. for (const slot of slots) {
  8505. /* Уже куплено */
  8506. if (slot.bought) {
  8507. continue;
  8508. }
  8509. /* Не душа героя */
  8510. if (!('fragmentHero' in slot.reward)) {
  8511. continue;
  8512. }
  8513. const coin = Object.keys(slot.cost).pop();
  8514. const coinId = Object.keys(slot.cost[coin]).pop();
  8515. const stock = inv[coin][coinId] || 0;
  8516. /* Не хватает на покупку */
  8517. if (slot.cost[coin][coinId] > stock) {
  8518. continue;
  8519. }
  8520. inv[coin][coinId] -= slot.cost[coin][coinId];
  8521. calls.push({
  8522. name: "shopBuy",
  8523. args: {
  8524. shopId: shop.id,
  8525. slot: slot.id,
  8526. cost: slot.cost,
  8527. reward: slot.reward,
  8528. },
  8529. ident: `shopBuy_${shop.id}_${slot.id}`,
  8530. })
  8531. }
  8532. }
  8533.  
  8534. if (!calls.length) {
  8535. setProgress(I18N('NO_PURCHASABLE_HERO_SOULS'), true);
  8536. return;
  8537. }
  8538.  
  8539. const bought = await Send(JSON.stringify({ calls })).then(e => e.results.map(n => n.result.response));
  8540. if (!bought) {
  8541. console.log('что-то пошло не так')
  8542. return;
  8543. }
  8544.  
  8545. let countHeroSouls = 0;
  8546. for (const buy of bought) {
  8547. countHeroSouls += +Object.values(Object.values(buy).pop()).pop();
  8548. }
  8549. console.log(countHeroSouls, bought, calls);
  8550. setProgress(I18N('PURCHASED_HERO_SOULS', { countHeroSouls }), true);
  8551. }
  8552.  
  8553. /** Открыть платные сундуки в Запределье за 90 */
  8554. async function bossOpenChestPay() {
  8555. const callsNames = ['userGetInfo', 'bossGetAll', 'specialOffer_getAll', 'getTime'];
  8556. const info = await Send({ calls: callsNames.map((name) => ({ name, args: {}, ident: name })) }).then((e) =>
  8557. e.results.map((n) => n.result.response)
  8558. );
  8559.  
  8560. const user = info[0];
  8561. const boses = info[1];
  8562. const offers = info[2];
  8563. const time = info[3];
  8564.  
  8565. const discountOffer = offers.find((e) => e.offerType == 'costReplaceOutlandChest');
  8566.  
  8567. let discount = 1;
  8568. if (discountOffer && discountOffer.endTime > time) {
  8569. discount = 1 - discountOffer.offerData.outlandChest.discountPercent / 100;
  8570. }
  8571.  
  8572. cost9chests = 540 * discount;
  8573. cost18chests = 1740 * discount;
  8574. costFirstChest = 90 * discount;
  8575. costSecondChest = 200 * discount;
  8576.  
  8577. const currentStarMoney = user.starMoney;
  8578. if (currentStarMoney < cost9chests) {
  8579. setProgress('Недостаточно изюма, нужно ' + cost9chests + ' у Вас ' + currentStarMoney, true);
  8580. return;
  8581. }
  8582.  
  8583. const imgEmerald =
  8584. "<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='>";
  8585.  
  8586. if (currentStarMoney < cost9chests) {
  8587. setProgress(I18N('NOT_ENOUGH_EMERALDS_540', { currentStarMoney, imgEmerald }), true);
  8588. return;
  8589. }
  8590.  
  8591. const buttons = [{ result: false, isClose: true }];
  8592.  
  8593. if (currentStarMoney >= cost9chests) {
  8594. buttons.push({
  8595. msg: I18N('BUY_OUTLAND_BTN', { count: 9, countEmerald: cost9chests, imgEmerald }),
  8596. result: [costFirstChest, costFirstChest, 0],
  8597. });
  8598. }
  8599.  
  8600. if (currentStarMoney >= cost18chests) {
  8601. buttons.push({
  8602. msg: I18N('BUY_OUTLAND_BTN', { count: 18, countEmerald: cost18chests, imgEmerald }),
  8603. result: [costFirstChest, costFirstChest, 0, costSecondChest, costSecondChest, 0],
  8604. });
  8605. }
  8606.  
  8607. const answer = await popup.confirm(`<div style="margin-bottom: 15px;">${I18N('BUY_OUTLAND')}</div>`, buttons);
  8608.  
  8609. if (!answer) {
  8610. return;
  8611. }
  8612.  
  8613. const callBoss = [];
  8614. let n = 0;
  8615. for (let boss of boses) {
  8616. const bossId = boss.id;
  8617. if (boss.chestNum != 2) {
  8618. continue;
  8619. }
  8620. const calls = [];
  8621. for (const starmoney of answer) {
  8622. calls.push({
  8623. name: 'bossOpenChest',
  8624. args: {
  8625. amount: 1,
  8626. bossId,
  8627. starmoney,
  8628. },
  8629. ident: 'bossOpenChest_' + ++n,
  8630. });
  8631. }
  8632. callBoss.push(calls);
  8633. }
  8634.  
  8635. if (!callBoss.length) {
  8636. setProgress(I18N('CHESTS_NOT_AVAILABLE'), true);
  8637. return;
  8638. }
  8639.  
  8640. let count = 0;
  8641. let errors = 0;
  8642. for (const calls of callBoss) {
  8643. const result = await Send({ calls });
  8644. console.log(result);
  8645. if (result?.results) {
  8646. count += result.results.length;
  8647. } else {
  8648. errors++;
  8649. }
  8650. }
  8651.  
  8652. setProgress(`${I18N('OUTLAND_CHESTS_RECEIVED')}: ${count}`, true);
  8653. }
  8654.  
  8655. async function autoRaidAdventure() {
  8656. const calls = [
  8657. {
  8658. name: "userGetInfo",
  8659. args: {},
  8660. ident: "userGetInfo"
  8661. },
  8662. {
  8663. name: "adventure_raidGetInfo",
  8664. args: {},
  8665. ident: "adventure_raidGetInfo"
  8666. }
  8667. ];
  8668. const result = await Send(JSON.stringify({ calls }))
  8669. .then(e => e.results.map(n => n.result.response));
  8670.  
  8671. const portalSphere = result[0].refillable.find(n => n.id == 45);
  8672. const adventureRaid = Object.entries(result[1].raid).filter(e => e[1]).pop()
  8673. const adventureId = adventureRaid ? adventureRaid[0] : 0;
  8674.  
  8675. if (!portalSphere.amount || !adventureId) {
  8676. setProgress(I18N('RAID_NOT_AVAILABLE'), true);
  8677. return;
  8678. }
  8679.  
  8680. const countRaid = +(await popup.confirm(I18N('RAID_ADVENTURE', { adventureId }), [
  8681. { result: false, isClose: true },
  8682. { msg: I18N('RAID'), isInput: true, default: portalSphere.amount },
  8683. ]));
  8684.  
  8685. if (!countRaid) {
  8686. return;
  8687. }
  8688.  
  8689. if (countRaid > portalSphere.amount) {
  8690. countRaid = portalSphere.amount;
  8691. }
  8692.  
  8693. const resultRaid = await Send(JSON.stringify({
  8694. calls: [...Array(countRaid)].map((e, i) => ({
  8695. name: "adventure_raid",
  8696. args: {
  8697. adventureId
  8698. },
  8699. ident: `body_${i}`
  8700. }))
  8701. })).then(e => e.results.map(n => n.result.response));
  8702.  
  8703. if (!resultRaid.length) {
  8704. console.log(resultRaid);
  8705. setProgress(I18N('SOMETHING_WENT_WRONG'), true);
  8706. return;
  8707. }
  8708.  
  8709. console.log(resultRaid, adventureId, portalSphere.amount);
  8710. setProgress(I18N('ADVENTURE_COMPLETED', { adventureId, times: resultRaid.length }), true);
  8711. }
  8712.  
  8713. /** Вывести всю клановую статистику в консоль браузера */
  8714. async function clanStatistic() {
  8715. const copy = function (text) {
  8716. const copyTextarea = document.createElement("textarea");
  8717. copyTextarea.style.opacity = "0";
  8718. copyTextarea.textContent = text;
  8719. document.body.appendChild(copyTextarea);
  8720. copyTextarea.select();
  8721. document.execCommand("copy");
  8722. document.body.removeChild(copyTextarea);
  8723. delete copyTextarea;
  8724. }
  8725. const calls = [
  8726. { name: "clanGetInfo", args: {}, ident: "clanGetInfo" },
  8727. { name: "clanGetWeeklyStat", args: {}, ident: "clanGetWeeklyStat" },
  8728. { name: "clanGetLog", args: {}, ident: "clanGetLog" },
  8729. ];
  8730.  
  8731. const result = await Send(JSON.stringify({ calls }));
  8732.  
  8733. const dataClanInfo = result.results[0].result.response;
  8734. const dataClanStat = result.results[1].result.response;
  8735. const dataClanLog = result.results[2].result.response;
  8736.  
  8737. const membersStat = {};
  8738. for (let i = 0; i < dataClanStat.stat.length; i++) {
  8739. membersStat[dataClanStat.stat[i].id] = dataClanStat.stat[i];
  8740. }
  8741.  
  8742. const joinStat = {};
  8743. historyLog = dataClanLog.history;
  8744. for (let j in historyLog) {
  8745. his = historyLog[j];
  8746. if (his.event == 'join') {
  8747. joinStat[his.userId] = his.ctime;
  8748. }
  8749. }
  8750.  
  8751. const infoArr = [];
  8752. const members = dataClanInfo.clan.members;
  8753. for (let n in members) {
  8754. var member = [
  8755. n,
  8756. members[n].name,
  8757. members[n].level,
  8758. dataClanInfo.clan.warriors.includes(+n) ? 1 : 0,
  8759. (new Date(members[n].lastLoginTime * 1000)).toLocaleString().replace(',', ''),
  8760. joinStat[n] ? (new Date(joinStat[n] * 1000)).toLocaleString().replace(',', '') : '',
  8761. membersStat[n].activity.reverse().join('\t'),
  8762. membersStat[n].adventureStat.reverse().join('\t'),
  8763. membersStat[n].clanGifts.reverse().join('\t'),
  8764. membersStat[n].clanWarStat.reverse().join('\t'),
  8765. membersStat[n].dungeonActivity.reverse().join('\t'),
  8766. ];
  8767. infoArr.push(member);
  8768. }
  8769. const info = infoArr.sort((a, b) => (b[2] - a[2])).map((e) => e.join('\t')).join('\n');
  8770. console.log(info);
  8771. copy(info);
  8772. setProgress(I18N('CLAN_STAT_COPY'), true);
  8773. }
  8774.  
  8775. async function buyInStoreForGold() {
  8776. const result = await Send('{"calls":[{"name":"shopGetAll","args":{},"ident":"body"},{"name":"userGetInfo","args":{},"ident":"userGetInfo"}]}').then(e => e.results.map(n => n.result.response));
  8777. const shops = result[0];
  8778. const user = result[1];
  8779. let gold = user.gold;
  8780. const calls = [];
  8781. if (shops[17]) {
  8782. const slots = shops[17].slots;
  8783. for (let i = 1; i <= 2; i++) {
  8784. if (!slots[i].bought) {
  8785. const costGold = slots[i].cost.gold;
  8786. if ((gold - costGold) < 0) {
  8787. continue;
  8788. }
  8789. gold -= costGold;
  8790. calls.push({
  8791. name: "shopBuy",
  8792. args: {
  8793. shopId: 17,
  8794. slot: i,
  8795. cost: slots[i].cost,
  8796. reward: slots[i].reward,
  8797. },
  8798. ident: 'body_' + i,
  8799. })
  8800. }
  8801. }
  8802. }
  8803. const slots = shops[1].slots;
  8804. for (let i = 4; i <= 6; i++) {
  8805. if (!slots[i].bought && slots[i]?.cost?.gold) {
  8806. const costGold = slots[i].cost.gold;
  8807. if ((gold - costGold) < 0) {
  8808. continue;
  8809. }
  8810. gold -= costGold;
  8811. calls.push({
  8812. name: "shopBuy",
  8813. args: {
  8814. shopId: 1,
  8815. slot: i,
  8816. cost: slots[i].cost,
  8817. reward: slots[i].reward,
  8818. },
  8819. ident: 'body_' + i,
  8820. })
  8821. }
  8822. }
  8823.  
  8824. if (!calls.length) {
  8825. setProgress(I18N('NOTHING_BUY'), true);
  8826. return;
  8827. }
  8828.  
  8829. const resultBuy = await Send(JSON.stringify({ calls })).then(e => e.results.map(n => n.result.response));
  8830. console.log(resultBuy);
  8831. const countBuy = resultBuy.length;
  8832. setProgress(I18N('LOTS_BOUGHT', { countBuy }), true);
  8833. }
  8834.  
  8835. function rewardsAndMailFarm() {
  8836. return new Promise(function (resolve, reject) {
  8837. let questGetAllCall = {
  8838. calls: [{
  8839. name: "questGetAll",
  8840. args: {},
  8841. ident: "questGetAll"
  8842. }, {
  8843. name: "mailGetAll",
  8844. args: {},
  8845. ident: "mailGetAll"
  8846. }]
  8847. }
  8848. send(JSON.stringify(questGetAllCall), function (data) {
  8849. if (!data) return;
  8850. const questGetAll = data.results[0].result.response.filter((e) => e.state == 2);
  8851. const questBattlePass = lib.getData('quest').battlePass;
  8852. const questChainBPass = lib.getData('battlePass').questChain;
  8853. const listBattlePass = lib.getData('battlePass').list;
  8854.  
  8855. const questAllFarmCall = {
  8856. calls: [],
  8857. };
  8858. const questIds = [];
  8859. for (let quest of questGetAll) {
  8860. if (quest.id >= 2001e4) {
  8861. continue;
  8862. }
  8863. if (quest.id > 1e6 && quest.id < 2e7) {
  8864. const questInfo = questBattlePass[quest.id];
  8865. const chain = questChainBPass[questInfo.chain];
  8866. if (chain.requirement?.battlePassTicket) {
  8867. continue;
  8868. }
  8869. const battlePass = listBattlePass[chain.battlePass];
  8870. const startTime = battlePass.startCondition.time.value * 1e3
  8871. const endTime = new Date(startTime + battlePass.duration * 1e3);
  8872. if (startTime > Date.now() || endTime < Date.now()) {
  8873. continue;
  8874. }
  8875. }
  8876. if (quest.id >= 2e7) {
  8877. questIds.push(quest.id);
  8878. continue;
  8879. }
  8880. questAllFarmCall.calls.push({
  8881. name: 'questFarm',
  8882. args: {
  8883. questId: quest.id,
  8884. },
  8885. ident: `questFarm_${quest.id}`,
  8886. });
  8887. }
  8888.  
  8889. if (questIds.length) {
  8890. questAllFarmCall.calls.push({
  8891. name: 'quest_questsFarm',
  8892. args: { questIds },
  8893. ident: 'quest_questsFarm',
  8894. });
  8895. }
  8896.  
  8897. let letters = data?.results[1]?.result?.response?.letters;
  8898. letterIds = lettersFilter(letters);
  8899.  
  8900. if (letterIds.length) {
  8901. questAllFarmCall.calls.push({
  8902. name: 'mailFarm',
  8903. args: { letterIds },
  8904. ident: 'mailFarm',
  8905. });
  8906. }
  8907.  
  8908. if (!questAllFarmCall.calls.length) {
  8909. setProgress(I18N('NOTHING_TO_COLLECT'), true);
  8910. resolve();
  8911. return;
  8912. }
  8913.  
  8914. send(JSON.stringify(questAllFarmCall), async function (res) {
  8915. let countQuests = 0;
  8916. let countMail = 0;
  8917. let questsIds = [];
  8918. for (let call of res.results) {
  8919. if (call.ident.includes('questFarm')) {
  8920. countQuests++;
  8921. } else if (call.ident.includes('questsFarm')) {
  8922. countQuests += Object.keys(call.result.response).length;
  8923. } else if (call.ident.includes('mailFarm')) {
  8924. countMail = Object.keys(call.result.response).length;
  8925. }
  8926.  
  8927. const newQuests = call.result.newQuests;
  8928. if (newQuests) {
  8929. for (let quest of newQuests) {
  8930. if ((quest.id < 1e6 || (quest.id >= 2e7 && quest.id < 2001e4)) && quest.state == 2) {
  8931. questsIds.push(quest.id);
  8932. }
  8933. }
  8934. }
  8935. }
  8936.  
  8937. while (questsIds.length) {
  8938. const questIds = [];
  8939. const calls = [];
  8940. for (let questId of questsIds) {
  8941. if (questId < 1e6) {
  8942. calls.push({
  8943. name: 'questFarm',
  8944. args: {
  8945. questId,
  8946. },
  8947. ident: `questFarm_${questId}`,
  8948. });
  8949. countQuests++;
  8950. } else if (questId >= 2e7 && questId < 2001e4) {
  8951. questIds.push(questId);
  8952. countQuests++;
  8953. }
  8954. }
  8955. calls.push({
  8956. name: 'quest_questsFarm',
  8957. args: { questIds },
  8958. ident: 'body',
  8959. });
  8960. const results = await Send({ calls }).then((e) => e.results.map((e) => e.result));
  8961. questsIds = [];
  8962. for (const result of results) {
  8963. const newQuests = result.newQuests;
  8964. if (newQuests) {
  8965. for (let quest of newQuests) {
  8966. if (quest.state == 2) {
  8967. questsIds.push(quest.id);
  8968. }
  8969. }
  8970. }
  8971. }
  8972. }
  8973.  
  8974. setProgress(I18N('COLLECT_REWARDS_AND_MAIL', { countQuests, countMail }), true);
  8975. resolve();
  8976. });
  8977. });
  8978. })
  8979. }
  8980.  
  8981. class epicBrawl {
  8982. timeout = null;
  8983. time = null;
  8984.  
  8985. constructor() {
  8986. if (epicBrawl.inst) {
  8987. return epicBrawl.inst;
  8988. }
  8989. epicBrawl.inst = this;
  8990. return this;
  8991. }
  8992.  
  8993. runTimeout(func, timeDiff) {
  8994. const worker = new Worker(URL.createObjectURL(new Blob([`
  8995. self.onmessage = function(e) {
  8996. const timeDiff = e.data;
  8997.  
  8998. if (timeDiff > 0) {
  8999. setTimeout(() => {
  9000. self.postMessage(1);
  9001. self.close();
  9002. }, timeDiff);
  9003. }
  9004. };
  9005. `])));
  9006. worker.postMessage(timeDiff);
  9007. worker.onmessage = () => {
  9008. func();
  9009. };
  9010. return true;
  9011. }
  9012.  
  9013. timeDiff(date1, date2) {
  9014. const date1Obj = new Date(date1);
  9015. const date2Obj = new Date(date2);
  9016.  
  9017. const timeDiff = Math.abs(date2Obj - date1Obj);
  9018.  
  9019. const totalSeconds = timeDiff / 1000;
  9020. const minutes = Math.floor(totalSeconds / 60);
  9021. const seconds = Math.floor(totalSeconds % 60);
  9022.  
  9023. const formattedMinutes = String(minutes).padStart(2, '0');
  9024. const formattedSeconds = String(seconds).padStart(2, '0');
  9025.  
  9026. return `${formattedMinutes}:${formattedSeconds}`;
  9027. }
  9028.  
  9029. check() {
  9030. console.log(new Date(this.time))
  9031. if (Date.now() > this.time) {
  9032. this.timeout = null;
  9033. this.start()
  9034. return;
  9035. }
  9036. this.timeout = this.runTimeout(() => this.check(), 6e4);
  9037. return this.timeDiff(this.time, Date.now())
  9038. }
  9039.  
  9040. async start() {
  9041. if (this.timeout) {
  9042. const time = this.timeDiff(this.time, Date.now());
  9043. console.log(new Date(this.time))
  9044. setProgress(I18N('TIMER_ALREADY', { time }), false, hideProgress);
  9045. return;
  9046. }
  9047. setProgress(I18N('EPIC_BRAWL'), false, hideProgress);
  9048. 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));
  9049. const refill = teamInfo[2].refillable.find(n => n.id == 52)
  9050. this.time = (refill.lastRefill + 3600) * 1000
  9051. const attempts = refill.amount;
  9052. if (!attempts) {
  9053. console.log(new Date(this.time));
  9054. const time = this.check();
  9055. setProgress(I18N('NO_ATTEMPTS_TIMER_START', { time }), false, hideProgress);
  9056. return;
  9057. }
  9058.  
  9059. if (!teamInfo[0].epic_brawl) {
  9060. setProgress(I18N('NO_HEROES_PACK'), false, hideProgress);
  9061. return;
  9062. }
  9063.  
  9064. const args = {
  9065. heroes: teamInfo[0].epic_brawl.filter(e => e < 1000),
  9066. pet: teamInfo[0].epic_brawl.filter(e => e > 6000).pop(),
  9067. favor: teamInfo[1].epic_brawl,
  9068. }
  9069.  
  9070. let wins = 0;
  9071. let coins = 0;
  9072. let streak = { progress: 0, nextStage: 0 };
  9073. for (let i = attempts; i > 0; i--) {
  9074. const info = await Send(JSON.stringify({
  9075. calls: [
  9076. { name: "epicBrawl_getEnemy", args: {}, ident: "epicBrawl_getEnemy" }, { name: "epicBrawl_startBattle", args, ident: "epicBrawl_startBattle" }
  9077. ]
  9078. })).then(e => e.results.map(n => n.result.response));
  9079.  
  9080. const { progress, result } = await Calc(info[1].battle);
  9081. 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));
  9082.  
  9083. const resultInfo = endResult[0].result;
  9084. streak = endResult[1];
  9085.  
  9086. wins += resultInfo.win;
  9087. coins += resultInfo.reward ? resultInfo.reward.coin[39] : 0;
  9088.  
  9089. console.log(endResult[0].result)
  9090. if (endResult[1].progress == endResult[1].nextStage) {
  9091. const farm = await Send('{"calls":[{"name":"epicBrawl_farmWinStreak","args":{},"ident":"body"}]}').then(e => e.results[0].result.response);
  9092. coins += farm.coin[39];
  9093. }
  9094.  
  9095. setProgress(I18N('EPIC_BRAWL_RESULT', {
  9096. i, wins, attempts, coins,
  9097. progress: streak.progress,
  9098. nextStage: streak.nextStage,
  9099. end: '',
  9100. }), false, hideProgress);
  9101. }
  9102.  
  9103. console.log(new Date(this.time));
  9104. const time = this.check();
  9105. setProgress(I18N('EPIC_BRAWL_RESULT', {
  9106. wins, attempts, coins,
  9107. i: '',
  9108. progress: streak.progress,
  9109. nextStage: streak.nextStage,
  9110. end: I18N('ATTEMPT_ENDED', { time }),
  9111. }), false, hideProgress);
  9112. }
  9113. }
  9114.  
  9115. function countdownTimer(seconds, message) {
  9116. message = message || I18N('TIMER');
  9117. const stopTimer = Date.now() + seconds * 1e3
  9118. return new Promise(resolve => {
  9119. const interval = setInterval(async () => {
  9120. const now = Date.now();
  9121. setProgress(`${message} ${((stopTimer - now) / 1000).toFixed(2)}`, false);
  9122. if (now > stopTimer) {
  9123. clearInterval(interval);
  9124. setProgress('', 1);
  9125. resolve();
  9126. }
  9127. }, 100);
  9128. });
  9129. }
  9130.  
  9131. this.HWHFuncs.countdownTimer = countdownTimer;
  9132.  
  9133. /** Набить килов в горниле душк */
  9134. async function bossRatingEventSouls() {
  9135. const data = await Send({
  9136. calls: [
  9137. { name: "heroGetAll", args: {}, ident: "teamGetAll" },
  9138. { name: "offerGetAll", args: {}, ident: "offerGetAll" },
  9139. { name: "pet_getAll", args: {}, ident: "pet_getAll" },
  9140. ]
  9141. });
  9142. const bossEventInfo = data.results[1].result.response.find(e => e.offerType == "bossEvent");
  9143. if (!bossEventInfo) {
  9144. setProgress('Эвент завершен', true);
  9145. return;
  9146. }
  9147.  
  9148. if (bossEventInfo.progress.score > 250) {
  9149. setProgress('Уже убито больше 250 врагов');
  9150. rewardBossRatingEventSouls();
  9151. return;
  9152. }
  9153. const availablePets = Object.values(data.results[2].result.response).map(e => e.id);
  9154. const heroGetAllList = data.results[0].result.response;
  9155. const usedHeroes = bossEventInfo.progress.usedHeroes;
  9156. const heroList = [];
  9157.  
  9158. for (let heroId in heroGetAllList) {
  9159. let hero = heroGetAllList[heroId];
  9160. if (usedHeroes.includes(hero.id)) {
  9161. continue;
  9162. }
  9163. heroList.push(hero.id);
  9164. }
  9165.  
  9166. if (!heroList.length) {
  9167. setProgress('Нет героев', true);
  9168. return;
  9169. }
  9170.  
  9171. const pet = availablePets.includes(6005) ? 6005 : availablePets[Math.floor(Math.random() * availablePets.length)];
  9172. const petLib = lib.getData('pet');
  9173. let count = 1;
  9174.  
  9175. for (const heroId of heroList) {
  9176. const args = {
  9177. heroes: [heroId],
  9178. pet
  9179. }
  9180. /** Поиск питомца для героя */
  9181. for (const petId of availablePets) {
  9182. if (petLib[petId].favorHeroes.includes(heroId)) {
  9183. args.favor = {
  9184. [heroId]: petId
  9185. }
  9186. break;
  9187. }
  9188. }
  9189.  
  9190. const calls = [{
  9191. name: "bossRatingEvent_startBattle",
  9192. args,
  9193. ident: "body"
  9194. }, {
  9195. name: "offerGetAll",
  9196. args: {},
  9197. ident: "offerGetAll"
  9198. }];
  9199.  
  9200. const res = await Send({ calls });
  9201. count++;
  9202.  
  9203. if ('error' in res) {
  9204. console.error(res.error);
  9205. setProgress('Перезагрузите игру и попробуйте позже', true);
  9206. return;
  9207. }
  9208.  
  9209. const eventInfo = res.results[1].result.response.find(e => e.offerType == "bossEvent");
  9210. if (eventInfo.progress.score > 250) {
  9211. break;
  9212. }
  9213. setProgress('Количество убитых врагов: ' + eventInfo.progress.score + '<br>Использовано ' + count + ' героев');
  9214. }
  9215.  
  9216. rewardBossRatingEventSouls();
  9217. }
  9218. /** Сбор награды из Горнила Душ */
  9219. async function rewardBossRatingEventSouls() {
  9220. const data = await Send({
  9221. calls: [
  9222. { name: "offerGetAll", args: {}, ident: "offerGetAll" }
  9223. ]
  9224. });
  9225.  
  9226. const bossEventInfo = data.results[0].result.response.find(e => e.offerType == "bossEvent");
  9227. if (!bossEventInfo) {
  9228. setProgress('Эвент завершен', true);
  9229. return;
  9230. }
  9231.  
  9232. const farmedChests = bossEventInfo.progress.farmedChests;
  9233. const score = bossEventInfo.progress.score;
  9234. // setProgress('Количество убитых врагов: ' + score);
  9235. const revard = bossEventInfo.reward;
  9236. const calls = [];
  9237.  
  9238. let count = 0;
  9239. for (let i = 1; i < 10; i++) {
  9240. if (farmedChests.includes(i)) {
  9241. continue;
  9242. }
  9243. if (score < revard[i].score) {
  9244. break;
  9245. }
  9246. calls.push({
  9247. name: "bossRatingEvent_getReward",
  9248. args: {
  9249. rewardId: i
  9250. },
  9251. ident: "body_" + i
  9252. });
  9253. count++;
  9254. }
  9255. if (!count) {
  9256. setProgress('Нечего собирать', true);
  9257. return;
  9258. }
  9259.  
  9260. Send({ calls }).then(e => {
  9261. console.log(e);
  9262. setProgress('Собрано ' + e?.results?.length + ' наград', true);
  9263. })
  9264. }
  9265. /**
  9266. * Spin the Seer
  9267. *
  9268. * Покрутить провидца
  9269. */
  9270. async function rollAscension() {
  9271. const refillable = await Send({calls:[
  9272. {
  9273. name:"userGetInfo",
  9274. args:{},
  9275. ident:"userGetInfo"
  9276. }
  9277. ]}).then(e => e.results[0].result.response.refillable);
  9278. const i47 = refillable.find(i => i.id == 47);
  9279. if (i47?.amount) {
  9280. await Send({ calls: [{ name: "ascensionChest_open", args: { paid: false, amount: 1 }, ident: "body" }] });
  9281. setProgress(I18N('DONE'), true);
  9282. } else {
  9283. setProgress(I18N('NOT_ENOUGH_AP'), true);
  9284. }
  9285. }
  9286.  
  9287. /**
  9288. * Collect gifts for the New Year
  9289. *
  9290. * Собрать подарки на новый год
  9291. */
  9292. function getGiftNewYear() {
  9293. Send({ calls: [{ name: "newYearGiftGet", args: { type: 0 }, ident: "body" }] }).then(e => {
  9294. const gifts = e.results[0].result.response.gifts;
  9295. const calls = gifts.filter(e => e.opened == 0).map(e => ({
  9296. name: "newYearGiftOpen",
  9297. args: {
  9298. giftId: e.id
  9299. },
  9300. ident: `body_${e.id}`
  9301. }));
  9302. if (!calls.length) {
  9303. setProgress(I18N('NY_NO_GIFTS'), 5000);
  9304. return;
  9305. }
  9306. Send({ calls }).then(e => {
  9307. console.log(e.results)
  9308. const msg = I18N('NY_GIFTS_COLLECTED', { count: e.results.length });
  9309. console.log(msg);
  9310. setProgress(msg, 5000);
  9311. });
  9312. })
  9313. }
  9314.  
  9315. async function updateArtifacts() {
  9316. const count = +await popup.confirm(I18N('SET_NUMBER_LEVELS'), [
  9317. { msg: I18N('BTN_GO'), isInput: true, default: 10 },
  9318. { result: false, isClose: true }
  9319. ]);
  9320. if (!count) {
  9321. return;
  9322. }
  9323. const quest = new questRun;
  9324. await quest.autoInit();
  9325. const heroes = Object.values(quest.questInfo['heroGetAll']);
  9326. const inventory = quest.questInfo['inventoryGet'];
  9327. const calls = [];
  9328. for (let i = count; i > 0; i--) {
  9329. const upArtifact = quest.getUpgradeArtifact();
  9330. if (!upArtifact.heroId) {
  9331. if (await popup.confirm(I18N('POSSIBLE_IMPROVE_LEVELS', { count: calls.length }), [
  9332. { msg: I18N('YES'), result: true },
  9333. { result: false, isClose: true }
  9334. ])) {
  9335. break;
  9336. } else {
  9337. return;
  9338. }
  9339. }
  9340. const hero = heroes.find(e => e.id == upArtifact.heroId);
  9341. hero.artifacts[upArtifact.slotId].level++;
  9342. inventory[upArtifact.costCurrency][upArtifact.costId] -= upArtifact.costValue;
  9343. calls.push({
  9344. name: "heroArtifactLevelUp",
  9345. args: {
  9346. heroId: upArtifact.heroId,
  9347. slotId: upArtifact.slotId
  9348. },
  9349. ident: `heroArtifactLevelUp_${i}`
  9350. });
  9351. }
  9352.  
  9353. if (!calls.length) {
  9354. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  9355. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  9356. return;
  9357. }
  9358.  
  9359. await Send(JSON.stringify({ calls })).then(e => {
  9360. if ('error' in e) {
  9361. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  9362. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  9363. } else {
  9364. console.log(I18N('IMPROVED_LEVELS', { count: e.results.length }));
  9365. setProgress(I18N('IMPROVED_LEVELS', { count: e.results.length }), false);
  9366. }
  9367. });
  9368. }
  9369.  
  9370. window.sign = a => {
  9371. const i = this['\x78\x79\x7a'];
  9372. 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'))
  9373. }
  9374.  
  9375. async function updateSkins() {
  9376. const count = +await popup.confirm(I18N('SET_NUMBER_LEVELS'), [
  9377. { msg: I18N('BTN_GO'), isInput: true, default: 10 },
  9378. { result: false, isClose: true }
  9379. ]);
  9380. if (!count) {
  9381. return;
  9382. }
  9383.  
  9384. const quest = new questRun;
  9385. await quest.autoInit();
  9386. const heroes = Object.values(quest.questInfo['heroGetAll']);
  9387. const inventory = quest.questInfo['inventoryGet'];
  9388. const calls = [];
  9389. for (let i = count; i > 0; i--) {
  9390. const upSkin = quest.getUpgradeSkin();
  9391. if (!upSkin.heroId) {
  9392. if (await popup.confirm(I18N('POSSIBLE_IMPROVE_LEVELS', { count: calls.length }), [
  9393. { msg: I18N('YES'), result: true },
  9394. { result: false, isClose: true }
  9395. ])) {
  9396. break;
  9397. } else {
  9398. return;
  9399. }
  9400. }
  9401. const hero = heroes.find(e => e.id == upSkin.heroId);
  9402. hero.skins[upSkin.skinId]++;
  9403. inventory[upSkin.costCurrency][upSkin.costCurrencyId] -= upSkin.cost;
  9404. calls.push({
  9405. name: "heroSkinUpgrade",
  9406. args: {
  9407. heroId: upSkin.heroId,
  9408. skinId: upSkin.skinId
  9409. },
  9410. ident: `heroSkinUpgrade_${i}`
  9411. })
  9412. }
  9413.  
  9414. if (!calls.length) {
  9415. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  9416. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  9417. return;
  9418. }
  9419.  
  9420. await Send(JSON.stringify({ calls })).then(e => {
  9421. if ('error' in e) {
  9422. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  9423. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  9424. } else {
  9425. console.log(I18N('IMPROVED_LEVELS', { count: e.results.length }));
  9426. setProgress(I18N('IMPROVED_LEVELS', { count: e.results.length }), false);
  9427. }
  9428. });
  9429. }
  9430.  
  9431. function getQuestionInfo(img, nameOnly = false) {
  9432. const libHeroes = Object.values(lib.data.hero);
  9433. const parts = img.split(':');
  9434. const id = parts[1];
  9435. switch (parts[0]) {
  9436. case 'titanArtifact_id':
  9437. return cheats.translate("LIB_TITAN_ARTIFACT_NAME_" + id);
  9438. case 'titan':
  9439. return cheats.translate("LIB_HERO_NAME_" + id);
  9440. case 'skill':
  9441. return cheats.translate("LIB_SKILL_" + id);
  9442. case 'inventoryItem_gear':
  9443. return cheats.translate("LIB_GEAR_NAME_" + id);
  9444. case 'inventoryItem_coin':
  9445. return cheats.translate("LIB_COIN_NAME_" + id);
  9446. case 'artifact':
  9447. if (nameOnly) {
  9448. return cheats.translate("LIB_ARTIFACT_NAME_" + id);
  9449. }
  9450. heroes = libHeroes.filter(h => h.id < 100 && h.artifacts.includes(+id));
  9451. return {
  9452. /** Как называется этот артефакт? */
  9453. name: cheats.translate("LIB_ARTIFACT_NAME_" + id),
  9454. /** Какому герою принадлежит этот артефакт? */
  9455. heroes: heroes.map(h => cheats.translate("LIB_HERO_NAME_" + h.id))
  9456. };
  9457. case 'hero':
  9458. if (nameOnly) {
  9459. return cheats.translate("LIB_HERO_NAME_" + id);
  9460. }
  9461. artifacts = lib.data.hero[id].artifacts;
  9462. return {
  9463. /** Как зовут этого героя? */
  9464. name: cheats.translate("LIB_HERO_NAME_" + id),
  9465. /** Какой артефакт принадлежит этому герою? */
  9466. artifact: artifacts.map(a => cheats.translate("LIB_ARTIFACT_NAME_" + a))
  9467. };
  9468. }
  9469. }
  9470.  
  9471. function hintQuest(quest) {
  9472. const result = {};
  9473. if (quest?.questionIcon) {
  9474. const info = getQuestionInfo(quest.questionIcon);
  9475. if (info?.heroes) {
  9476. /** Какому герою принадлежит этот артефакт? */
  9477. result.answer = quest.answers.filter(e => info.heroes.includes(e.answerText.slice(1)));
  9478. }
  9479. if (info?.artifact) {
  9480. /** Какой артефакт принадлежит этому герою? */
  9481. result.answer = quest.answers.filter(e => info.artifact.includes(e.answerText.slice(1)));
  9482. }
  9483. if (typeof info == 'string') {
  9484. result.info = { name: info };
  9485. } else {
  9486. result.info = info;
  9487. }
  9488. }
  9489.  
  9490. if (quest.answers[0]?.answerIcon) {
  9491. result.answer = quest.answers.filter(e => quest.question.includes(getQuestionInfo(e.answerIcon, true)))
  9492. }
  9493.  
  9494. if ((!result?.answer || !result.answer.length) && !result.info?.name) {
  9495. return false;
  9496. }
  9497.  
  9498. let resultText = '';
  9499. if (result?.info) {
  9500. resultText += I18N('PICTURE') + result.info.name;
  9501. }
  9502. console.log(result);
  9503. if (result?.answer && result.answer.length) {
  9504. resultText += I18N('ANSWER') + result.answer[0].id + (!result.answer[0].answerIcon ? ' - ' + result.answer[0].answerText : '');
  9505. }
  9506.  
  9507. return resultText;
  9508. }
  9509.  
  9510. async function farmBattlePass() {
  9511. const isFarmReward = (reward) => {
  9512. return !(reward?.buff || reward?.fragmentHero || reward?.bundleHeroReward);
  9513. };
  9514.  
  9515. const battlePassProcess = (pass) => {
  9516. if (!pass.id) {return []}
  9517. const levels = Object.values(lib.data.battlePass.level).filter(x => x.battlePass == pass.id)
  9518. const last_level = levels[levels.length - 1];
  9519. let actual = Math.max(...levels.filter(p => pass.exp >= p.experience).map(p => p.level))
  9520.  
  9521. if (pass.exp > last_level.experience) {
  9522. actual = last_level.level + (pass.exp - last_level.experience) / last_level.experienceByLevel;
  9523. }
  9524. const calls = [];
  9525. for(let i = 1; i <= actual; i++) {
  9526. const level = i >= last_level.level ? last_level : levels.find(l => l.level === i);
  9527. const reward = {free: level?.freeReward, paid:level?.paidReward};
  9528.  
  9529. if (!pass.rewards[i]?.free && isFarmReward(reward.free)) {
  9530. const args = {level: i, free:true};
  9531. if (!pass.gold) { args.id = pass.id }
  9532. calls.push({ name: 'battlePass_farmReward', args, ident: `${pass.gold ? 'body' : 'spesial'}_free_${args.id}_${i}` });
  9533. }
  9534. if (pass.ticket && !pass.rewards[i]?.paid && isFarmReward(reward.paid)) {
  9535. const args = {level: i, free:false};
  9536. if (!pass.gold) { args.id = pass.id}
  9537. calls.push({ name: 'battlePass_farmReward', args, ident: `${pass.gold ? 'body' : 'spesial'}_paid_${args.id}_${i}` });
  9538. }
  9539. }
  9540. return calls;
  9541. }
  9542.  
  9543. const passes = await Send({
  9544. calls: [
  9545. { name: 'battlePass_getInfo', args: {}, ident: 'getInfo' },
  9546. { name: 'battlePass_getSpecial', args: {}, ident: 'getSpecial' },
  9547. ],
  9548. }).then((e) => [{...e.results[0].result.response?.battlePass, gold: true}, ...Object.values(e.results[1].result.response)]);
  9549.  
  9550. const calls = passes.map(p => battlePassProcess(p)).flat()
  9551.  
  9552. if (!calls.length) {
  9553. setProgress(I18N('NOTHING_TO_COLLECT'));
  9554. return;
  9555. }
  9556.  
  9557. let results = await Send({calls});
  9558. if (results.error) {
  9559. console.log(results.error);
  9560. setProgress(I18N('SOMETHING_WENT_WRONG'));
  9561. } else {
  9562. setProgress(I18N('SEASON_REWARD_COLLECTED', {count: results.results.length}), true);
  9563. }
  9564. }
  9565.  
  9566. async function sellHeroSoulsForGold() {
  9567. let { fragmentHero, heroes } = await Send({
  9568. calls: [
  9569. { name: 'inventoryGet', args: {}, ident: 'inventoryGet' },
  9570. { name: 'heroGetAll', args: {}, ident: 'heroGetAll' },
  9571. ],
  9572. })
  9573. .then((e) => e.results.map((r) => r.result.response))
  9574. .then((e) => ({ fragmentHero: e[0].fragmentHero, heroes: e[1] }));
  9575.  
  9576. const calls = [];
  9577. for (let i in fragmentHero) {
  9578. if (heroes[i] && heroes[i].star == 6) {
  9579. calls.push({
  9580. name: 'inventorySell',
  9581. args: {
  9582. type: 'hero',
  9583. libId: i,
  9584. amount: fragmentHero[i],
  9585. fragment: true,
  9586. },
  9587. ident: 'inventorySell_' + i,
  9588. });
  9589. }
  9590. }
  9591. if (!calls.length) {
  9592. console.log(0);
  9593. return 0;
  9594. }
  9595. const rewards = await Send({ calls }).then((e) => e.results.map((r) => r.result?.response?.gold || 0));
  9596. const gold = rewards.reduce((e, a) => e + a, 0);
  9597. setProgress(I18N('GOLD_RECEIVED', { gold }), true);
  9598. }
  9599.  
  9600. /**
  9601. * Attack of the minions of Asgard
  9602. *
  9603. * Атака прислужников Асгарда
  9604. */
  9605. function testRaidNodes() {
  9606. const { executeRaidNodes } = HWHClasses;
  9607. return new Promise((resolve, reject) => {
  9608. const tower = new executeRaidNodes(resolve, reject);
  9609. tower.start();
  9610. });
  9611. }
  9612.  
  9613. /**
  9614. * Attack of the minions of Asgard
  9615. *
  9616. * Атака прислужников Асгарда
  9617. */
  9618. function executeRaidNodes(resolve, reject) {
  9619. let raidData = {
  9620. teams: [],
  9621. favor: {},
  9622. nodes: [],
  9623. attempts: 0,
  9624. countExecuteBattles: 0,
  9625. cancelBattle: 0,
  9626. }
  9627.  
  9628. callsExecuteRaidNodes = {
  9629. calls: [{
  9630. name: "clanRaid_getInfo",
  9631. args: {},
  9632. ident: "clanRaid_getInfo"
  9633. }, {
  9634. name: "teamGetAll",
  9635. args: {},
  9636. ident: "teamGetAll"
  9637. }, {
  9638. name: "teamGetFavor",
  9639. args: {},
  9640. ident: "teamGetFavor"
  9641. }]
  9642. }
  9643.  
  9644. this.start = function () {
  9645. send(JSON.stringify(callsExecuteRaidNodes), startRaidNodes);
  9646. }
  9647.  
  9648. async function startRaidNodes(data) {
  9649. res = data.results;
  9650. clanRaidInfo = res[0].result.response;
  9651. teamGetAll = res[1].result.response;
  9652. teamGetFavor = res[2].result.response;
  9653.  
  9654. let index = 0;
  9655. let isNotFullPack = false;
  9656. for (let team of teamGetAll.clanRaid_nodes) {
  9657. if (team.length < 6) {
  9658. isNotFullPack = true;
  9659. }
  9660. raidData.teams.push({
  9661. data: {},
  9662. heroes: team.filter(id => id < 6000),
  9663. pet: team.filter(id => id >= 6000).pop(),
  9664. battleIndex: index++
  9665. });
  9666. }
  9667. raidData.favor = teamGetFavor.clanRaid_nodes;
  9668.  
  9669. if (isNotFullPack) {
  9670. if (await popup.confirm(I18N('MINIONS_WARNING'), [
  9671. { msg: I18N('BTN_NO'), result: true },
  9672. { msg: I18N('BTN_YES'), result: false },
  9673. ])) {
  9674. endRaidNodes('isNotFullPack');
  9675. return;
  9676. }
  9677. }
  9678.  
  9679. raidData.nodes = clanRaidInfo.nodes;
  9680. raidData.attempts = clanRaidInfo.attempts;
  9681. setIsCancalBattle(false);
  9682.  
  9683. checkNodes();
  9684. }
  9685.  
  9686. function getAttackNode() {
  9687. for (let nodeId in raidData.nodes) {
  9688. let node = raidData.nodes[nodeId];
  9689. let points = 0
  9690. for (team of node.teams) {
  9691. points += team.points;
  9692. }
  9693. let now = Date.now() / 1000;
  9694. if (!points && now > node.timestamps.start && now < node.timestamps.end) {
  9695. let countTeam = node.teams.length;
  9696. delete raidData.nodes[nodeId];
  9697. return {
  9698. nodeId,
  9699. countTeam
  9700. };
  9701. }
  9702. }
  9703. return null;
  9704. }
  9705.  
  9706. function checkNodes() {
  9707. setProgress(`${I18N('REMAINING_ATTEMPTS')}: ${raidData.attempts}`);
  9708. let nodeInfo = getAttackNode();
  9709. if (nodeInfo && raidData.attempts) {
  9710. startNodeBattles(nodeInfo);
  9711. return;
  9712. }
  9713.  
  9714. endRaidNodes('EndRaidNodes');
  9715. }
  9716.  
  9717. function startNodeBattles(nodeInfo) {
  9718. let {nodeId, countTeam} = nodeInfo;
  9719. let teams = raidData.teams.slice(0, countTeam);
  9720. let heroes = raidData.teams.map(e => e.heroes).flat();
  9721. let favor = {...raidData.favor};
  9722. for (let heroId in favor) {
  9723. if (!heroes.includes(+heroId)) {
  9724. delete favor[heroId];
  9725. }
  9726. }
  9727.  
  9728. let calls = [{
  9729. name: "clanRaid_startNodeBattles",
  9730. args: {
  9731. nodeId,
  9732. teams,
  9733. favor
  9734. },
  9735. ident: "body"
  9736. }];
  9737.  
  9738. send(JSON.stringify({calls}), resultNodeBattles);
  9739. }
  9740.  
  9741. function resultNodeBattles(e) {
  9742. if (e['error']) {
  9743. endRaidNodes('nodeBattlesError', e['error']);
  9744. return;
  9745. }
  9746.  
  9747. console.log(e);
  9748. let battles = e.results[0].result.response.battles;
  9749. let promises = [];
  9750. let battleIndex = 0;
  9751. for (let battle of battles) {
  9752. battle.battleIndex = battleIndex++;
  9753. promises.push(calcBattleResult(battle));
  9754. }
  9755.  
  9756. Promise.all(promises)
  9757. .then(results => {
  9758. const endResults = {};
  9759. let isAllWin = true;
  9760. for (let r of results) {
  9761. isAllWin &&= r.result.win;
  9762. }
  9763. if (!isAllWin) {
  9764. cancelEndNodeBattle(results[0]);
  9765. return;
  9766. }
  9767. raidData.countExecuteBattles = results.length;
  9768. let timeout = 500;
  9769. for (let r of results) {
  9770. setTimeout(endNodeBattle, timeout, r);
  9771. timeout += 500;
  9772. }
  9773. });
  9774. }
  9775. /**
  9776. * Returns the battle calculation promise
  9777. *
  9778. * Возвращает промис расчета боя
  9779. */
  9780. function calcBattleResult(battleData) {
  9781. return new Promise(function (resolve, reject) {
  9782. BattleCalc(battleData, "get_clanPvp", resolve);
  9783. });
  9784. }
  9785. /**
  9786. * Cancels the fight
  9787. *
  9788. * Отменяет бой
  9789. */
  9790. function cancelEndNodeBattle(r) {
  9791. const fixBattle = function (heroes) {
  9792. for (const ids in heroes) {
  9793. hero = heroes[ids];
  9794. hero.energy = random(1, 999);
  9795. if (hero.hp > 0) {
  9796. hero.hp = random(1, hero.hp);
  9797. }
  9798. }
  9799. }
  9800. fixBattle(r.progress[0].attackers.heroes);
  9801. fixBattle(r.progress[0].defenders.heroes);
  9802. endNodeBattle(r);
  9803. }
  9804. /**
  9805. * Ends the fight
  9806. *
  9807. * Завершает бой
  9808. */
  9809. function endNodeBattle(r) {
  9810. let nodeId = r.battleData.result.nodeId;
  9811. let battleIndex = r.battleData.battleIndex;
  9812. let calls = [{
  9813. name: "clanRaid_endNodeBattle",
  9814. args: {
  9815. nodeId,
  9816. battleIndex,
  9817. result: r.result,
  9818. progress: r.progress
  9819. },
  9820. ident: "body"
  9821. }]
  9822.  
  9823. SendRequest(JSON.stringify({calls}), battleResult);
  9824. }
  9825. /**
  9826. * Processing the results of the battle
  9827. *
  9828. * Обработка результатов боя
  9829. */
  9830. function battleResult(e) {
  9831. if (e['error']) {
  9832. endRaidNodes('missionEndError', e['error']);
  9833. return;
  9834. }
  9835. r = e.results[0].result.response;
  9836. if (r['error']) {
  9837. if (r.reason == "invalidBattle") {
  9838. raidData.cancelBattle++;
  9839. checkNodes();
  9840. } else {
  9841. endRaidNodes('missionEndError', e['error']);
  9842. }
  9843. return;
  9844. }
  9845.  
  9846. if (!(--raidData.countExecuteBattles)) {
  9847. raidData.attempts--;
  9848. checkNodes();
  9849. }
  9850. }
  9851. /**
  9852. * Completing a task
  9853. *
  9854. * Завершение задачи
  9855. */
  9856. function endRaidNodes(reason, info) {
  9857. setIsCancalBattle(true);
  9858. let textCancel = raidData.cancelBattle ? ` ${I18N('BATTLES_CANCELED')}: ${raidData.cancelBattle}` : '';
  9859. setProgress(`${I18N('MINION_RAID')} ${I18N('COMPLETED')}! ${textCancel}`, true);
  9860. console.log(reason, info);
  9861. resolve();
  9862. }
  9863. }
  9864.  
  9865. this.HWHClasses.executeRaidNodes = executeRaidNodes;
  9866.  
  9867. /**
  9868. * Asgard Boss Attack Replay
  9869. *
  9870. * Повтор атаки босса Асгарда
  9871. */
  9872. function testBossBattle() {
  9873. const { executeBossBattle } = HWHClasses;
  9874. return new Promise((resolve, reject) => {
  9875. const bossBattle = new executeBossBattle(resolve, reject);
  9876. bossBattle.start(lastBossBattle);
  9877. });
  9878. }
  9879.  
  9880. /**
  9881. * Asgard Boss Attack Replay
  9882. *
  9883. * Повтор атаки босса Асгарда
  9884. */
  9885. function executeBossBattle(resolve, reject) {
  9886.  
  9887. this.start = function (battleInfo) {
  9888. preCalcBattle(battleInfo);
  9889. }
  9890.  
  9891. function getBattleInfo(battle) {
  9892. return new Promise(function (resolve) {
  9893. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  9894. BattleCalc(battle, getBattleType(battle.type), e => {
  9895. let extra = e.progress[0].defenders.heroes[1].extra;
  9896. resolve(extra.damageTaken + extra.damageTakenNextLevel);
  9897. });
  9898. });
  9899. }
  9900.  
  9901. function preCalcBattle(battle) {
  9902. let actions = [];
  9903. const countTestBattle = getInput('countTestBattle');
  9904. for (let i = 0; i < countTestBattle; i++) {
  9905. actions.push(getBattleInfo(battle, true));
  9906. }
  9907. Promise.all(actions)
  9908. .then(resultPreCalcBattle);
  9909. }
  9910.  
  9911. async function resultPreCalcBattle(damages) {
  9912. let maxDamage = 0;
  9913. let minDamage = 1e10;
  9914. let avgDamage = 0;
  9915. for (let damage of damages) {
  9916. avgDamage += damage
  9917. if (damage > maxDamage) {
  9918. maxDamage = damage;
  9919. }
  9920. if (damage < minDamage) {
  9921. minDamage = damage;
  9922. }
  9923. }
  9924. avgDamage /= damages.length;
  9925. console.log(damages.map(e => e.toLocaleString()).join('\n'), avgDamage, maxDamage);
  9926.  
  9927. await popup.confirm(
  9928. `${I18N('ROUND_STAT')} ${damages.length} ${I18N('BATTLE')}:` +
  9929. `<br>${I18N('MINIMUM')}: ` + minDamage.toLocaleString() +
  9930. `<br>${I18N('MAXIMUM')}: ` + maxDamage.toLocaleString() +
  9931. `<br>${I18N('AVERAGE')}: ` + avgDamage.toLocaleString()
  9932. , [
  9933. { msg: I18N('BTN_OK'), result: 0},
  9934. ])
  9935. endBossBattle(I18N('BTN_CANCEL'));
  9936. }
  9937.  
  9938. /**
  9939. * Completing a task
  9940. *
  9941. * Завершение задачи
  9942. */
  9943. function endBossBattle(reason, info) {
  9944. console.log(reason, info);
  9945. resolve();
  9946. }
  9947. }
  9948.  
  9949. this.HWHClasses.executeBossBattle = executeBossBattle;
  9950.  
  9951. class FixBattle {
  9952. minTimer = 1.3;
  9953. maxTimer = 15.3;
  9954.  
  9955. constructor(battle, isTimeout = true) {
  9956. this.battle = structuredClone(battle);
  9957. this.isTimeout = isTimeout;
  9958. }
  9959.  
  9960. timeout(callback, timeout) {
  9961. if (this.isTimeout) {
  9962. this.worker.postMessage(timeout);
  9963. this.worker.onmessage = callback;
  9964. } else {
  9965. callback();
  9966. }
  9967. }
  9968.  
  9969. randTimer() {
  9970. return Math.random() * (this.maxTimer - this.minTimer + 1) + this.minTimer;
  9971. }
  9972.  
  9973. setAvgTime(startTime) {
  9974. this.fixTime += Date.now() - startTime;
  9975. this.avgTime = this.fixTime / this.count;
  9976. }
  9977.  
  9978. init() {
  9979. this.fixTime = 0;
  9980. this.lastTimer = 0;
  9981. this.index = 0;
  9982. this.lastBossDamage = 0;
  9983. this.bestResult = {
  9984. count: 0,
  9985. timer: 0,
  9986. value: 0,
  9987. result: null,
  9988. progress: null,
  9989. };
  9990. this.lastBattleResult = {
  9991. win: false,
  9992. };
  9993. this.worker = new Worker(
  9994. URL.createObjectURL(
  9995. new Blob([
  9996. `self.onmessage = function(e) {
  9997. const timeout = e.data;
  9998. setTimeout(() => {
  9999. self.postMessage(1);
  10000. }, timeout);
  10001. };`,
  10002. ])
  10003. )
  10004. );
  10005. }
  10006.  
  10007. async start(endTime = Date.now() + 6e4, maxCount = 100) {
  10008. this.endTime = endTime;
  10009. this.maxCount = maxCount;
  10010. this.init();
  10011. return await new Promise((resolve) => {
  10012. this.resolve = resolve;
  10013. this.count = 0;
  10014. this.loop();
  10015. });
  10016. }
  10017.  
  10018. endFix() {
  10019. this.bestResult.maxCount = this.count;
  10020. this.worker.terminate();
  10021. this.resolve(this.bestResult);
  10022. }
  10023.  
  10024. async loop() {
  10025. const start = Date.now();
  10026. if (this.isEndLoop()) {
  10027. this.endFix();
  10028. return;
  10029. }
  10030. this.count++;
  10031. try {
  10032. this.lastResult = await Calc(this.battle);
  10033. } catch (e) {
  10034. this.updateProgressTimer(this.index++);
  10035. this.timeout(this.loop.bind(this), 0);
  10036. return;
  10037. }
  10038. const { progress, result } = this.lastResult;
  10039. this.lastBattleResult = result;
  10040. this.lastBattleProgress = progress;
  10041. this.setAvgTime(start);
  10042. this.checkResult();
  10043. this.showResult();
  10044. this.updateProgressTimer();
  10045. this.timeout(this.loop.bind(this), 0);
  10046. }
  10047.  
  10048. isEndLoop() {
  10049. return this.count >= this.maxCount || this.endTime < Date.now();
  10050. }
  10051.  
  10052. updateProgressTimer(index = 0) {
  10053. this.lastTimer = this.randTimer();
  10054. this.battle.progress = [{ attackers: { input: ['auto', 0, 0, 'auto', index, this.lastTimer] } }];
  10055. }
  10056.  
  10057. showResult() {
  10058. console.log(
  10059. this.count,
  10060. this.avgTime.toFixed(2),
  10061. (this.endTime - Date.now()) / 1000,
  10062. this.lastTimer.toFixed(2),
  10063. this.lastBossDamage.toLocaleString(),
  10064. this.bestResult.value.toLocaleString()
  10065. );
  10066. }
  10067.  
  10068. checkResult() {
  10069. const { damageTaken, damageTakenNextLevel } = this.lastBattleProgress[0].defenders.heroes[1].extra;
  10070. this.lastBossDamage = damageTaken + damageTakenNextLevel;
  10071. if (this.lastBossDamage > this.bestResult.value) {
  10072. this.bestResult = {
  10073. count: this.count,
  10074. timer: this.lastTimer,
  10075. value: this.lastBossDamage,
  10076. result: structuredClone(this.lastBattleResult),
  10077. progress: structuredClone(this.lastBattleProgress),
  10078. };
  10079. }
  10080. }
  10081.  
  10082. stopFix() {
  10083. this.endTime = 0;
  10084. }
  10085. }
  10086.  
  10087. this.HWHClasses.FixBattle = FixBattle;
  10088.  
  10089. class WinFixBattle extends FixBattle {
  10090. checkResult() {
  10091. if (this.lastBattleResult.win) {
  10092. this.bestResult = {
  10093. count: this.count,
  10094. timer: this.lastTimer,
  10095. value: this.lastBattleResult.stars,
  10096. result: structuredClone(this.lastBattleResult),
  10097. progress: structuredClone(this.lastBattleProgress),
  10098. battleTimer: this.lastResult.battleTimer,
  10099. };
  10100. }
  10101. }
  10102.  
  10103. setWinTimer(value) {
  10104. this.winTimer = value;
  10105. }
  10106.  
  10107. setMaxTimer(value) {
  10108. this.maxTimer = value;
  10109. }
  10110.  
  10111. randTimer() {
  10112. if (this.winTimer) {
  10113. return this.winTimer;
  10114. }
  10115. return super.randTimer();
  10116. }
  10117.  
  10118. isEndLoop() {
  10119. return super.isEndLoop() || this.bestResult.result?.win;
  10120. }
  10121.  
  10122. showResult() {
  10123. console.log(
  10124. this.count,
  10125. this.avgTime.toFixed(2),
  10126. (this.endTime - Date.now()) / 1000,
  10127. this.lastResult.battleTime,
  10128. this.lastTimer,
  10129. this.bestResult.value
  10130. );
  10131. const endTime = ((this.endTime - Date.now()) / 1000).toFixed(2);
  10132. const avgTime = this.avgTime.toFixed(2);
  10133. const msg = `${I18N('LETS_FIX')} ${this.count}/${this.maxCount}<br/>${endTime}s<br/>${avgTime}ms`;
  10134. setProgress(msg, false, this.stopFix.bind(this));
  10135. }
  10136. }
  10137.  
  10138. this.HWHClasses.WinFixBattle = WinFixBattle;
  10139.  
  10140. class BestOrWinFixBattle extends WinFixBattle {
  10141. isNoMakeWin = false;
  10142.  
  10143. getState(result) {
  10144. let beforeSumFactor = 0;
  10145. const beforeHeroes = result.battleData.defenders[0];
  10146. for (let heroId in beforeHeroes) {
  10147. const hero = beforeHeroes[heroId];
  10148. const state = hero.state;
  10149. let factor = 1;
  10150. if (state) {
  10151. const hp = state.hp / (hero?.hp || 1);
  10152. const energy = state.energy / 1e3;
  10153. factor = hp + energy / 20;
  10154. }
  10155. beforeSumFactor += factor;
  10156. }
  10157.  
  10158. let afterSumFactor = 0;
  10159. const afterHeroes = result.progress[0].defenders.heroes;
  10160. for (let heroId in afterHeroes) {
  10161. const hero = afterHeroes[heroId];
  10162. const hp = hero.hp / (beforeHeroes[heroId]?.hp || 1);
  10163. const energy = hero.energy / 1e3;
  10164. const factor = hp + energy / 20;
  10165. afterSumFactor += factor;
  10166. }
  10167. return 100 - Math.floor((afterSumFactor / beforeSumFactor) * 1e4) / 100;
  10168. }
  10169.  
  10170. setNoMakeWin(value) {
  10171. this.isNoMakeWin = value;
  10172. }
  10173.  
  10174. checkResult() {
  10175. const state = this.getState(this.lastResult);
  10176. console.log(state);
  10177.  
  10178. if (state > this.bestResult.value) {
  10179. if (!(this.isNoMakeWin && this.lastBattleResult.win)) {
  10180. this.bestResult = {
  10181. count: this.count,
  10182. timer: this.lastTimer,
  10183. value: state,
  10184. result: structuredClone(this.lastBattleResult),
  10185. progress: structuredClone(this.lastBattleProgress),
  10186. battleTimer: this.lastResult.battleTimer,
  10187. };
  10188. }
  10189. }
  10190. }
  10191. }
  10192.  
  10193. this.HWHClasses.BestOrWinFixBattle = BestOrWinFixBattle;
  10194.  
  10195. class BossFixBattle extends FixBattle {
  10196. showResult() {
  10197. super.showResult();
  10198. //setTimeout(() => {
  10199. const best = this.bestResult;
  10200. const maxDmg = best.value.toLocaleString();
  10201. const avgTime = this.avgTime.toLocaleString();
  10202. const msg = `${I18N('LETS_FIX')} ${this.count}/${this.maxCount}<br/>${maxDmg}<br/>${avgTime}ms`;
  10203. setProgress(msg, false, this.stopFix.bind(this));
  10204. //}, 0);
  10205. }
  10206. }
  10207.  
  10208. this.HWHClasses.BossFixBattle = BossFixBattle;
  10209.  
  10210. class DungeonFixBattle extends FixBattle {
  10211. init() {
  10212. super.init();
  10213. this.isTimeout = false;
  10214. }
  10215.  
  10216. setState() {
  10217. const result = this.lastResult;
  10218. let beforeSumFactor = 0;
  10219. const beforeHeroes = result.battleData.attackers;
  10220. for (let heroId in beforeHeroes) {
  10221. const hero = beforeHeroes[heroId];
  10222. const state = hero.state;
  10223. let factor = 1;
  10224. if (state) {
  10225. const hp = state.hp / (hero?.hp || 1);
  10226. const energy = state.energy / 1e3;
  10227. factor = hp + energy / 20;
  10228. }
  10229. beforeSumFactor += factor;
  10230. }
  10231.  
  10232. let afterSumFactor = 0;
  10233. const afterHeroes = result.progress[0].attackers.heroes;
  10234. for (let heroId in afterHeroes) {
  10235. const hero = afterHeroes[heroId];
  10236. const hp = hero.hp / (beforeHeroes[heroId]?.hp || 1);
  10237. const energy = hero.energy / 1e3;
  10238. const factor = hp + energy / 20;
  10239. afterSumFactor += factor;
  10240. }
  10241. this.lastState = Math.floor((afterSumFactor / beforeSumFactor) * 1e4) / 100;
  10242. }
  10243.  
  10244. checkResult() {
  10245. this.setState();
  10246. if (this.lastResult.result.win && this.lastState > this.bestResult.value) {
  10247. this.bestResult = {
  10248. count: this.count,
  10249. timer: this.lastTimer,
  10250. value: this.lastState,
  10251. result: this.lastResult.result,
  10252. progress: this.lastResult.progress,
  10253. };
  10254. }
  10255. }
  10256.  
  10257. showResult() {
  10258. console.log(
  10259. this.count,
  10260. this.avgTime.toFixed(2),
  10261. (this.endTime - Date.now()) / 1000,
  10262. this.lastTimer.toFixed(2),
  10263. this.lastState.toLocaleString(),
  10264. this.bestResult.value.toLocaleString()
  10265. );
  10266. }
  10267. }
  10268.  
  10269. this.HWHClasses.DungeonFixBattle = DungeonFixBattle;
  10270.  
  10271. const masterWsMixin = {
  10272. wsStart() {
  10273. const socket = new WebSocket(this.url);
  10274.  
  10275. socket.onopen = () => {
  10276. console.log('Connected to server');
  10277.  
  10278. // Пример создания новой задачи
  10279. const newTask = {
  10280. type: 'newTask',
  10281. battle: this.battle,
  10282. endTime: this.endTime - 1e4,
  10283. maxCount: this.maxCount,
  10284. };
  10285. socket.send(JSON.stringify(newTask));
  10286. };
  10287.  
  10288. socket.onmessage = this.onmessage.bind(this);
  10289.  
  10290. socket.onclose = () => {
  10291. console.log('Disconnected from server');
  10292. };
  10293.  
  10294. this.ws = socket;
  10295. },
  10296.  
  10297. onmessage(event) {
  10298. const data = JSON.parse(event.data);
  10299. switch (data.type) {
  10300. case 'newTask': {
  10301. console.log('newTask:', data);
  10302. this.id = data.id;
  10303. this.countExecutor = data.count;
  10304. break;
  10305. }
  10306. case 'getSolTask': {
  10307. console.log('getSolTask:', data);
  10308. this.endFix(data.solutions);
  10309. break;
  10310. }
  10311. case 'resolveTask': {
  10312. console.log('resolveTask:', data);
  10313. if (data.id === this.id && data.solutions.length === this.countExecutor) {
  10314. this.worker.terminate();
  10315. this.endFix(data.solutions);
  10316. }
  10317. break;
  10318. }
  10319. default:
  10320. console.log('Unknown message type:', data.type);
  10321. }
  10322. },
  10323.  
  10324. getTask() {
  10325. this.ws.send(
  10326. JSON.stringify({
  10327. type: 'getSolTask',
  10328. id: this.id,
  10329. })
  10330. );
  10331. },
  10332. };
  10333.  
  10334. /*
  10335. mFix = new action.masterFixBattle(battle)
  10336. await mFix.start(Date.now() + 6e4, 1);
  10337. */
  10338. class masterFixBattle extends FixBattle {
  10339. constructor(battle, url = 'wss://localho.st:3000') {
  10340. super(battle, true);
  10341. this.url = url;
  10342. }
  10343.  
  10344. async start(endTime, maxCount) {
  10345. this.endTime = endTime;
  10346. this.maxCount = maxCount;
  10347. this.init();
  10348. this.wsStart();
  10349. return await new Promise((resolve) => {
  10350. this.resolve = resolve;
  10351. const timeout = this.endTime - Date.now();
  10352. this.timeout(this.getTask.bind(this), timeout);
  10353. });
  10354. }
  10355.  
  10356. async endFix(solutions) {
  10357. this.ws.close();
  10358. let maxCount = 0;
  10359. for (const solution of solutions) {
  10360. maxCount += solution.maxCount;
  10361. if (solution.value > this.bestResult.value) {
  10362. this.bestResult = solution;
  10363. }
  10364. }
  10365. this.count = maxCount;
  10366. super.endFix();
  10367. }
  10368. }
  10369.  
  10370. Object.assign(masterFixBattle.prototype, masterWsMixin);
  10371.  
  10372. this.HWHClasses.masterFixBattle = masterFixBattle;
  10373.  
  10374. class masterWinFixBattle extends WinFixBattle {
  10375. constructor(battle, url = 'wss://localho.st:3000') {
  10376. super(battle, true);
  10377. this.url = url;
  10378. }
  10379.  
  10380. async start(endTime, maxCount) {
  10381. this.endTime = endTime;
  10382. this.maxCount = maxCount;
  10383. this.init();
  10384. this.wsStart();
  10385. return await new Promise((resolve) => {
  10386. this.resolve = resolve;
  10387. const timeout = this.endTime - Date.now();
  10388. this.timeout(this.getTask.bind(this), timeout);
  10389. });
  10390. }
  10391.  
  10392. async endFix(solutions) {
  10393. this.ws.close();
  10394. let maxCount = 0;
  10395. for (const solution of solutions) {
  10396. maxCount += solution.maxCount;
  10397. if (solution.value > this.bestResult.value) {
  10398. this.bestResult = solution;
  10399. }
  10400. }
  10401. this.count = maxCount;
  10402. super.endFix();
  10403. }
  10404. }
  10405.  
  10406. Object.assign(masterWinFixBattle.prototype, masterWsMixin);
  10407.  
  10408. this.HWHClasses.masterWinFixBattle = masterWinFixBattle;
  10409.  
  10410. const slaveWsMixin = {
  10411. wsStop() {
  10412. this.ws.close();
  10413. },
  10414.  
  10415. wsStart() {
  10416. const socket = new WebSocket(this.url);
  10417.  
  10418. socket.onopen = () => {
  10419. console.log('Connected to server');
  10420. };
  10421. socket.onmessage = this.onmessage.bind(this);
  10422. socket.onclose = () => {
  10423. console.log('Disconnected from server');
  10424. };
  10425.  
  10426. this.ws = socket;
  10427. },
  10428.  
  10429. async onmessage(event) {
  10430. const data = JSON.parse(event.data);
  10431. switch (data.type) {
  10432. case 'newTask': {
  10433. console.log('newTask:', data.task);
  10434. const { battle, endTime, maxCount } = data.task;
  10435. this.battle = battle;
  10436. const id = data.task.id;
  10437. const solution = await this.start(endTime, maxCount);
  10438. this.ws.send(
  10439. JSON.stringify({
  10440. type: 'resolveTask',
  10441. id,
  10442. solution,
  10443. })
  10444. );
  10445. break;
  10446. }
  10447. default:
  10448. console.log('Unknown message type:', data.type);
  10449. }
  10450. },
  10451. };
  10452. /*
  10453. sFix = new action.slaveFixBattle();
  10454. sFix.wsStart()
  10455. */
  10456. class slaveFixBattle extends FixBattle {
  10457. constructor(url = 'wss://localho.st:3000') {
  10458. super(null, false);
  10459. this.isTimeout = false;
  10460. this.url = url;
  10461. }
  10462. }
  10463.  
  10464. Object.assign(slaveFixBattle.prototype, slaveWsMixin);
  10465.  
  10466. this.HWHClasses.slaveFixBattle = slaveFixBattle;
  10467.  
  10468. class slaveWinFixBattle extends WinFixBattle {
  10469. constructor(url = 'wss://localho.st:3000') {
  10470. super(null, false);
  10471. this.isTimeout = false;
  10472. this.url = url;
  10473. }
  10474. }
  10475.  
  10476. Object.assign(slaveWinFixBattle.prototype, slaveWsMixin);
  10477.  
  10478. this.HWHClasses.slaveWinFixBattle = slaveWinFixBattle;
  10479. /**
  10480. * Auto-repeat attack
  10481. *
  10482. * Автоповтор атаки
  10483. */
  10484. function testAutoBattle() {
  10485. const { executeAutoBattle } = HWHClasses;
  10486. return new Promise((resolve, reject) => {
  10487. const bossBattle = new executeAutoBattle(resolve, reject);
  10488. bossBattle.start(lastBattleArg, lastBattleInfo);
  10489. });
  10490. }
  10491.  
  10492. /**
  10493. * Auto-repeat attack
  10494. *
  10495. * Автоповтор атаки
  10496. */
  10497. function executeAutoBattle(resolve, reject) {
  10498. let battleArg = {};
  10499. let countBattle = 0;
  10500. let countError = 0;
  10501. let findCoeff = 0;
  10502. let dataNotEeceived = 0;
  10503. let stopAutoBattle = false;
  10504.  
  10505. let isSetWinTimer = false;
  10506. 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>';
  10507. 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>';
  10508. 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>';
  10509.  
  10510. this.start = function (battleArgs, battleInfo) {
  10511. battleArg = battleArgs;
  10512. if (nameFuncStartBattle == 'invasion_bossStart') {
  10513. startBattle();
  10514. return;
  10515. }
  10516. preCalcBattle(battleInfo);
  10517. }
  10518. /**
  10519. * Returns a promise for combat recalculation
  10520. *
  10521. * Возвращает промис для прерасчета боя
  10522. */
  10523. function getBattleInfo(battle) {
  10524. return new Promise(function (resolve) {
  10525. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  10526. Calc(battle).then(e => {
  10527. e.coeff = calcCoeff(e, 'defenders');
  10528. resolve(e);
  10529. });
  10530. });
  10531. }
  10532. /**
  10533. * Battle recalculation
  10534. *
  10535. * Прерасчет боя
  10536. */
  10537. function preCalcBattle(battle) {
  10538. let actions = [];
  10539. const countTestBattle = getInput('countTestBattle');
  10540. for (let i = 0; i < countTestBattle; i++) {
  10541. actions.push(getBattleInfo(battle));
  10542. }
  10543. Promise.all(actions)
  10544. .then(resultPreCalcBattle);
  10545. }
  10546. /**
  10547. * Processing the results of the battle recalculation
  10548. *
  10549. * Обработка результатов прерасчета боя
  10550. */
  10551. async function resultPreCalcBattle(results) {
  10552. let countWin = results.reduce((s, w) => w.result.win + s, 0);
  10553. setProgress(`${I18N('CHANCE_TO_WIN')} ${Math.floor(countWin / results.length * 100)}% (${results.length})`, false, hideProgress);
  10554. if (countWin > 0) {
  10555. setIsCancalBattle(false);
  10556. startBattle();
  10557. return;
  10558. }
  10559.  
  10560. let minCoeff = 100;
  10561. let maxCoeff = -100;
  10562. let avgCoeff = 0;
  10563. results.forEach(e => {
  10564. if (e.coeff < minCoeff) minCoeff = e.coeff;
  10565. if (e.coeff > maxCoeff) maxCoeff = e.coeff;
  10566. avgCoeff += e.coeff;
  10567. });
  10568. avgCoeff /= results.length;
  10569.  
  10570. if (nameFuncStartBattle == 'invasion_bossStart' ||
  10571. nameFuncStartBattle == 'bossAttack') {
  10572. const result = await popup.confirm(
  10573. I18N('BOSS_VICTORY_IMPOSSIBLE', { battles: results.length }), [
  10574. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  10575. { msg: I18N('BTN_DO_IT'), result: true },
  10576. ])
  10577. if (result) {
  10578. setIsCancalBattle(false);
  10579. startBattle();
  10580. return;
  10581. }
  10582. setProgress(I18N('NOT_THIS_TIME'), true);
  10583. endAutoBattle('invasion_bossStart');
  10584. return;
  10585. }
  10586.  
  10587. const result = await popup.confirm(
  10588. I18N('VICTORY_IMPOSSIBLE') +
  10589. `<br>${I18N('ROUND_STAT')} ${results.length} ${I18N('BATTLE')}:` +
  10590. `<br>${I18N('MINIMUM')}: ` + minCoeff.toLocaleString() +
  10591. `<br>${I18N('MAXIMUM')}: ` + maxCoeff.toLocaleString() +
  10592. `<br>${I18N('AVERAGE')}: ` + avgCoeff.toLocaleString() +
  10593. `<br>${I18N('FIND_COEFF')} ` + avgCoeff.toLocaleString(), [
  10594. { msg: I18N('BTN_CANCEL'), result: 0, isCancel: true },
  10595. { msg: I18N('BTN_GO'), isInput: true, default: Math.round(avgCoeff * 1000) / 1000 },
  10596. ])
  10597. if (result) {
  10598. findCoeff = result;
  10599. setIsCancalBattle(false);
  10600. startBattle();
  10601. return;
  10602. }
  10603. setProgress(I18N('NOT_THIS_TIME'), true);
  10604. endAutoBattle(I18N('NOT_THIS_TIME'));
  10605. }
  10606.  
  10607. /**
  10608. * Calculation of the combat result coefficient
  10609. *
  10610. * Расчет коэфициента результата боя
  10611. */
  10612. function calcCoeff(result, packType) {
  10613. let beforeSumFactor = 0;
  10614. const beforePack = result.battleData[packType][0];
  10615. for (let heroId in beforePack) {
  10616. const hero = beforePack[heroId];
  10617. const state = hero.state;
  10618. let factor = 1;
  10619. if (state) {
  10620. const hp = state.hp / state.maxHp;
  10621. const energy = state.energy / 1e3;
  10622. factor = hp + energy / 20;
  10623. }
  10624. beforeSumFactor += factor;
  10625. }
  10626.  
  10627. let afterSumFactor = 0;
  10628. const afterPack = result.progress[0][packType].heroes;
  10629. for (let heroId in afterPack) {
  10630. const hero = afterPack[heroId];
  10631. const stateHp = beforePack[heroId]?.state?.hp || beforePack[heroId]?.stats?.hp;
  10632. const hp = hero.hp / stateHp;
  10633. const energy = hero.energy / 1e3;
  10634. const factor = hp + energy / 20;
  10635. afterSumFactor += factor;
  10636. }
  10637. const resultCoeff = -(afterSumFactor - beforeSumFactor);
  10638. return Math.round(resultCoeff * 1000) / 1000;
  10639. }
  10640. /**
  10641. * Start battle
  10642. *
  10643. * Начало боя
  10644. */
  10645. function startBattle() {
  10646. countBattle++;
  10647. const countMaxBattle = getInput('countAutoBattle');
  10648. // setProgress(countBattle + '/' + countMaxBattle);
  10649. if (countBattle > countMaxBattle) {
  10650. setProgress(`${I18N('RETRY_LIMIT_EXCEEDED')}: ${countMaxBattle}`, true);
  10651. endAutoBattle(`${I18N('RETRY_LIMIT_EXCEEDED')}: ${countMaxBattle}`)
  10652. return;
  10653. }
  10654. if (stopAutoBattle) {
  10655. setProgress(I18N('STOPPED'), true);
  10656. endAutoBattle('STOPPED');
  10657. return;
  10658. }
  10659. send({calls: [{
  10660. name: nameFuncStartBattle,
  10661. args: battleArg,
  10662. ident: "body"
  10663. }]}, calcResultBattle);
  10664. }
  10665. /**
  10666. * Battle calculation
  10667. *
  10668. * Расчет боя
  10669. */
  10670. async function calcResultBattle(e) {
  10671. if (!e) {
  10672. console.log('данные не были получены');
  10673. if (dataNotEeceived < 10) {
  10674. dataNotEeceived++;
  10675. startBattle();
  10676. return;
  10677. }
  10678. endAutoBattle('Error', 'данные не были получены ' + dataNotEeceived + ' раз');
  10679. return;
  10680. }
  10681. if ('error' in e) {
  10682. if (e.error.description === 'too many tries') {
  10683. invasionTimer += 100;
  10684. countBattle--;
  10685. countError++;
  10686. console.log(`Errors: ${countError}`, e.error);
  10687. startBattle();
  10688. return;
  10689. }
  10690. const result = await popup.confirm(I18N('ERROR_DURING_THE_BATTLE') + '<br>' + e.error.description, [
  10691. { msg: I18N('BTN_OK'), result: false },
  10692. { msg: I18N('RELOAD_GAME'), result: true },
  10693. ]);
  10694. endAutoBattle('Error', e.error);
  10695. if (result) {
  10696. location.reload();
  10697. }
  10698. return;
  10699. }
  10700. let battle = e.results[0].result.response.battle
  10701. if (nameFuncStartBattle == 'towerStartBattle' ||
  10702. nameFuncStartBattle == 'bossAttack' ||
  10703. nameFuncStartBattle == 'invasion_bossStart') {
  10704. battle = e.results[0].result.response;
  10705. }
  10706. lastBattleInfo = battle;
  10707. BattleCalc(battle, getBattleType(battle.type), resultBattle);
  10708. }
  10709. /**
  10710. * Processing the results of the battle
  10711. *
  10712. * Обработка результатов боя
  10713. */
  10714. async function resultBattle(e) {
  10715. const isWin = e.result.win;
  10716. if (isWin) {
  10717. endBattle(e, false);
  10718. return;
  10719. } else if (isChecked('tryFixIt_v2')) {
  10720. const { WinFixBattle } = HWHClasses;
  10721. const cloneBattle = structuredClone(e.battleData);
  10722. const bFix = new WinFixBattle(cloneBattle);
  10723. let attempts = Infinity;
  10724. if (nameFuncStartBattle == 'invasion_bossStart' && !isSetWinTimer) {
  10725. let winTimer = await popup.confirm(`Secret number:`, [
  10726. { result: false, isClose: true },
  10727. { msg: 'Go', isInput: true, default: '0' },
  10728. ]);
  10729. winTimer = Number.parseFloat(winTimer);
  10730. if (winTimer) {
  10731. attempts = 5;
  10732. bFix.setWinTimer(winTimer);
  10733. }
  10734. isSetWinTimer = true;
  10735. }
  10736. let endTime = Date.now() + 6e4;
  10737. if (nameFuncStartBattle == 'invasion_bossStart') {
  10738. endTime = Date.now() + 6e4 * 4;
  10739. bFix.setMaxTimer(120.3);
  10740. }
  10741. const result = await bFix.start(endTime, attempts);
  10742. console.log(result);
  10743. if (result.value) {
  10744. endBattle(result, false);
  10745. return;
  10746. }
  10747. }
  10748. const countMaxBattle = getInput('countAutoBattle');
  10749. if (findCoeff) {
  10750. const coeff = calcCoeff(e, 'defenders');
  10751. setProgress(`${countBattle}/${countMaxBattle}, ${coeff}`);
  10752. if (coeff > findCoeff) {
  10753. endBattle(e, false);
  10754. return;
  10755. }
  10756. } else {
  10757. if (nameFuncStartBattle == 'invasion_bossStart') {
  10758. const bossLvl = lastBattleInfo.typeId >= 130 ? lastBattleInfo.typeId : '';
  10759. const justice = lastBattleInfo?.effects?.attackers?.percentInOutDamageModAndEnergyIncrease_any_99_100_300_99_1000_300 || 0;
  10760. setProgress(`${svgBoss} ${bossLvl} ${svgJustice} ${justice} <br>${svgAttempt} ${countBattle}/${countMaxBattle}`, false, () => {
  10761. stopAutoBattle = true;
  10762. });
  10763. await new Promise((resolve) => setTimeout(resolve, 5000));
  10764. } else {
  10765. setProgress(`${countBattle}/${countMaxBattle}`);
  10766. }
  10767. }
  10768. if (nameFuncStartBattle == 'towerStartBattle' ||
  10769. nameFuncStartBattle == 'bossAttack' ||
  10770. nameFuncStartBattle == 'invasion_bossStart') {
  10771. startBattle();
  10772. return;
  10773. }
  10774. cancelEndBattle(e);
  10775. }
  10776. /**
  10777. * Cancel fight
  10778. *
  10779. * Отмена боя
  10780. */
  10781. function cancelEndBattle(r) {
  10782. const fixBattle = function (heroes) {
  10783. for (const ids in heroes) {
  10784. hero = heroes[ids];
  10785. hero.energy = random(1, 999);
  10786. if (hero.hp > 0) {
  10787. hero.hp = random(1, hero.hp);
  10788. }
  10789. }
  10790. }
  10791. fixBattle(r.progress[0].attackers.heroes);
  10792. fixBattle(r.progress[0].defenders.heroes);
  10793. endBattle(r, true);
  10794. }
  10795. /**
  10796. * End of the fight
  10797. *
  10798. * Завершение боя */
  10799. function endBattle(battleResult, isCancal) {
  10800. let calls = [{
  10801. name: nameFuncEndBattle,
  10802. args: {
  10803. result: battleResult.result,
  10804. progress: battleResult.progress
  10805. },
  10806. ident: "body"
  10807. }];
  10808.  
  10809. if (nameFuncStartBattle == 'invasion_bossStart') {
  10810. calls[0].args.id = lastBattleArg.id;
  10811. }
  10812.  
  10813. send(JSON.stringify({
  10814. calls
  10815. }), async e => {
  10816. console.log(e);
  10817. if (isCancal) {
  10818. startBattle();
  10819. return;
  10820. }
  10821.  
  10822. setProgress(`${I18N('SUCCESS')}!`, 5000)
  10823. if (nameFuncStartBattle == 'invasion_bossStart' ||
  10824. nameFuncStartBattle == 'bossAttack') {
  10825. const countMaxBattle = getInput('countAutoBattle');
  10826. const bossLvl = lastBattleInfo.typeId >= 130 ? lastBattleInfo.typeId : '';
  10827. const justice = lastBattleInfo?.effects?.attackers?.percentInOutDamageModAndEnergyIncrease_any_99_100_300_99_1000_300 || 0;
  10828. let winTimer = '';
  10829. if (nameFuncStartBattle == 'invasion_bossStart') {
  10830. winTimer = '<br>Secret number: ' + battleResult.progress[0].attackers.input[5];
  10831. }
  10832. const result = await popup.confirm(
  10833. I18N('BOSS_HAS_BEEN_DEF_TEXT', {
  10834. bossLvl: `${svgBoss} ${bossLvl} ${svgJustice} ${justice}`,
  10835. countBattle: svgAttempt + ' ' + countBattle,
  10836. countMaxBattle,
  10837. winTimer,
  10838. }),
  10839. [
  10840. { msg: I18N('BTN_OK'), result: 0 },
  10841. { msg: I18N('MAKE_A_SYNC'), result: 1 },
  10842. { msg: I18N('RELOAD_GAME'), result: 2 },
  10843. ]
  10844. );
  10845. if (result) {
  10846. if (result == 1) {
  10847. cheats.refreshGame();
  10848. }
  10849. if (result == 2) {
  10850. location.reload();
  10851. }
  10852. }
  10853.  
  10854. }
  10855. endAutoBattle(`${I18N('SUCCESS')}!`)
  10856. });
  10857. }
  10858. /**
  10859. * Completing a task
  10860. *
  10861. * Завершение задачи
  10862. */
  10863. function endAutoBattle(reason, info) {
  10864. setIsCancalBattle(true);
  10865. console.log(reason, info);
  10866. resolve();
  10867. }
  10868. }
  10869.  
  10870. this.HWHClasses.executeAutoBattle = executeAutoBattle;
  10871.  
  10872. function testDailyQuests() {
  10873. const { dailyQuests } = HWHClasses;
  10874. return new Promise((resolve, reject) => {
  10875. const quests = new dailyQuests(resolve, reject);
  10876. quests.init(questsInfo);
  10877. quests.start();
  10878. });
  10879. }
  10880.  
  10881. /**
  10882. * Automatic completion of daily quests
  10883. *
  10884. * Автоматическое выполнение ежедневных квестов
  10885. */
  10886. class dailyQuests {
  10887. /**
  10888. * Send(' {"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}').then(e => console.log(e))
  10889. * Send(' {"calls":[{"name":"heroGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  10890. * Send(' {"calls":[{"name":"titanGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  10891. * Send(' {"calls":[{"name":"inventoryGet","args":{},"ident":"body"}]}').then(e => console.log(e))
  10892. * Send(' {"calls":[{"name":"questGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  10893. * Send(' {"calls":[{"name":"bossGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  10894. */
  10895. callsList = ['userGetInfo', 'heroGetAll', 'titanGetAll', 'inventoryGet', 'questGetAll', 'bossGetAll', 'missionGetAll'];
  10896.  
  10897. dataQuests = {
  10898. 10001: {
  10899. description: 'Улучши умения героев 3 раза', // ++++++++++++++++
  10900. doItCall: () => {
  10901. const upgradeSkills = this.getUpgradeSkills();
  10902. return upgradeSkills.map(({ heroId, skill }, index) => ({
  10903. name: 'heroUpgradeSkill',
  10904. args: { heroId, skill },
  10905. ident: `heroUpgradeSkill_${index}`,
  10906. }));
  10907. },
  10908. isWeCanDo: () => {
  10909. const upgradeSkills = this.getUpgradeSkills();
  10910. let sumGold = 0;
  10911. for (const skill of upgradeSkills) {
  10912. sumGold += this.skillCost(skill.value);
  10913. if (!skill.heroId) {
  10914. return false;
  10915. }
  10916. }
  10917. return this.questInfo['userGetInfo'].gold > sumGold;
  10918. },
  10919. },
  10920. 10002: {
  10921. description: 'Пройди 10 миссий', // --------------
  10922. isWeCanDo: () => false,
  10923. },
  10924. 10003: {
  10925. description: 'Пройди 3 героические миссии', // ++++++++++++++++
  10926. isWeCanDo: () => {
  10927. const vipPoints = +this.questInfo.userGetInfo.vipPoints;
  10928. const goldTicket = !!this.questInfo.inventoryGet.consumable[151];
  10929. return (vipPoints > 100 || goldTicket) && this.getHeroicMissionId();
  10930. },
  10931. doItCall: () => {
  10932. const selectedMissionId = this.getHeroicMissionId();
  10933. const goldTicket = !!this.questInfo.inventoryGet.consumable[151];
  10934. const vipLevel = Math.max(...lib.data.level.vip.filter(l => l.vipPoints <= +this.questInfo.userGetInfo.vipPoints).map(l => l.level));
  10935. // Возвращаем массив команд для рейда
  10936. if (vipLevel >= 5 || goldTicket) {
  10937. return [{ name: 'missionRaid', args: { id: selectedMissionId, times: 3 }, ident: 'missionRaid_1' }];
  10938. } else {
  10939. return [
  10940. { name: 'missionRaid', args: { id: selectedMissionId, times: 1 }, ident: 'missionRaid_1' },
  10941. { name: 'missionRaid', args: { id: selectedMissionId, times: 1 }, ident: 'missionRaid_2' },
  10942. { name: 'missionRaid', args: { id: selectedMissionId, times: 1 }, ident: 'missionRaid_3' },
  10943. ];
  10944. }
  10945. },
  10946. },
  10947. 10004: {
  10948. description: 'Сразись 3 раза на Арене или Гранд Арене', // --------------
  10949. isWeCanDo: () => false,
  10950. },
  10951. 10006: {
  10952. description: 'Используй обмен изумрудов 1 раз', // ++++++++++++++++
  10953. doItCall: () => [
  10954. {
  10955. name: 'refillableAlchemyUse',
  10956. args: { multi: false },
  10957. ident: 'refillableAlchemyUse',
  10958. },
  10959. ],
  10960. isWeCanDo: () => {
  10961. const starMoney = this.questInfo['userGetInfo'].starMoney;
  10962. return starMoney >= 20;
  10963. },
  10964. },
  10965. 10007: {
  10966. description: 'Соверши 1 призыв в Атриуме Душ', // ++++++++++++++++
  10967. doItCall: () => [{ name: 'gacha_open', args: { ident: 'heroGacha', free: true, pack: false }, ident: 'gacha_open' }],
  10968. isWeCanDo: () => {
  10969. const soulCrystal = this.questInfo['inventoryGet'].coin[38];
  10970. return soulCrystal > 0;
  10971. },
  10972. },
  10973. 10016: {
  10974. description: 'Отправь подарки согильдийцам', // ++++++++++++++++
  10975. doItCall: () => [{ name: 'clanSendDailyGifts', args: {}, ident: 'clanSendDailyGifts' }],
  10976. isWeCanDo: () => true,
  10977. },
  10978. 10018: {
  10979. description: 'Используй зелье опыта', // ++++++++++++++++
  10980. doItCall: () => {
  10981. const expHero = this.getExpHero();
  10982. return [
  10983. {
  10984. name: 'consumableUseHeroXp',
  10985. args: {
  10986. heroId: expHero.heroId,
  10987. libId: expHero.libId,
  10988. amount: 1,
  10989. },
  10990. ident: 'consumableUseHeroXp',
  10991. },
  10992. ];
  10993. },
  10994. isWeCanDo: () => {
  10995. const expHero = this.getExpHero();
  10996. return expHero.heroId && expHero.libId;
  10997. },
  10998. },
  10999. 10019: {
  11000. description: 'Открой 1 сундук в Башне',
  11001. doItFunc: testTower,
  11002. isWeCanDo: () => false,
  11003. },
  11004. 10020: {
  11005. description: 'Открой 3 сундука в Запределье', // Готово
  11006. doItCall: () => {
  11007. return this.getOutlandChest();
  11008. },
  11009. isWeCanDo: () => {
  11010. const outlandChest = this.getOutlandChest();
  11011. return outlandChest.length > 0;
  11012. },
  11013. },
  11014. 10021: {
  11015. description: 'Собери 75 Титанита в Подземелье Гильдии',
  11016. isWeCanDo: () => false,
  11017. },
  11018. 10022: {
  11019. description: 'Собери 150 Титанита в Подземелье Гильдии',
  11020. doItFunc: testDungeon,
  11021. isWeCanDo: () => false,
  11022. },
  11023. 10023: {
  11024. description: 'Прокачай Дар Стихий на 1 уровень', // Готово
  11025. doItCall: () => {
  11026. const heroId = this.getHeroIdTitanGift();
  11027. return [
  11028. { name: 'heroTitanGiftLevelUp', args: { heroId }, ident: 'heroTitanGiftLevelUp' },
  11029. { name: 'heroTitanGiftDrop', args: { heroId }, ident: 'heroTitanGiftDrop' },
  11030. ];
  11031. },
  11032. isWeCanDo: () => {
  11033. const heroId = this.getHeroIdTitanGift();
  11034. return heroId;
  11035. },
  11036. },
  11037. 10024: {
  11038. description: 'Повысь уровень любого артефакта один раз', // Готово
  11039. doItCall: () => {
  11040. const upArtifact = this.getUpgradeArtifact();
  11041. return [
  11042. {
  11043. name: 'heroArtifactLevelUp',
  11044. args: {
  11045. heroId: upArtifact.heroId,
  11046. slotId: upArtifact.slotId,
  11047. },
  11048. ident: `heroArtifactLevelUp`,
  11049. },
  11050. ];
  11051. },
  11052. isWeCanDo: () => {
  11053. const upgradeArtifact = this.getUpgradeArtifact();
  11054. return upgradeArtifact.heroId;
  11055. },
  11056. },
  11057. 10025: {
  11058. description: 'Начни 1 Экспедицию',
  11059. doItFunc: checkExpedition,
  11060. isWeCanDo: () => false,
  11061. },
  11062. 10026: {
  11063. description: 'Начни 4 Экспедиции', // --------------
  11064. doItFunc: checkExpedition,
  11065. isWeCanDo: () => false,
  11066. },
  11067. 10027: {
  11068. description: 'Победи в 1 бою Турнира Стихий',
  11069. doItFunc: testTitanArena,
  11070. isWeCanDo: () => false,
  11071. },
  11072. 10028: {
  11073. description: 'Повысь уровень любого артефакта титанов', // Готово
  11074. doItCall: () => {
  11075. const upTitanArtifact = this.getUpgradeTitanArtifact();
  11076. return [
  11077. {
  11078. name: 'titanArtifactLevelUp',
  11079. args: {
  11080. titanId: upTitanArtifact.titanId,
  11081. slotId: upTitanArtifact.slotId,
  11082. },
  11083. ident: `titanArtifactLevelUp`,
  11084. },
  11085. ];
  11086. },
  11087. isWeCanDo: () => {
  11088. const upgradeTitanArtifact = this.getUpgradeTitanArtifact();
  11089. return upgradeTitanArtifact.titanId;
  11090. },
  11091. },
  11092. 10029: {
  11093. description: 'Открой сферу артефактов титанов', // ++++++++++++++++
  11094. doItCall: () => [{ name: 'titanArtifactChestOpen', args: { amount: 1, free: true }, ident: 'titanArtifactChestOpen' }],
  11095. isWeCanDo: () => {
  11096. return this.questInfo['inventoryGet']?.consumable[55] > 0;
  11097. },
  11098. },
  11099. 10030: {
  11100. description: 'Улучши облик любого героя 1 раз', // Готово
  11101. doItCall: () => {
  11102. const upSkin = this.getUpgradeSkin();
  11103. return [
  11104. {
  11105. name: 'heroSkinUpgrade',
  11106. args: {
  11107. heroId: upSkin.heroId,
  11108. skinId: upSkin.skinId,
  11109. },
  11110. ident: `heroSkinUpgrade`,
  11111. },
  11112. ];
  11113. },
  11114. isWeCanDo: () => {
  11115. const upgradeSkin = this.getUpgradeSkin();
  11116. return upgradeSkin.heroId;
  11117. },
  11118. },
  11119. 10031: {
  11120. description: 'Победи в 6 боях Турнира Стихий', // --------------
  11121. doItFunc: testTitanArena,
  11122. isWeCanDo: () => false,
  11123. },
  11124. 10043: {
  11125. description: 'Начни или присоеденись к Приключению', // --------------
  11126. isWeCanDo: () => false,
  11127. },
  11128. 10044: {
  11129. description: 'Воспользуйся призывом питомцев 1 раз', // ++++++++++++++++
  11130. doItCall: () => [{ name: 'pet_chestOpen', args: { amount: 1, paid: false }, ident: 'pet_chestOpen' }],
  11131. isWeCanDo: () => {
  11132. return this.questInfo['inventoryGet']?.consumable[90] > 0;
  11133. },
  11134. },
  11135. 10046: {
  11136. /**
  11137. * TODO: Watch Adventure
  11138. * TODO: Смотреть приключение
  11139. */
  11140. description: 'Открой 3 сундука в Приключениях',
  11141. isWeCanDo: () => false,
  11142. },
  11143. 10047: {
  11144. description: 'Набери 150 очков активности в Гильдии', // Готово
  11145. doItCall: () => {
  11146. const enchantRune = this.getEnchantRune();
  11147. return [
  11148. {
  11149. name: 'heroEnchantRune',
  11150. args: {
  11151. heroId: enchantRune.heroId,
  11152. tier: enchantRune.tier,
  11153. items: {
  11154. consumable: { [enchantRune.itemId]: 1 },
  11155. },
  11156. },
  11157. ident: `heroEnchantRune`,
  11158. },
  11159. ];
  11160. },
  11161. isWeCanDo: () => {
  11162. const userInfo = this.questInfo['userGetInfo'];
  11163. const enchantRune = this.getEnchantRune();
  11164. return enchantRune.heroId && userInfo.gold > 1e3;
  11165. },
  11166. },
  11167. };
  11168.  
  11169. constructor(resolve, reject, questInfo) {
  11170. this.resolve = resolve;
  11171. this.reject = reject;
  11172. }
  11173.  
  11174. init(questInfo) {
  11175. this.questInfo = questInfo;
  11176. this.isAuto = false;
  11177. }
  11178.  
  11179. async autoInit(isAuto) {
  11180. this.isAuto = isAuto || false;
  11181. const quests = {};
  11182. const calls = this.callsList.map((name) => ({
  11183. name,
  11184. args: {},
  11185. ident: name,
  11186. }));
  11187. const result = await Send(JSON.stringify({ calls })).then((e) => e.results);
  11188. for (const call of result) {
  11189. quests[call.ident] = call.result.response;
  11190. }
  11191. this.questInfo = quests;
  11192. }
  11193.  
  11194. async start() {
  11195. const weCanDo = [];
  11196. const selectedActions = getSaveVal('selectedActions', {});
  11197. for (let quest of this.questInfo['questGetAll']) {
  11198. if (quest.id in this.dataQuests && quest.state == 1) {
  11199. if (!selectedActions[quest.id]) {
  11200. selectedActions[quest.id] = {
  11201. checked: false,
  11202. };
  11203. }
  11204.  
  11205. const isWeCanDo = this.dataQuests[quest.id].isWeCanDo;
  11206. if (!isWeCanDo.call(this)) {
  11207. continue;
  11208. }
  11209.  
  11210. weCanDo.push({
  11211. name: quest.id,
  11212. label: I18N(`QUEST_${quest.id}`),
  11213. checked: selectedActions[quest.id].checked,
  11214. });
  11215. }
  11216. }
  11217.  
  11218. if (!weCanDo.length) {
  11219. this.end(I18N('NOTHING_TO_DO'));
  11220. return;
  11221. }
  11222.  
  11223. console.log(weCanDo);
  11224. let taskList = [];
  11225. if (this.isAuto) {
  11226. taskList = weCanDo;
  11227. } else {
  11228. const answer = await popup.confirm(
  11229. `${I18N('YOU_CAN_COMPLETE')}:`,
  11230. [
  11231. { msg: I18N('BTN_DO_IT'), result: true },
  11232. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  11233. ],
  11234. weCanDo
  11235. );
  11236. if (!answer) {
  11237. this.end('');
  11238. return;
  11239. }
  11240. taskList = popup.getCheckBoxes();
  11241. taskList.forEach((e) => {
  11242. selectedActions[e.name].checked = e.checked;
  11243. });
  11244. setSaveVal('selectedActions', selectedActions);
  11245. }
  11246.  
  11247. const calls = [];
  11248. let countChecked = 0;
  11249. for (const task of taskList) {
  11250. if (task.checked) {
  11251. countChecked++;
  11252. const quest = this.dataQuests[task.name];
  11253. console.log(quest.description);
  11254.  
  11255. if (quest.doItCall) {
  11256. const doItCall = quest.doItCall.call(this);
  11257. calls.push(...doItCall);
  11258. }
  11259. }
  11260. }
  11261.  
  11262. if (!countChecked) {
  11263. this.end(I18N('NOT_QUEST_COMPLETED'));
  11264. return;
  11265. }
  11266.  
  11267. const result = await Send(JSON.stringify({ calls }));
  11268. if (result.error) {
  11269. console.error(result.error, result.error.call);
  11270. }
  11271. this.end(`${I18N('COMPLETED_QUESTS')}: ${countChecked}`);
  11272. }
  11273.  
  11274. errorHandling(error) {
  11275. //console.error(error);
  11276. let errorInfo = error.toString() + '\n';
  11277. try {
  11278. const errorStack = error.stack.split('\n');
  11279. const endStack = errorStack.map((e) => e.split('@')[0]).indexOf('testDoYourBest');
  11280. errorInfo += errorStack.slice(0, endStack).join('\n');
  11281. } catch (e) {
  11282. errorInfo += error.stack;
  11283. }
  11284. copyText(errorInfo);
  11285. }
  11286.  
  11287. skillCost(lvl) {
  11288. return 573 * lvl ** 0.9 + lvl ** 2.379;
  11289. }
  11290.  
  11291. getUpgradeSkills() {
  11292. const heroes = Object.values(this.questInfo['heroGetAll']);
  11293. const upgradeSkills = [
  11294. { heroId: 0, slotId: 0, value: 130 },
  11295. { heroId: 0, slotId: 0, value: 130 },
  11296. { heroId: 0, slotId: 0, value: 130 },
  11297. ];
  11298. const skillLib = lib.getData('skill');
  11299. /**
  11300. * color - 1 (белый) открывает 1 навык
  11301. * color - 2 (зеленый) открывает 2 навык
  11302. * color - 4 (синий) открывает 3 навык
  11303. * color - 7 (фиолетовый) открывает 4 навык
  11304. */
  11305. const colors = [1, 2, 4, 7];
  11306. for (const hero of heroes) {
  11307. const level = hero.level;
  11308. const color = hero.color;
  11309. for (let skillId in hero.skills) {
  11310. const tier = skillLib[skillId].tier;
  11311. const sVal = hero.skills[skillId];
  11312. if (color < colors[tier] || tier < 1 || tier > 4) {
  11313. continue;
  11314. }
  11315. for (let upSkill of upgradeSkills) {
  11316. if (sVal < upSkill.value && sVal < level) {
  11317. upSkill.value = sVal;
  11318. upSkill.heroId = hero.id;
  11319. upSkill.skill = tier;
  11320. break;
  11321. }
  11322. }
  11323. }
  11324. }
  11325. return upgradeSkills;
  11326. }
  11327.  
  11328. getUpgradeArtifact() {
  11329. const heroes = Object.values(this.questInfo['heroGetAll']);
  11330. const inventory = this.questInfo['inventoryGet'];
  11331. const upArt = { heroId: 0, slotId: 0, level: 100 };
  11332.  
  11333. const heroLib = lib.getData('hero');
  11334. const artifactLib = lib.getData('artifact');
  11335.  
  11336. for (const hero of heroes) {
  11337. const heroInfo = heroLib[hero.id];
  11338. const level = hero.level;
  11339. if (level < 20) {
  11340. continue;
  11341. }
  11342.  
  11343. for (let slotId in hero.artifacts) {
  11344. const art = hero.artifacts[slotId];
  11345. /* Текущая звезданость арта */
  11346. const star = art.star;
  11347. if (!star) {
  11348. continue;
  11349. }
  11350. /* Текущий уровень арта */
  11351. const level = art.level;
  11352. if (level >= 100) {
  11353. continue;
  11354. }
  11355. /* Идентификатор арта в библиотеке */
  11356. const artifactId = heroInfo.artifacts[slotId];
  11357. const artInfo = artifactLib.id[artifactId];
  11358. const costNextLevel = artifactLib.type[artInfo.type].levels[level + 1].cost;
  11359.  
  11360. const costCurrency = Object.keys(costNextLevel).pop();
  11361. const costValues = Object.entries(costNextLevel[costCurrency]).pop();
  11362. const costId = costValues[0];
  11363. const costValue = +costValues[1];
  11364.  
  11365. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  11366. if (level < upArt.level && inventory[costCurrency][costId] >= costValue) {
  11367. upArt.level = level;
  11368. upArt.heroId = hero.id;
  11369. upArt.slotId = slotId;
  11370. upArt.costCurrency = costCurrency;
  11371. upArt.costId = costId;
  11372. upArt.costValue = costValue;
  11373. }
  11374. }
  11375. }
  11376. return upArt;
  11377. }
  11378.  
  11379. getUpgradeSkin() {
  11380. const heroes = Object.values(this.questInfo['heroGetAll']);
  11381. const inventory = this.questInfo['inventoryGet'];
  11382. const upSkin = { heroId: 0, skinId: 0, level: 60, cost: 1500 };
  11383.  
  11384. const skinLib = lib.getData('skin');
  11385.  
  11386. for (const hero of heroes) {
  11387. const level = hero.level;
  11388. if (level < 20) {
  11389. continue;
  11390. }
  11391.  
  11392. for (let skinId in hero.skins) {
  11393. /* Текущий уровень скина */
  11394. const level = hero.skins[skinId];
  11395. if (level >= 60) {
  11396. continue;
  11397. }
  11398. /* Идентификатор скина в библиотеке */
  11399. const skinInfo = skinLib[skinId];
  11400. if (!skinInfo.statData.levels?.[level + 1]) {
  11401. continue;
  11402. }
  11403. const costNextLevel = skinInfo.statData.levels[level + 1].cost;
  11404.  
  11405. const costCurrency = Object.keys(costNextLevel).pop();
  11406. const costCurrencyId = Object.keys(costNextLevel[costCurrency]).pop();
  11407. const costValue = +costNextLevel[costCurrency][costCurrencyId];
  11408.  
  11409. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  11410. if (level < upSkin.level && costValue < upSkin.cost && inventory[costCurrency][costCurrencyId] >= costValue) {
  11411. upSkin.cost = costValue;
  11412. upSkin.level = level;
  11413. upSkin.heroId = hero.id;
  11414. upSkin.skinId = skinId;
  11415. upSkin.costCurrency = costCurrency;
  11416. upSkin.costCurrencyId = costCurrencyId;
  11417. }
  11418. }
  11419. }
  11420. return upSkin;
  11421. }
  11422.  
  11423. getUpgradeTitanArtifact() {
  11424. const titans = Object.values(this.questInfo['titanGetAll']);
  11425. const inventory = this.questInfo['inventoryGet'];
  11426. const userInfo = this.questInfo['userGetInfo'];
  11427. const upArt = { titanId: 0, slotId: 0, level: 120 };
  11428.  
  11429. const titanLib = lib.getData('titan');
  11430. const artTitanLib = lib.getData('titanArtifact');
  11431.  
  11432. for (const titan of titans) {
  11433. const titanInfo = titanLib[titan.id];
  11434. // const level = titan.level
  11435. // if (level < 20) {
  11436. // continue;
  11437. // }
  11438.  
  11439. for (let slotId in titan.artifacts) {
  11440. const art = titan.artifacts[slotId];
  11441. /* Текущая звезданость арта */
  11442. const star = art.star;
  11443. if (!star) {
  11444. continue;
  11445. }
  11446. /* Текущий уровень арта */
  11447. const level = art.level;
  11448. if (level >= 120) {
  11449. continue;
  11450. }
  11451. /* Идентификатор арта в библиотеке */
  11452. const artifactId = titanInfo.artifacts[slotId];
  11453. const artInfo = artTitanLib.id[artifactId];
  11454. const costNextLevel = artTitanLib.type[artInfo.type].levels[level + 1].cost;
  11455.  
  11456. const costCurrency = Object.keys(costNextLevel).pop();
  11457. let costValue = 0;
  11458. let currentValue = 0;
  11459. if (costCurrency == 'gold') {
  11460. costValue = costNextLevel[costCurrency];
  11461. currentValue = userInfo.gold;
  11462. } else {
  11463. const costValues = Object.entries(costNextLevel[costCurrency]).pop();
  11464. const costId = costValues[0];
  11465. costValue = +costValues[1];
  11466. currentValue = inventory[costCurrency][costId];
  11467. }
  11468.  
  11469. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  11470. if (level < upArt.level && currentValue >= costValue) {
  11471. upArt.level = level;
  11472. upArt.titanId = titan.id;
  11473. upArt.slotId = slotId;
  11474. break;
  11475. }
  11476. }
  11477. }
  11478. return upArt;
  11479. }
  11480.  
  11481. getEnchantRune() {
  11482. const heroes = Object.values(this.questInfo['heroGetAll']);
  11483. const inventory = this.questInfo['inventoryGet'];
  11484. const enchRune = { heroId: 0, tier: 0, exp: 43750, itemId: 0 };
  11485. for (let i = 1; i <= 4; i++) {
  11486. if (inventory.consumable[i] > 0) {
  11487. enchRune.itemId = i;
  11488. break;
  11489. }
  11490. return enchRune;
  11491. }
  11492.  
  11493. const runeLib = lib.getData('rune');
  11494. const runeLvls = Object.values(runeLib.level);
  11495. /**
  11496. * color - 4 (синий) открывает 1 и 2 символ
  11497. * color - 7 (фиолетовый) открывает 3 символ
  11498. * color - 8 (фиолетовый +1) открывает 4 символ
  11499. * color - 9 (фиолетовый +2) открывает 5 символ
  11500. */
  11501. // TODO: кажется надо учесть уровень команды
  11502. const colors = [4, 4, 7, 8, 9];
  11503. for (const hero of heroes) {
  11504. const color = hero.color;
  11505.  
  11506. for (let runeTier in hero.runes) {
  11507. /* Проверка на доступность руны */
  11508. if (color < colors[runeTier]) {
  11509. continue;
  11510. }
  11511. /* Текущий опыт руны */
  11512. const exp = hero.runes[runeTier];
  11513. if (exp >= 43750) {
  11514. continue;
  11515. }
  11516.  
  11517. let level = 0;
  11518. if (exp) {
  11519. for (let lvl of runeLvls) {
  11520. if (exp >= lvl.enchantValue) {
  11521. level = lvl.level;
  11522. } else {
  11523. break;
  11524. }
  11525. }
  11526. }
  11527. /** Уровень героя необходимый для уровня руны */
  11528. const heroLevel = runeLib.level[level].heroLevel;
  11529. if (hero.level < heroLevel) {
  11530. continue;
  11531. }
  11532.  
  11533. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  11534. if (exp < enchRune.exp) {
  11535. enchRune.exp = exp;
  11536. enchRune.heroId = hero.id;
  11537. enchRune.tier = runeTier;
  11538. break;
  11539. }
  11540. }
  11541. }
  11542. return enchRune;
  11543. }
  11544.  
  11545. getOutlandChest() {
  11546. const bosses = this.questInfo['bossGetAll'];
  11547.  
  11548. const calls = [];
  11549.  
  11550. for (let boss of bosses) {
  11551. if (boss.mayRaid) {
  11552. calls.push({
  11553. name: 'bossRaid',
  11554. args: {
  11555. bossId: boss.id,
  11556. },
  11557. ident: 'bossRaid_' + boss.id,
  11558. });
  11559. calls.push({
  11560. name: 'bossOpenChest',
  11561. args: {
  11562. bossId: boss.id,
  11563. amount: 1,
  11564. starmoney: 0,
  11565. },
  11566. ident: 'bossOpenChest_' + boss.id,
  11567. });
  11568. } else if (boss.chestId == 1) {
  11569. calls.push({
  11570. name: 'bossOpenChest',
  11571. args: {
  11572. bossId: boss.id,
  11573. amount: 1,
  11574. starmoney: 0,
  11575. },
  11576. ident: 'bossOpenChest_' + boss.id,
  11577. });
  11578. }
  11579. }
  11580.  
  11581. return calls;
  11582. }
  11583.  
  11584. getExpHero() {
  11585. const heroes = Object.values(this.questInfo['heroGetAll']);
  11586. const inventory = this.questInfo['inventoryGet'];
  11587. const expHero = { heroId: 0, exp: 3625195, libId: 0 };
  11588. /** зелья опыта (consumable 9, 10, 11, 12) */
  11589. for (let i = 9; i <= 12; i++) {
  11590. if (inventory.consumable[i]) {
  11591. expHero.libId = i;
  11592. break;
  11593. }
  11594. }
  11595.  
  11596. for (const hero of heroes) {
  11597. const exp = hero.xp;
  11598. if (exp < expHero.exp) {
  11599. expHero.heroId = hero.id;
  11600. }
  11601. }
  11602. return expHero;
  11603. }
  11604.  
  11605. getHeroIdTitanGift() {
  11606. const heroes = Object.values(this.questInfo['heroGetAll']);
  11607. const inventory = this.questInfo['inventoryGet'];
  11608. const user = this.questInfo['userGetInfo'];
  11609. const titanGiftLib = lib.getData('titanGift');
  11610. /** Искры */
  11611. const titanGift = inventory.consumable[24];
  11612. let heroId = 0;
  11613. let minLevel = 30;
  11614.  
  11615. if (titanGift < 250 || user.gold < 7000) {
  11616. return 0;
  11617. }
  11618.  
  11619. for (const hero of heroes) {
  11620. if (hero.titanGiftLevel >= 30) {
  11621. continue;
  11622. }
  11623.  
  11624. if (!hero.titanGiftLevel) {
  11625. return hero.id;
  11626. }
  11627.  
  11628. const cost = titanGiftLib[hero.titanGiftLevel].cost;
  11629. if (minLevel > hero.titanGiftLevel && titanGift >= cost.consumable[24] && user.gold >= cost.gold) {
  11630. minLevel = hero.titanGiftLevel;
  11631. heroId = hero.id;
  11632. }
  11633. }
  11634.  
  11635. return heroId;
  11636. }
  11637.  
  11638. getHeroicMissionId() {
  11639. // Получаем доступные миссии с 3 звездами
  11640. const availableMissionsToRaid = Object.values(this.questInfo.missionGetAll)
  11641. .filter((mission) => mission.stars === 3)
  11642. .map((mission) => mission.id);
  11643.  
  11644. // Получаем героев для улучшения, у которых меньше 6 звезд
  11645. const heroesToUpgrade = Object.values(this.questInfo.heroGetAll)
  11646. .filter((hero) => hero.star < 6)
  11647. .sort((a, b) => b.power - a.power)
  11648. .map((hero) => hero.id);
  11649.  
  11650. // Получаем героические миссии, которые доступны для рейдов
  11651. const heroicMissions = Object.values(lib.data.mission).filter((mission) => mission.isHeroic && availableMissionsToRaid.includes(mission.id));
  11652.  
  11653. // Собираем дропы из героических миссий
  11654. const drops = heroicMissions.map((mission) => {
  11655. const lastWave = mission.normalMode.waves[mission.normalMode.waves.length - 1];
  11656. const allRewards = lastWave.enemies[lastWave.enemies.length - 1]
  11657. .drop.map((drop) => drop.reward);
  11658.  
  11659. const heroId = +Object.keys(allRewards.find((reward) => reward.fragmentHero).fragmentHero).pop();
  11660.  
  11661. return { id: mission.id, heroId };
  11662. });
  11663.  
  11664. // Определяем, какие дропы подходят для героев, которых нужно улучшить
  11665. const heroDrops = heroesToUpgrade.map((heroId) => drops.find((drop) => drop.heroId == heroId)).filter((drop) => drop);
  11666. const firstMission = heroDrops[0];
  11667. // Выбираем миссию для рейда
  11668. const selectedMissionId = firstMission ? firstMission.id : 1;
  11669.  
  11670. const stamina = this.questInfo.userGetInfo.refillable.find((x) => x.id == 1).amount;
  11671. const costMissions = 3 * lib.data.mission[selectedMissionId].normalMode.teamExp;
  11672. if (stamina < costMissions) {
  11673. console.log('Энергии не достаточно');
  11674. return 0;
  11675. }
  11676. return selectedMissionId;
  11677. }
  11678.  
  11679. end(status) {
  11680. setProgress(status, true);
  11681. this.resolve();
  11682. }
  11683. }
  11684.  
  11685. this.questRun = dailyQuests;
  11686. this.HWHClasses.dailyQuests = dailyQuests;
  11687.  
  11688. function testDoYourBest() {
  11689. const { doYourBest } = HWHClasses;
  11690. return new Promise((resolve, reject) => {
  11691. const doIt = new doYourBest(resolve, reject);
  11692. doIt.start();
  11693. });
  11694. }
  11695.  
  11696. /**
  11697. * Do everything button
  11698. *
  11699. * Кнопка сделать все
  11700. */
  11701. class doYourBest {
  11702.  
  11703. funcList = [
  11704. {
  11705. name: 'getOutland',
  11706. label: I18N('ASSEMBLE_OUTLAND'),
  11707. checked: false
  11708. },
  11709. {
  11710. name: 'testTower',
  11711. label: I18N('PASS_THE_TOWER'),
  11712. checked: false
  11713. },
  11714. {
  11715. name: 'checkExpedition',
  11716. label: I18N('CHECK_EXPEDITIONS'),
  11717. checked: false
  11718. },
  11719. {
  11720. name: 'testTitanArena',
  11721. label: I18N('COMPLETE_TOE'),
  11722. checked: false
  11723. },
  11724. {
  11725. name: 'mailGetAll',
  11726. label: I18N('COLLECT_MAIL'),
  11727. checked: false
  11728. },
  11729. {
  11730. name: 'collectAllStuff',
  11731. label: I18N('COLLECT_MISC'),
  11732. title: I18N('COLLECT_MISC_TITLE'),
  11733. checked: false
  11734. },
  11735. {
  11736. name: 'getDailyBonus',
  11737. label: I18N('DAILY_BONUS'),
  11738. checked: false
  11739. },
  11740. {
  11741. name: 'dailyQuests',
  11742. label: I18N('DO_DAILY_QUESTS'),
  11743. checked: false
  11744. },
  11745. {
  11746. name: 'rollAscension',
  11747. label: I18N('SEER_TITLE'),
  11748. checked: false
  11749. },
  11750. {
  11751. name: 'questAllFarm',
  11752. label: I18N('COLLECT_QUEST_REWARDS'),
  11753. checked: false
  11754. },
  11755. {
  11756. name: 'testDungeon',
  11757. label: I18N('COMPLETE_DUNGEON'),
  11758. checked: false
  11759. },
  11760. {
  11761. name: 'synchronization',
  11762. label: I18N('MAKE_A_SYNC'),
  11763. checked: false
  11764. },
  11765. {
  11766. name: 'reloadGame',
  11767. label: I18N('RELOAD_GAME'),
  11768. checked: false
  11769. },
  11770. ];
  11771.  
  11772. functions = {
  11773. getOutland,
  11774. testTower,
  11775. checkExpedition,
  11776. testTitanArena,
  11777. mailGetAll,
  11778. collectAllStuff: async () => {
  11779. await offerFarmAllReward();
  11780. 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"}]}');
  11781. },
  11782. dailyQuests: async function () {
  11783. const quests = new dailyQuests(() => { }, () => { });
  11784. await quests.autoInit(true);
  11785. await quests.start();
  11786. },
  11787. rollAscension,
  11788. getDailyBonus,
  11789. questAllFarm,
  11790. testDungeon,
  11791. synchronization: async () => {
  11792. cheats.refreshGame();
  11793. },
  11794. reloadGame: async () => {
  11795. location.reload();
  11796. },
  11797. }
  11798.  
  11799. constructor(resolve, reject, questInfo) {
  11800. this.resolve = resolve;
  11801. this.reject = reject;
  11802. this.questInfo = questInfo
  11803. }
  11804.  
  11805. async start() {
  11806. const selectedDoIt = getSaveVal('selectedDoIt', {});
  11807.  
  11808. this.funcList.forEach(task => {
  11809. if (!selectedDoIt[task.name]) {
  11810. selectedDoIt[task.name] = {
  11811. checked: task.checked
  11812. }
  11813. } else {
  11814. task.checked = selectedDoIt[task.name].checked
  11815. }
  11816. });
  11817.  
  11818. const answer = await popup.confirm(I18N('RUN_FUNCTION'), [
  11819. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  11820. { msg: I18N('BTN_GO'), result: true },
  11821. ], this.funcList);
  11822.  
  11823. if (!answer) {
  11824. this.end('');
  11825. return;
  11826. }
  11827.  
  11828. const taskList = popup.getCheckBoxes();
  11829. taskList.forEach(task => {
  11830. selectedDoIt[task.name].checked = task.checked;
  11831. });
  11832. setSaveVal('selectedDoIt', selectedDoIt);
  11833. for (const task of popup.getCheckBoxes()) {
  11834. if (task.checked) {
  11835. try {
  11836. setProgress(`${task.label} <br>${I18N('PERFORMED')}!`);
  11837. await this.functions[task.name]();
  11838. setProgress(`${task.label} <br>${I18N('DONE')}!`);
  11839. } catch (error) {
  11840. if (await popup.confirm(`${I18N('ERRORS_OCCURRES')}:<br> ${task.label} <br>${I18N('COPY_ERROR')}?`, [
  11841. { msg: I18N('BTN_NO'), result: false },
  11842. { msg: I18N('BTN_YES'), result: true },
  11843. ])) {
  11844. this.errorHandling(error);
  11845. }
  11846. }
  11847. }
  11848. }
  11849. setTimeout((msg) => {
  11850. this.end(msg);
  11851. }, 2000, I18N('ALL_TASK_COMPLETED'));
  11852. return;
  11853. }
  11854.  
  11855. errorHandling(error) {
  11856. //console.error(error);
  11857. let errorInfo = error.toString() + '\n';
  11858. try {
  11859. const errorStack = error.stack.split('\n');
  11860. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testDoYourBest");
  11861. errorInfo += errorStack.slice(0, endStack).join('\n');
  11862. } catch (e) {
  11863. errorInfo += error.stack;
  11864. }
  11865. copyText(errorInfo);
  11866. }
  11867.  
  11868. end(status) {
  11869. setProgress(status, true);
  11870. this.resolve();
  11871. }
  11872. }
  11873.  
  11874. this.HWHClasses.doYourBest = doYourBest;
  11875.  
  11876. /**
  11877. * Passing the adventure along the specified route
  11878. *
  11879. * Прохождение приключения по указанному маршруту
  11880. */
  11881. function testAdventure(type) {
  11882. const { executeAdventure } = HWHClasses;
  11883. return new Promise((resolve, reject) => {
  11884. const bossBattle = new executeAdventure(resolve, reject);
  11885. bossBattle.start(type);
  11886. });
  11887. }
  11888.  
  11889. /**
  11890. * Passing the adventure along the specified route
  11891. *
  11892. * Прохождение приключения по указанному маршруту
  11893. */
  11894. class executeAdventure {
  11895.  
  11896. type = 'default';
  11897.  
  11898. actions = {
  11899. default: {
  11900. getInfo: "adventure_getInfo",
  11901. startBattle: 'adventure_turnStartBattle',
  11902. endBattle: 'adventure_endBattle',
  11903. collectBuff: 'adventure_turnCollectBuff'
  11904. },
  11905. solo: {
  11906. getInfo: "adventureSolo_getInfo",
  11907. startBattle: 'adventureSolo_turnStartBattle',
  11908. endBattle: 'adventureSolo_endBattle',
  11909. collectBuff: 'adventureSolo_turnCollectBuff'
  11910. }
  11911. }
  11912.  
  11913. terminatеReason = I18N('UNKNOWN');
  11914. callAdventureInfo = {
  11915. name: "adventure_getInfo",
  11916. args: {},
  11917. ident: "adventure_getInfo"
  11918. }
  11919. callTeamGetAll = {
  11920. name: "teamGetAll",
  11921. args: {},
  11922. ident: "teamGetAll"
  11923. }
  11924. callTeamGetFavor = {
  11925. name: "teamGetFavor",
  11926. args: {},
  11927. ident: "teamGetFavor"
  11928. }
  11929. callStartBattle = {
  11930. name: "adventure_turnStartBattle",
  11931. args: {},
  11932. ident: "body"
  11933. }
  11934. callEndBattle = {
  11935. name: "adventure_endBattle",
  11936. args: {
  11937. result: {},
  11938. progress: {},
  11939. },
  11940. ident: "body"
  11941. }
  11942. callCollectBuff = {
  11943. name: "adventure_turnCollectBuff",
  11944. args: {},
  11945. ident: "body"
  11946. }
  11947.  
  11948. constructor(resolve, reject) {
  11949. this.resolve = resolve;
  11950. this.reject = reject;
  11951. }
  11952.  
  11953. async start(type) {
  11954. this.type = type || this.type;
  11955. this.callAdventureInfo.name = this.actions[this.type].getInfo;
  11956. const data = await Send(JSON.stringify({
  11957. calls: [
  11958. this.callAdventureInfo,
  11959. this.callTeamGetAll,
  11960. this.callTeamGetFavor
  11961. ]
  11962. }));
  11963. return this.checkAdventureInfo(data.results);
  11964. }
  11965.  
  11966. async getPath() {
  11967. const oldVal = getSaveVal('adventurePath', '');
  11968. const keyPath = `adventurePath:${this.mapIdent}`;
  11969. const answer = await popup.confirm(I18N('ENTER_THE_PATH'), [
  11970. {
  11971. msg: I18N('START_ADVENTURE'),
  11972. placeholder: '1,2,3,4,5,6',
  11973. isInput: true,
  11974. default: getSaveVal(keyPath, oldVal)
  11975. },
  11976. {
  11977. msg: I18N('BTN_CANCEL'),
  11978. result: false,
  11979. isCancel: true
  11980. },
  11981. ]);
  11982. if (!answer) {
  11983. this.terminatеReason = I18N('BTN_CANCELED');
  11984. return false;
  11985. }
  11986.  
  11987. let path = answer.split(',');
  11988. if (path.length < 2) {
  11989. path = answer.split('-');
  11990. }
  11991. if (path.length < 2) {
  11992. this.terminatеReason = I18N('MUST_TWO_POINTS');
  11993. return false;
  11994. }
  11995.  
  11996. for (let p in path) {
  11997. path[p] = +path[p].trim()
  11998. if (Number.isNaN(path[p])) {
  11999. this.terminatеReason = I18N('MUST_ONLY_NUMBERS');
  12000. return false;
  12001. }
  12002. }
  12003.  
  12004. if (!this.checkPath(path)) {
  12005. return false;
  12006. }
  12007. setSaveVal(keyPath, answer);
  12008. return path;
  12009. }
  12010.  
  12011. checkPath(path) {
  12012. for (let i = 0; i < path.length - 1; i++) {
  12013. const currentPoint = path[i];
  12014. const nextPoint = path[i + 1];
  12015.  
  12016. const isValidPath = this.paths.some(p =>
  12017. (p.from_id === currentPoint && p.to_id === nextPoint) ||
  12018. (p.from_id === nextPoint && p.to_id === currentPoint)
  12019. );
  12020.  
  12021. if (!isValidPath) {
  12022. this.terminatеReason = I18N('INCORRECT_WAY', {
  12023. from: currentPoint,
  12024. to: nextPoint,
  12025. });
  12026. return false;
  12027. }
  12028. }
  12029.  
  12030. return true;
  12031. }
  12032.  
  12033. async checkAdventureInfo(data) {
  12034. this.advInfo = data[0].result.response;
  12035. if (!this.advInfo) {
  12036. this.terminatеReason = I18N('NOT_ON_AN_ADVENTURE') ;
  12037. return this.end();
  12038. }
  12039. const heroesTeam = data[1].result.response.adventure_hero;
  12040. const favor = data[2]?.result.response.adventure_hero;
  12041. const heroes = heroesTeam.slice(0, 5);
  12042. const pet = heroesTeam[5];
  12043. this.args = {
  12044. pet,
  12045. heroes,
  12046. favor,
  12047. path: [],
  12048. broadcast: false
  12049. }
  12050. const advUserInfo = this.advInfo.users[userInfo.id];
  12051. this.turnsLeft = advUserInfo.turnsLeft;
  12052. this.currentNode = advUserInfo.currentNode;
  12053. this.nodes = this.advInfo.nodes;
  12054. this.paths = this.advInfo.paths;
  12055. this.mapIdent = this.advInfo.mapIdent;
  12056.  
  12057. this.path = await this.getPath();
  12058. if (!this.path) {
  12059. return this.end();
  12060. }
  12061.  
  12062. if (this.currentNode == 1 && this.path[0] != 1) {
  12063. this.path.unshift(1);
  12064. }
  12065.  
  12066. return this.loop();
  12067. }
  12068.  
  12069. async loop() {
  12070. const position = this.path.indexOf(+this.currentNode);
  12071. if (!(~position)) {
  12072. this.terminatеReason = I18N('YOU_IN_NOT_ON_THE_WAY');
  12073. return this.end();
  12074. }
  12075. this.path = this.path.slice(position);
  12076. if ((this.path.length - 1) > this.turnsLeft &&
  12077. await popup.confirm(I18N('ATTEMPTS_NOT_ENOUGH'), [
  12078. { msg: I18N('YES_CONTINUE'), result: false },
  12079. { msg: I18N('BTN_NO'), result: true },
  12080. ])) {
  12081. this.terminatеReason = I18N('NOT_ENOUGH_AP');
  12082. return this.end();
  12083. }
  12084. const toPath = [];
  12085. for (const nodeId of this.path) {
  12086. if (!this.turnsLeft) {
  12087. this.terminatеReason = I18N('ATTEMPTS_ARE_OVER');
  12088. return this.end();
  12089. }
  12090. toPath.push(nodeId);
  12091. console.log(toPath);
  12092. if (toPath.length > 1) {
  12093. setProgress(toPath.join(' > ') + ` ${I18N('MOVES')}: ` + this.turnsLeft);
  12094. }
  12095. if (nodeId == this.currentNode) {
  12096. continue;
  12097. }
  12098.  
  12099. const nodeInfo = this.getNodeInfo(nodeId);
  12100. if (nodeInfo.type == 'TYPE_COMBAT') {
  12101. if (nodeInfo.state == 'empty') {
  12102. this.turnsLeft--;
  12103. continue;
  12104. }
  12105.  
  12106. /**
  12107. * Disable regular battle cancellation
  12108. *
  12109. * Отключаем штатную отменую боя
  12110. */
  12111. setIsCancalBattle(false);
  12112. if (await this.battle(toPath)) {
  12113. this.turnsLeft--;
  12114. toPath.splice(0, toPath.indexOf(nodeId));
  12115. nodeInfo.state = 'empty';
  12116. setIsCancalBattle(true);
  12117. continue;
  12118. }
  12119. setIsCancalBattle(true);
  12120. return this.end()
  12121. }
  12122.  
  12123. if (nodeInfo.type == 'TYPE_PLAYERBUFF') {
  12124. const buff = this.checkBuff(nodeInfo);
  12125. if (buff == null) {
  12126. continue;
  12127. }
  12128.  
  12129. if (await this.collectBuff(buff, toPath)) {
  12130. this.turnsLeft--;
  12131. toPath.splice(0, toPath.indexOf(nodeId));
  12132. continue;
  12133. }
  12134. this.terminatеReason = I18N('BUFF_GET_ERROR');
  12135. return this.end();
  12136. }
  12137. }
  12138. this.terminatеReason = I18N('SUCCESS');
  12139. return this.end();
  12140. }
  12141.  
  12142. /**
  12143. * Carrying out a fight
  12144. *
  12145. * Проведение боя
  12146. */
  12147. async battle(path, preCalc = true) {
  12148. const data = await this.startBattle(path);
  12149. try {
  12150. const battle = data.results[0].result.response.battle;
  12151. const result = await Calc(battle);
  12152. if (result.result.win) {
  12153. const info = await this.endBattle(result);
  12154. if (info.results[0].result.response?.error) {
  12155. this.terminatеReason = I18N('BATTLE_END_ERROR');
  12156. return false;
  12157. }
  12158. } else {
  12159. await this.cancelBattle(result);
  12160.  
  12161. if (preCalc && await this.preCalcBattle(battle)) {
  12162. path = path.slice(-2);
  12163. for (let i = 1; i <= getInput('countAutoBattle'); i++) {
  12164. setProgress(`${I18N('AUTOBOT')}: ${i}/${getInput('countAutoBattle')}`);
  12165. const result = await this.battle(path, false);
  12166. if (result) {
  12167. setProgress(I18N('VICTORY'));
  12168. return true;
  12169. }
  12170. }
  12171. this.terminatеReason = I18N('FAILED_TO_WIN_AUTO');
  12172. return false;
  12173. }
  12174. return false;
  12175. }
  12176. } catch (error) {
  12177. console.error(error);
  12178. if (await popup.confirm(I18N('ERROR_OF_THE_BATTLE_COPY'), [
  12179. { msg: I18N('BTN_NO'), result: false },
  12180. { msg: I18N('BTN_YES'), result: true },
  12181. ])) {
  12182. this.errorHandling(error, data);
  12183. }
  12184. this.terminatеReason = I18N('ERROR_DURING_THE_BATTLE');
  12185. return false;
  12186. }
  12187. return true;
  12188. }
  12189.  
  12190. /**
  12191. * Recalculate battles
  12192. *
  12193. * Прерасчтет битвы
  12194. */
  12195. async preCalcBattle(battle) {
  12196. const countTestBattle = getInput('countTestBattle');
  12197. for (let i = 0; i < countTestBattle; i++) {
  12198. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  12199. const result = await Calc(battle);
  12200. if (result.result.win) {
  12201. console.log(i, countTestBattle);
  12202. return true;
  12203. }
  12204. }
  12205. this.terminatеReason = I18N('NO_CHANCE_WIN') + countTestBattle;
  12206. return false;
  12207. }
  12208.  
  12209. /**
  12210. * Starts a fight
  12211. *
  12212. * Начинает бой
  12213. */
  12214. startBattle(path) {
  12215. this.args.path = path;
  12216. this.callStartBattle.name = this.actions[this.type].startBattle;
  12217. this.callStartBattle.args = this.args
  12218. const calls = [this.callStartBattle];
  12219. return Send(JSON.stringify({ calls }));
  12220. }
  12221.  
  12222. cancelBattle(battle) {
  12223. const fixBattle = function (heroes) {
  12224. for (const ids in heroes) {
  12225. const hero = heroes[ids];
  12226. hero.energy = random(1, 999);
  12227. if (hero.hp > 0) {
  12228. hero.hp = random(1, hero.hp);
  12229. }
  12230. }
  12231. }
  12232. fixBattle(battle.progress[0].attackers.heroes);
  12233. fixBattle(battle.progress[0].defenders.heroes);
  12234. return this.endBattle(battle);
  12235. }
  12236.  
  12237. /**
  12238. * Ends the fight
  12239. *
  12240. * Заканчивает бой
  12241. */
  12242. endBattle(battle) {
  12243. this.callEndBattle.name = this.actions[this.type].endBattle;
  12244. this.callEndBattle.args.result = battle.result
  12245. this.callEndBattle.args.progress = battle.progress
  12246. const calls = [this.callEndBattle];
  12247. return Send(JSON.stringify({ calls }));
  12248. }
  12249.  
  12250. /**
  12251. * Checks if you can get a buff
  12252. *
  12253. * Проверяет можно ли получить баф
  12254. */
  12255. checkBuff(nodeInfo) {
  12256. let id = null;
  12257. let value = 0;
  12258. for (const buffId in nodeInfo.buffs) {
  12259. const buff = nodeInfo.buffs[buffId];
  12260. if (buff.owner == null && buff.value > value) {
  12261. id = buffId;
  12262. value = buff.value;
  12263. }
  12264. }
  12265. nodeInfo.buffs[id].owner = 'Я';
  12266. return id;
  12267. }
  12268.  
  12269. /**
  12270. * Collects a buff
  12271. *
  12272. * Собирает баф
  12273. */
  12274. async collectBuff(buff, path) {
  12275. this.callCollectBuff.name = this.actions[this.type].collectBuff;
  12276. this.callCollectBuff.args = { buff, path };
  12277. const calls = [this.callCollectBuff];
  12278. return Send(JSON.stringify({ calls }));
  12279. }
  12280.  
  12281. getNodeInfo(nodeId) {
  12282. return this.nodes.find(node => node.id == nodeId);
  12283. }
  12284.  
  12285. errorHandling(error, data) {
  12286. //console.error(error);
  12287. let errorInfo = error.toString() + '\n';
  12288. try {
  12289. const errorStack = error.stack.split('\n');
  12290. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testAdventure");
  12291. errorInfo += errorStack.slice(0, endStack).join('\n');
  12292. } catch (e) {
  12293. errorInfo += error.stack;
  12294. }
  12295. if (data) {
  12296. errorInfo += '\nData: ' + JSON.stringify(data);
  12297. }
  12298. copyText(errorInfo);
  12299. }
  12300.  
  12301. end() {
  12302. setIsCancalBattle(true);
  12303. setProgress(this.terminatеReason, true);
  12304. console.log(this.terminatеReason);
  12305. this.resolve();
  12306. }
  12307. }
  12308.  
  12309. this.HWHClasses.executeAdventure = executeAdventure;
  12310.  
  12311. /**
  12312. * Passage of brawls
  12313. *
  12314. * Прохождение потасовок
  12315. */
  12316. function testBrawls(isAuto) {
  12317. const { executeBrawls } = HWHClasses;
  12318. return new Promise((resolve, reject) => {
  12319. const brawls = new executeBrawls(resolve, reject);
  12320. brawls.start(brawlsPack, isAuto);
  12321. });
  12322. }
  12323. /**
  12324. * Passage of brawls
  12325. *
  12326. * Прохождение потасовок
  12327. */
  12328. class executeBrawls {
  12329. callBrawlQuestGetInfo = {
  12330. name: "brawl_questGetInfo",
  12331. args: {},
  12332. ident: "brawl_questGetInfo"
  12333. }
  12334. callBrawlFindEnemies = {
  12335. name: "brawl_findEnemies",
  12336. args: {},
  12337. ident: "brawl_findEnemies"
  12338. }
  12339. callBrawlQuestFarm = {
  12340. name: "brawl_questFarm",
  12341. args: {},
  12342. ident: "brawl_questFarm"
  12343. }
  12344. callUserGetInfo = {
  12345. name: "userGetInfo",
  12346. args: {},
  12347. ident: "userGetInfo"
  12348. }
  12349. callTeamGetMaxUpgrade = {
  12350. name: "teamGetMaxUpgrade",
  12351. args: {},
  12352. ident: "teamGetMaxUpgrade"
  12353. }
  12354. callBrawlGetInfo = {
  12355. name: "brawl_getInfo",
  12356. args: {},
  12357. ident: "brawl_getInfo"
  12358. }
  12359.  
  12360. stats = {
  12361. win: 0,
  12362. loss: 0,
  12363. count: 0,
  12364. }
  12365.  
  12366. stage = {
  12367. '3': 1,
  12368. '7': 2,
  12369. '12': 3,
  12370. }
  12371.  
  12372. attempts = 0;
  12373.  
  12374. constructor(resolve, reject) {
  12375. this.resolve = resolve;
  12376. this.reject = reject;
  12377.  
  12378. const allHeroIds = Object.keys(lib.getData('hero'));
  12379. this.callTeamGetMaxUpgrade.args.units = {
  12380. hero: allHeroIds.filter((id) => +id < 1000),
  12381. titan: allHeroIds.filter((id) => +id >= 4000 && +id < 4100),
  12382. pet: allHeroIds.filter((id) => +id >= 6000 && +id < 6100),
  12383. };
  12384. }
  12385.  
  12386. async start(args, isAuto) {
  12387. this.isAuto = isAuto;
  12388. this.args = args;
  12389. setIsCancalBattle(false);
  12390. this.brawlInfo = await this.getBrawlInfo();
  12391. this.attempts = this.brawlInfo.attempts;
  12392.  
  12393. if (!this.attempts && !this.info.boughtEndlessLivesToday) {
  12394. this.end(I18N('DONT_HAVE_LIVES'));
  12395. return;
  12396. }
  12397.  
  12398. while (1) {
  12399. if (!isBrawlsAutoStart) {
  12400. this.end(I18N('BTN_CANCELED'));
  12401. return;
  12402. }
  12403.  
  12404. const maxStage = this.brawlInfo.questInfo.stage;
  12405. const stage = this.stage[maxStage];
  12406. const progress = this.brawlInfo.questInfo.progress;
  12407.  
  12408. setProgress(
  12409. `${I18N('STAGE')} ${stage}: ${progress}/${maxStage}<br>${I18N('FIGHTS')}: ${this.stats.count}<br>${I18N('WINS')}: ${
  12410. this.stats.win
  12411. }<br>${I18N('LOSSES')}: ${this.stats.loss}<br>${I18N('LIVES')}: ${this.attempts}<br>${I18N('STOP')}`,
  12412. false,
  12413. function () {
  12414. isBrawlsAutoStart = false;
  12415. }
  12416. );
  12417.  
  12418. if (this.brawlInfo.questInfo.canFarm) {
  12419. const result = await this.questFarm();
  12420. console.log(result);
  12421. }
  12422.  
  12423. if (!this.continueAttack && this.brawlInfo.questInfo.stage == 12 && this.brawlInfo.questInfo.progress == 12) {
  12424. if (
  12425. await popup.confirm(I18N('BRAWL_DAILY_TASK_COMPLETED'), [
  12426. { msg: I18N('BTN_NO'), result: true },
  12427. { msg: I18N('BTN_YES'), result: false },
  12428. ])
  12429. ) {
  12430. this.end(I18N('SUCCESS'));
  12431. return;
  12432. } else {
  12433. this.continueAttack = true;
  12434. }
  12435. }
  12436.  
  12437. if (!this.attempts && !this.info.boughtEndlessLivesToday) {
  12438. this.end(I18N('DONT_HAVE_LIVES'));
  12439. return;
  12440. }
  12441.  
  12442. const enemie = Object.values(this.brawlInfo.findEnemies).shift();
  12443.  
  12444. // Автоматический подбор пачки
  12445. if (this.isAuto) {
  12446. if (this.mandatoryId <= 4000 && this.mandatoryId != 13) {
  12447. this.end(I18N('BRAWL_AUTO_PACK_NOT_CUR_HERO'));
  12448. return;
  12449. }
  12450. if (this.mandatoryId >= 4000 && this.mandatoryId < 4100) {
  12451. this.args = await this.updateTitanPack(enemie.heroes);
  12452. } else if (this.mandatoryId < 4000 && this.mandatoryId == 13) {
  12453. this.args = await this.updateHeroesPack(enemie.heroes);
  12454. }
  12455. }
  12456.  
  12457. const result = await this.battle(enemie.userId);
  12458. this.brawlInfo = {
  12459. questInfo: result[1].result.response,
  12460. findEnemies: result[2].result.response,
  12461. };
  12462. }
  12463. }
  12464.  
  12465. async updateTitanPack(enemieHeroes) {
  12466. const packs = [
  12467. [4033, 4040, 4041, 4042, 4043],
  12468. [4032, 4040, 4041, 4042, 4043],
  12469. [4031, 4040, 4041, 4042, 4043],
  12470. [4030, 4040, 4041, 4042, 4043],
  12471. [4032, 4033, 4040, 4042, 4043],
  12472. [4030, 4033, 4041, 4042, 4043],
  12473. [4031, 4033, 4040, 4042, 4043],
  12474. [4032, 4033, 4040, 4041, 4043],
  12475. [4023, 4040, 4041, 4042, 4043],
  12476. [4030, 4033, 4040, 4042, 4043],
  12477. [4031, 4033, 4040, 4041, 4043],
  12478. [4022, 4040, 4041, 4042, 4043],
  12479. [4030, 4033, 4040, 4041, 4043],
  12480. [4021, 4040, 4041, 4042, 4043],
  12481. [4020, 4040, 4041, 4042, 4043],
  12482. [4023, 4033, 4040, 4042, 4043],
  12483. [4030, 4032, 4033, 4042, 4043],
  12484. [4023, 4033, 4040, 4041, 4043],
  12485. [4031, 4032, 4033, 4040, 4043],
  12486. [4030, 4032, 4033, 4041, 4043],
  12487. [4030, 4031, 4033, 4042, 4043],
  12488. [4013, 4040, 4041, 4042, 4043],
  12489. [4030, 4032, 4033, 4040, 4043],
  12490. [4030, 4031, 4033, 4041, 4043],
  12491. [4012, 4040, 4041, 4042, 4043],
  12492. [4030, 4031, 4033, 4040, 4043],
  12493. [4011, 4040, 4041, 4042, 4043],
  12494. [4010, 4040, 4041, 4042, 4043],
  12495. [4023, 4032, 4033, 4042, 4043],
  12496. [4022, 4032, 4033, 4042, 4043],
  12497. [4023, 4032, 4033, 4041, 4043],
  12498. [4021, 4032, 4033, 4042, 4043],
  12499. [4022, 4032, 4033, 4041, 4043],
  12500. [4023, 4030, 4033, 4042, 4043],
  12501. [4023, 4032, 4033, 4040, 4043],
  12502. [4013, 4033, 4040, 4042, 4043],
  12503. [4020, 4032, 4033, 4042, 4043],
  12504. [4021, 4032, 4033, 4041, 4043],
  12505. [4022, 4030, 4033, 4042, 4043],
  12506. [4022, 4032, 4033, 4040, 4043],
  12507. [4023, 4030, 4033, 4041, 4043],
  12508. [4023, 4031, 4033, 4040, 4043],
  12509. [4013, 4033, 4040, 4041, 4043],
  12510. [4020, 4031, 4033, 4042, 4043],
  12511. [4020, 4032, 4033, 4041, 4043],
  12512. [4021, 4030, 4033, 4042, 4043],
  12513. [4021, 4032, 4033, 4040, 4043],
  12514. [4022, 4030, 4033, 4041, 4043],
  12515. [4022, 4031, 4033, 4040, 4043],
  12516. [4023, 4030, 4033, 4040, 4043],
  12517. [4030, 4031, 4032, 4033, 4043],
  12518. [4003, 4040, 4041, 4042, 4043],
  12519. [4020, 4030, 4033, 4042, 4043],
  12520. [4020, 4031, 4033, 4041, 4043],
  12521. [4020, 4032, 4033, 4040, 4043],
  12522. [4021, 4030, 4033, 4041, 4043],
  12523. [4021, 4031, 4033, 4040, 4043],
  12524. [4022, 4030, 4033, 4040, 4043],
  12525. [4030, 4031, 4032, 4033, 4042],
  12526. [4002, 4040, 4041, 4042, 4043],
  12527. [4020, 4030, 4033, 4041, 4043],
  12528. [4020, 4031, 4033, 4040, 4043],
  12529. [4021, 4030, 4033, 4040, 4043],
  12530. [4030, 4031, 4032, 4033, 4041],
  12531. [4001, 4040, 4041, 4042, 4043],
  12532. [4030, 4031, 4032, 4033, 4040],
  12533. [4000, 4040, 4041, 4042, 4043],
  12534. [4013, 4032, 4033, 4042, 4043],
  12535. [4012, 4032, 4033, 4042, 4043],
  12536. [4013, 4032, 4033, 4041, 4043],
  12537. [4023, 4031, 4032, 4033, 4043],
  12538. [4011, 4032, 4033, 4042, 4043],
  12539. [4012, 4032, 4033, 4041, 4043],
  12540. [4013, 4030, 4033, 4042, 4043],
  12541. [4013, 4032, 4033, 4040, 4043],
  12542. [4023, 4030, 4032, 4033, 4043],
  12543. [4003, 4033, 4040, 4042, 4043],
  12544. [4013, 4023, 4040, 4042, 4043],
  12545. [4010, 4032, 4033, 4042, 4043],
  12546. [4011, 4032, 4033, 4041, 4043],
  12547. [4012, 4030, 4033, 4042, 4043],
  12548. [4012, 4032, 4033, 4040, 4043],
  12549. [4013, 4030, 4033, 4041, 4043],
  12550. [4013, 4031, 4033, 4040, 4043],
  12551. [4023, 4030, 4031, 4033, 4043],
  12552. [4003, 4033, 4040, 4041, 4043],
  12553. [4013, 4023, 4040, 4041, 4043],
  12554. [4010, 4031, 4033, 4042, 4043],
  12555. [4010, 4032, 4033, 4041, 4043],
  12556. [4011, 4030, 4033, 4042, 4043],
  12557. [4011, 4032, 4033, 4040, 4043],
  12558. [4012, 4030, 4033, 4041, 4043],
  12559. [4012, 4031, 4033, 4040, 4043],
  12560. [4013, 4030, 4033, 4040, 4043],
  12561. [4010, 4030, 4033, 4042, 4043],
  12562. [4010, 4031, 4033, 4041, 4043],
  12563. [4010, 4032, 4033, 4040, 4043],
  12564. [4011, 4030, 4033, 4041, 4043],
  12565. [4011, 4031, 4033, 4040, 4043],
  12566. [4012, 4030, 4033, 4040, 4043],
  12567. [4010, 4030, 4033, 4041, 4043],
  12568. [4010, 4031, 4033, 4040, 4043],
  12569. [4011, 4030, 4033, 4040, 4043],
  12570. [4003, 4032, 4033, 4042, 4043],
  12571. [4002, 4032, 4033, 4042, 4043],
  12572. [4003, 4032, 4033, 4041, 4043],
  12573. [4013, 4031, 4032, 4033, 4043],
  12574. [4001, 4032, 4033, 4042, 4043],
  12575. [4002, 4032, 4033, 4041, 4043],
  12576. [4003, 4030, 4033, 4042, 4043],
  12577. [4003, 4032, 4033, 4040, 4043],
  12578. [4013, 4030, 4032, 4033, 4043],
  12579. [4003, 4023, 4040, 4042, 4043],
  12580. [4000, 4032, 4033, 4042, 4043],
  12581. [4001, 4032, 4033, 4041, 4043],
  12582. [4002, 4030, 4033, 4042, 4043],
  12583. [4002, 4032, 4033, 4040, 4043],
  12584. [4003, 4030, 4033, 4041, 4043],
  12585. [4003, 4031, 4033, 4040, 4043],
  12586. [4020, 4022, 4023, 4042, 4043],
  12587. [4013, 4030, 4031, 4033, 4043],
  12588. [4003, 4023, 4040, 4041, 4043],
  12589. [4000, 4031, 4033, 4042, 4043],
  12590. [4000, 4032, 4033, 4041, 4043],
  12591. [4001, 4030, 4033, 4042, 4043],
  12592. [4001, 4032, 4033, 4040, 4043],
  12593. [4002, 4030, 4033, 4041, 4043],
  12594. [4002, 4031, 4033, 4040, 4043],
  12595. [4003, 4030, 4033, 4040, 4043],
  12596. [4021, 4022, 4023, 4040, 4043],
  12597. [4020, 4022, 4023, 4041, 4043],
  12598. [4020, 4021, 4023, 4042, 4043],
  12599. [4023, 4030, 4031, 4032, 4033],
  12600. [4000, 4030, 4033, 4042, 4043],
  12601. [4000, 4031, 4033, 4041, 4043],
  12602. [4000, 4032, 4033, 4040, 4043],
  12603. [4001, 4030, 4033, 4041, 4043],
  12604. [4001, 4031, 4033, 4040, 4043],
  12605. [4002, 4030, 4033, 4040, 4043],
  12606. [4020, 4022, 4023, 4040, 4043],
  12607. [4020, 4021, 4023, 4041, 4043],
  12608. [4022, 4030, 4031, 4032, 4033],
  12609. [4000, 4030, 4033, 4041, 4043],
  12610. [4000, 4031, 4033, 4040, 4043],
  12611. [4001, 4030, 4033, 4040, 4043],
  12612. [4020, 4021, 4023, 4040, 4043],
  12613. [4021, 4030, 4031, 4032, 4033],
  12614. [4020, 4030, 4031, 4032, 4033],
  12615. [4003, 4031, 4032, 4033, 4043],
  12616. [4020, 4022, 4023, 4033, 4043],
  12617. [4003, 4030, 4032, 4033, 4043],
  12618. [4003, 4013, 4040, 4042, 4043],
  12619. [4020, 4021, 4023, 4033, 4043],
  12620. [4003, 4030, 4031, 4033, 4043],
  12621. [4003, 4013, 4040, 4041, 4043],
  12622. [4013, 4030, 4031, 4032, 4033],
  12623. [4012, 4030, 4031, 4032, 4033],
  12624. [4011, 4030, 4031, 4032, 4033],
  12625. [4010, 4030, 4031, 4032, 4033],
  12626. [4013, 4023, 4031, 4032, 4033],
  12627. [4013, 4023, 4030, 4032, 4033],
  12628. [4020, 4022, 4023, 4032, 4033],
  12629. [4013, 4023, 4030, 4031, 4033],
  12630. [4021, 4022, 4023, 4030, 4033],
  12631. [4020, 4022, 4023, 4031, 4033],
  12632. [4020, 4021, 4023, 4032, 4033],
  12633. [4020, 4021, 4022, 4023, 4043],
  12634. [4003, 4030, 4031, 4032, 4033],
  12635. [4020, 4022, 4023, 4030, 4033],
  12636. [4020, 4021, 4023, 4031, 4033],
  12637. [4020, 4021, 4022, 4023, 4042],
  12638. [4002, 4030, 4031, 4032, 4033],
  12639. [4020, 4021, 4023, 4030, 4033],
  12640. [4020, 4021, 4022, 4023, 4041],
  12641. [4001, 4030, 4031, 4032, 4033],
  12642. [4020, 4021, 4022, 4023, 4040],
  12643. [4000, 4030, 4031, 4032, 4033],
  12644. [4003, 4023, 4031, 4032, 4033],
  12645. [4013, 4020, 4022, 4023, 4043],
  12646. [4003, 4023, 4030, 4032, 4033],
  12647. [4010, 4012, 4013, 4042, 4043],
  12648. [4013, 4020, 4021, 4023, 4043],
  12649. [4003, 4023, 4030, 4031, 4033],
  12650. [4011, 4012, 4013, 4040, 4043],
  12651. [4010, 4012, 4013, 4041, 4043],
  12652. [4010, 4011, 4013, 4042, 4043],
  12653. [4020, 4021, 4022, 4023, 4033],
  12654. [4010, 4012, 4013, 4040, 4043],
  12655. [4010, 4011, 4013, 4041, 4043],
  12656. [4020, 4021, 4022, 4023, 4032],
  12657. [4010, 4011, 4013, 4040, 4043],
  12658. [4020, 4021, 4022, 4023, 4031],
  12659. [4020, 4021, 4022, 4023, 4030],
  12660. [4003, 4013, 4031, 4032, 4033],
  12661. [4010, 4012, 4013, 4033, 4043],
  12662. [4003, 4020, 4022, 4023, 4043],
  12663. [4013, 4020, 4022, 4023, 4033],
  12664. [4003, 4013, 4030, 4032, 4033],
  12665. [4010, 4011, 4013, 4033, 4043],
  12666. [4003, 4020, 4021, 4023, 4043],
  12667. [4013, 4020, 4021, 4023, 4033],
  12668. [4003, 4013, 4030, 4031, 4033],
  12669. [4010, 4012, 4013, 4023, 4043],
  12670. [4003, 4020, 4022, 4023, 4033],
  12671. [4010, 4012, 4013, 4032, 4033],
  12672. [4010, 4011, 4013, 4023, 4043],
  12673. [4003, 4020, 4021, 4023, 4033],
  12674. [4011, 4012, 4013, 4030, 4033],
  12675. [4010, 4012, 4013, 4031, 4033],
  12676. [4010, 4011, 4013, 4032, 4033],
  12677. [4013, 4020, 4021, 4022, 4023],
  12678. [4010, 4012, 4013, 4030, 4033],
  12679. [4010, 4011, 4013, 4031, 4033],
  12680. [4012, 4020, 4021, 4022, 4023],
  12681. [4010, 4011, 4013, 4030, 4033],
  12682. [4011, 4020, 4021, 4022, 4023],
  12683. [4010, 4020, 4021, 4022, 4023],
  12684. [4010, 4012, 4013, 4023, 4033],
  12685. [4000, 4002, 4003, 4042, 4043],
  12686. [4010, 4011, 4013, 4023, 4033],
  12687. [4001, 4002, 4003, 4040, 4043],
  12688. [4000, 4002, 4003, 4041, 4043],
  12689. [4000, 4001, 4003, 4042, 4043],
  12690. [4010, 4011, 4012, 4013, 4043],
  12691. [4003, 4020, 4021, 4022, 4023],
  12692. [4000, 4002, 4003, 4040, 4043],
  12693. [4000, 4001, 4003, 4041, 4043],
  12694. [4010, 4011, 4012, 4013, 4042],
  12695. [4002, 4020, 4021, 4022, 4023],
  12696. [4000, 4001, 4003, 4040, 4043],
  12697. [4010, 4011, 4012, 4013, 4041],
  12698. [4001, 4020, 4021, 4022, 4023],
  12699. [4010, 4011, 4012, 4013, 4040],
  12700. [4000, 4020, 4021, 4022, 4023],
  12701. [4001, 4002, 4003, 4033, 4043],
  12702. [4000, 4002, 4003, 4033, 4043],
  12703. [4003, 4010, 4012, 4013, 4043],
  12704. [4003, 4013, 4020, 4022, 4023],
  12705. [4000, 4001, 4003, 4033, 4043],
  12706. [4003, 4010, 4011, 4013, 4043],
  12707. [4003, 4013, 4020, 4021, 4023],
  12708. [4010, 4011, 4012, 4013, 4033],
  12709. [4010, 4011, 4012, 4013, 4032],
  12710. [4010, 4011, 4012, 4013, 4031],
  12711. [4010, 4011, 4012, 4013, 4030],
  12712. [4001, 4002, 4003, 4023, 4043],
  12713. [4000, 4002, 4003, 4023, 4043],
  12714. [4003, 4010, 4012, 4013, 4033],
  12715. [4000, 4002, 4003, 4032, 4033],
  12716. [4000, 4001, 4003, 4023, 4043],
  12717. [4003, 4010, 4011, 4013, 4033],
  12718. [4001, 4002, 4003, 4030, 4033],
  12719. [4000, 4002, 4003, 4031, 4033],
  12720. [4000, 4001, 4003, 4032, 4033],
  12721. [4010, 4011, 4012, 4013, 4023],
  12722. [4000, 4002, 4003, 4030, 4033],
  12723. [4000, 4001, 4003, 4031, 4033],
  12724. [4010, 4011, 4012, 4013, 4022],
  12725. [4000, 4001, 4003, 4030, 4033],
  12726. [4010, 4011, 4012, 4013, 4021],
  12727. [4010, 4011, 4012, 4013, 4020],
  12728. [4001, 4002, 4003, 4013, 4043],
  12729. [4001, 4002, 4003, 4023, 4033],
  12730. [4000, 4002, 4003, 4013, 4043],
  12731. [4000, 4002, 4003, 4023, 4033],
  12732. [4003, 4010, 4012, 4013, 4023],
  12733. [4000, 4001, 4003, 4013, 4043],
  12734. [4000, 4001, 4003, 4023, 4033],
  12735. [4003, 4010, 4011, 4013, 4023],
  12736. [4001, 4002, 4003, 4013, 4033],
  12737. [4000, 4002, 4003, 4013, 4033],
  12738. [4000, 4001, 4003, 4013, 4033],
  12739. [4000, 4001, 4002, 4003, 4043],
  12740. [4003, 4010, 4011, 4012, 4013],
  12741. [4000, 4001, 4002, 4003, 4042],
  12742. [4002, 4010, 4011, 4012, 4013],
  12743. [4000, 4001, 4002, 4003, 4041],
  12744. [4001, 4010, 4011, 4012, 4013],
  12745. [4000, 4001, 4002, 4003, 4040],
  12746. [4000, 4010, 4011, 4012, 4013],
  12747. [4001, 4002, 4003, 4013, 4023],
  12748. [4000, 4002, 4003, 4013, 4023],
  12749. [4000, 4001, 4003, 4013, 4023],
  12750. [4000, 4001, 4002, 4003, 4033],
  12751. [4000, 4001, 4002, 4003, 4032],
  12752. [4000, 4001, 4002, 4003, 4031],
  12753. [4000, 4001, 4002, 4003, 4030],
  12754. [4000, 4001, 4002, 4003, 4023],
  12755. [4000, 4001, 4002, 4003, 4022],
  12756. [4000, 4001, 4002, 4003, 4021],
  12757. [4000, 4001, 4002, 4003, 4020],
  12758. [4000, 4001, 4002, 4003, 4013],
  12759. [4000, 4001, 4002, 4003, 4012],
  12760. [4000, 4001, 4002, 4003, 4011],
  12761. [4000, 4001, 4002, 4003, 4010],
  12762. ].filter((p) => p.includes(this.mandatoryId));
  12763.  
  12764. const bestPack = {
  12765. pack: packs[0],
  12766. winRate: 0,
  12767. countBattle: 0,
  12768. id: 0,
  12769. };
  12770.  
  12771. for (const id in packs) {
  12772. const pack = packs[id];
  12773. const attackers = this.maxUpgrade.filter((e) => pack.includes(e.id)).reduce((obj, e) => ({ ...obj, [e.id]: e }), {});
  12774. const battle = {
  12775. attackers,
  12776. defenders: [enemieHeroes],
  12777. type: 'brawl_titan',
  12778. };
  12779. const isRandom = this.isRandomBattle(battle);
  12780. const stat = {
  12781. count: 0,
  12782. win: 0,
  12783. winRate: 0,
  12784. };
  12785. for (let i = 1; i <= 20; i++) {
  12786. battle.seed = Math.floor(Date.now() / 1000) + Math.random() * 1000;
  12787. const result = await Calc(battle);
  12788. stat.win += result.result.win;
  12789. stat.count += 1;
  12790. stat.winRate = stat.win / stat.count;
  12791. if (!isRandom || (i >= 2 && stat.winRate < 0.65) || (i >= 10 && stat.winRate == 1)) {
  12792. break;
  12793. }
  12794. }
  12795.  
  12796. if (!isRandom && stat.win) {
  12797. return {
  12798. favor: {},
  12799. heroes: pack,
  12800. };
  12801. }
  12802. if (stat.winRate > 0.85) {
  12803. return {
  12804. favor: {},
  12805. heroes: pack,
  12806. };
  12807. }
  12808. if (stat.winRate > bestPack.winRate) {
  12809. bestPack.countBattle = stat.count;
  12810. bestPack.winRate = stat.winRate;
  12811. bestPack.pack = pack;
  12812. bestPack.id = id;
  12813. }
  12814. }
  12815.  
  12816. //console.log(bestPack.id, bestPack.pack, bestPack.winRate, bestPack.countBattle);
  12817. return {
  12818. favor: {},
  12819. heroes: bestPack.pack,
  12820. };
  12821. }
  12822.  
  12823. isRandomPack(pack) {
  12824. const ids = Object.keys(pack);
  12825. return ids.includes('4023') || ids.includes('4021');
  12826. }
  12827.  
  12828. isRandomBattle(battle) {
  12829. return this.isRandomPack(battle.attackers) || this.isRandomPack(battle.defenders[0]);
  12830. }
  12831.  
  12832. async updateHeroesPack(enemieHeroes) {
  12833. 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}}}];
  12834.  
  12835. const bestPack = {
  12836. pack: packs[0],
  12837. countWin: 0,
  12838. }
  12839.  
  12840. for (const pack of packs) {
  12841. const attackers = pack.attackers;
  12842. const battle = {
  12843. attackers,
  12844. defenders: [enemieHeroes],
  12845. type: 'brawl',
  12846. };
  12847.  
  12848. let countWinBattles = 0;
  12849. let countTestBattle = 10;
  12850. for (let i = 0; i < countTestBattle; i++) {
  12851. battle.seed = Math.floor(Date.now() / 1000) + Math.random() * 1000;
  12852. const result = await Calc(battle);
  12853. if (result.result.win) {
  12854. countWinBattles++;
  12855. }
  12856. if (countWinBattles > 7) {
  12857. console.log(pack)
  12858. return pack.args;
  12859. }
  12860. }
  12861. if (countWinBattles > bestPack.countWin) {
  12862. bestPack.countWin = countWinBattles;
  12863. bestPack.pack = pack.args;
  12864. }
  12865. }
  12866.  
  12867. console.log(bestPack);
  12868. return bestPack.pack;
  12869. }
  12870.  
  12871. async questFarm() {
  12872. const calls = [this.callBrawlQuestFarm];
  12873. const result = await Send(JSON.stringify({ calls }));
  12874. return result.results[0].result.response;
  12875. }
  12876.  
  12877. async getBrawlInfo() {
  12878. const data = await Send(JSON.stringify({
  12879. calls: [
  12880. this.callUserGetInfo,
  12881. this.callBrawlQuestGetInfo,
  12882. this.callBrawlFindEnemies,
  12883. this.callTeamGetMaxUpgrade,
  12884. this.callBrawlGetInfo,
  12885. ]
  12886. }));
  12887.  
  12888. let attempts = data.results[0].result.response.refillable.find(n => n.id == 48);
  12889.  
  12890. const maxUpgrade = data.results[3].result.response;
  12891. const maxHero = Object.values(maxUpgrade.hero);
  12892. const maxTitan = Object.values(maxUpgrade.titan);
  12893. const maxPet = Object.values(maxUpgrade.pet);
  12894. this.maxUpgrade = [...maxHero, ...maxPet, ...maxTitan];
  12895.  
  12896. this.info = data.results[4].result.response;
  12897. this.mandatoryId = lib.data.brawl.promoHero[this.info.id].promoHero;
  12898. return {
  12899. attempts: attempts.amount,
  12900. questInfo: data.results[1].result.response,
  12901. findEnemies: data.results[2].result.response,
  12902. }
  12903. }
  12904.  
  12905. /**
  12906. * Carrying out a fight
  12907. *
  12908. * Проведение боя
  12909. */
  12910. async battle(userId) {
  12911. this.stats.count++;
  12912. const battle = await this.startBattle(userId, this.args);
  12913. const result = await Calc(battle);
  12914. console.log(result.result);
  12915. if (result.result.win) {
  12916. this.stats.win++;
  12917. } else {
  12918. this.stats.loss++;
  12919. if (!this.info.boughtEndlessLivesToday) {
  12920. this.attempts--;
  12921. }
  12922. }
  12923. return await this.endBattle(result);
  12924. // return await this.cancelBattle(result);
  12925. }
  12926.  
  12927. /**
  12928. * Starts a fight
  12929. *
  12930. * Начинает бой
  12931. */
  12932. async startBattle(userId, args) {
  12933. const call = {
  12934. name: "brawl_startBattle",
  12935. args,
  12936. ident: "brawl_startBattle"
  12937. }
  12938. call.args.userId = userId;
  12939. const calls = [call];
  12940. const result = await Send(JSON.stringify({ calls }));
  12941. return result.results[0].result.response;
  12942. }
  12943.  
  12944. cancelBattle(battle) {
  12945. const fixBattle = function (heroes) {
  12946. for (const ids in heroes) {
  12947. const hero = heroes[ids];
  12948. hero.energy = random(1, 999);
  12949. if (hero.hp > 0) {
  12950. hero.hp = random(1, hero.hp);
  12951. }
  12952. }
  12953. }
  12954. fixBattle(battle.progress[0].attackers.heroes);
  12955. fixBattle(battle.progress[0].defenders.heroes);
  12956. return this.endBattle(battle);
  12957. }
  12958.  
  12959. /**
  12960. * Ends the fight
  12961. *
  12962. * Заканчивает бой
  12963. */
  12964. async endBattle(battle) {
  12965. battle.progress[0].attackers.input = ['auto', 0, 0, 'auto', 0, 0];
  12966. const calls = [{
  12967. name: "brawl_endBattle",
  12968. args: {
  12969. result: battle.result,
  12970. progress: battle.progress
  12971. },
  12972. ident: "brawl_endBattle"
  12973. },
  12974. this.callBrawlQuestGetInfo,
  12975. this.callBrawlFindEnemies,
  12976. ];
  12977. const result = await Send(JSON.stringify({ calls }));
  12978. return result.results;
  12979. }
  12980.  
  12981. end(endReason) {
  12982. setIsCancalBattle(true);
  12983. isBrawlsAutoStart = false;
  12984. setProgress(endReason, true);
  12985. console.log(endReason);
  12986. this.resolve();
  12987. }
  12988. }
  12989.  
  12990. this.HWHClasses.executeBrawls = executeBrawls;
  12991.  
  12992. })();
  12993.  
  12994. /**
  12995. * TODO:
  12996. * Получение всех уровней при сборе всех наград (квест на титанит и на энку) +-
  12997. * Добивание на арене титанов
  12998. * Закрытие окошек по Esc +-
  12999. * Починить работу скрипта на уровне команды ниже 10 +-
  13000. * Написать номальную синхронизацию
  13001. * Запрет сбора квестов и отправки экспеиций в промежуток между локальным обновлением и глобальным обновлением дня
  13002. * Улучшение боев
  13003. */