HeroWarsHelper

Automation of actions for the game Hero Wars

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

  1. // ==UserScript==
  2. // @name HeroWarsHelper
  3. // @name:en HeroWarsHelper
  4. // @name:ru HeroWarsHelper
  5. // @namespace HeroWarsHelper
  6. // @version 2.319
  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. },
  586. ru: {
  587. /* Чекбоксы */
  588. SKIP_FIGHTS: 'Пропуск боев',
  589. SKIP_FIGHTS_TITLE: 'Пропуск боев в запределье и арене титанов, автопропуск в башне и кампании',
  590. ENDLESS_CARDS: 'Бесконечные карты',
  591. ENDLESS_CARDS_TITLE: 'Отключить трату карт предсказаний',
  592. AUTO_EXPEDITION: 'АвтоЭкспедиции',
  593. AUTO_EXPEDITION_TITLE: 'Автоотправка экспедиций',
  594. CANCEL_FIGHT: 'Отмена боя',
  595. CANCEL_FIGHT_TITLE: 'Возможность отмены ручного боя на ВГ, СМ и в Асгарде',
  596. GIFTS: 'Подарки',
  597. GIFTS_TITLE: 'Собирать подарки автоматически',
  598. BATTLE_RECALCULATION: 'Прерасчет боя',
  599. BATTLE_RECALCULATION_TITLE: 'Предварительный расчет боя',
  600. QUANTITY_CONTROL: 'Контроль кол-ва',
  601. QUANTITY_CONTROL_TITLE: 'Возможность указывать количество открываемых "лутбоксов"',
  602. REPEAT_CAMPAIGN: 'Повтор в кампании',
  603. REPEAT_CAMPAIGN_TITLE: 'Автоповтор боев в кампании',
  604. DISABLE_DONAT: 'Отключить донат',
  605. DISABLE_DONAT_TITLE: 'Убирает все предложения доната',
  606. DAILY_QUESTS: 'Квесты',
  607. DAILY_QUESTS_TITLE: 'Выполнять ежедневные квесты',
  608. AUTO_QUIZ: 'АвтоВикторина',
  609. AUTO_QUIZ_TITLE: 'Автоматическое получение правильных ответов на вопросы викторины',
  610. SECRET_WEALTH_CHECKBOX: 'Автоматическая покупка в магазине "Тайное Богатство" при заходе в игру',
  611. HIDE_SERVERS: 'Свернуть сервера',
  612. HIDE_SERVERS_TITLE: 'Скрывать неиспользуемые сервера',
  613. /* Поля ввода */
  614. HOW_MUCH_TITANITE: 'Сколько фармим титанита',
  615. COMBAT_SPEED: 'Множитель ускорения боя',
  616. NUMBER_OF_TEST: 'Количество тестовых боев',
  617. NUMBER_OF_AUTO_BATTLE: 'Количество попыток автобоев',
  618. /* Кнопки */
  619. RUN_SCRIPT: 'Запустить скрипт',
  620. TO_DO_EVERYTHING: 'Сделать все',
  621. TO_DO_EVERYTHING_TITLE: 'Выполнить несколько действий',
  622. OUTLAND: 'Запределье',
  623. OUTLAND_TITLE: 'Собрать Запределье',
  624. TITAN_ARENA: 'Турнир Стихий',
  625. TITAN_ARENA_TITLE: 'Автопрохождение Турнира Стихий',
  626. DUNGEON: 'Подземелье',
  627. DUNGEON_TITLE: 'Автопрохождение подземелья',
  628. SEER: 'Провидец',
  629. SEER_TITLE: 'Покрутить Провидца',
  630. TOWER: 'Башня',
  631. TOWER_TITLE: 'Автопрохождение башни',
  632. EXPEDITIONS: 'Экспедиции',
  633. EXPEDITIONS_TITLE: 'Отправка и сбор экспедиций',
  634. SYNC: 'Синхронизация',
  635. SYNC_TITLE: 'Частичная синхронизация данных игры без перезагрузки сатраницы',
  636. ARCHDEMON: 'Архидемон',
  637. FURNACE_OF_SOULS: 'Горнило душ',
  638. ARCHDEMON_TITLE: 'Набивает килы и собирает награду',
  639. ESTER_EGGS: 'Пасхалки',
  640. ESTER_EGGS_TITLE: 'Собрать все пасхалки или награды',
  641. REWARDS: 'Награды',
  642. REWARDS_TITLE: 'Собрать все награды за задания',
  643. MAIL: 'Почта',
  644. MAIL_TITLE: 'Собрать всю почту, кроме писем с энергией и зарядами портала',
  645. MINIONS: 'Прислужники',
  646. MINIONS_TITLE: 'Атакует прислужников сохраннеными пачками',
  647. ADVENTURE: 'Приключение',
  648. ADVENTURE_TITLE: 'Проходит приключение по указанному маршруту',
  649. STORM: 'Буря',
  650. STORM_TITLE: 'Проходит бурю по указанному маршруту',
  651. SANCTUARY: 'Святилище',
  652. SANCTUARY_TITLE: 'Быстрый переход к Святилищу',
  653. GUILD_WAR: 'Война гильдий',
  654. GUILD_WAR_TITLE: 'Быстрый переход к Войне гильдий',
  655. SECRET_WEALTH: 'Тайное богатство',
  656. SECRET_WEALTH_TITLE: 'Купить что-то в магазине "Тайное богатство"',
  657. /* Разное */
  658. BOTTOM_URLS:
  659. '<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>',
  660. GIFTS_SENT: 'Подарки отправлены!',
  661. DO_YOU_WANT: 'Вы действительно хотите это сделать?',
  662. BTN_RUN: 'Запускай',
  663. BTN_CANCEL: 'Отмена',
  664. BTN_ACCEPT: 'Принять',
  665. BTN_OK: 'Ок',
  666. MSG_HAVE_BEEN_DEFEATED: 'Вы потерпели поражение!',
  667. BTN_AUTO: 'Авто',
  668. MSG_YOU_APPLIED: 'Вы нанесли',
  669. MSG_DAMAGE: 'урона',
  670. MSG_CANCEL_AND_STAT: 'Авто (F5) и показать Статистику',
  671. MSG_REPEAT_MISSION: 'Повторить миссию?',
  672. BTN_REPEAT: 'Повторить',
  673. BTN_NO: 'Нет',
  674. MSG_SPECIFY_QUANT: 'Указать количество:',
  675. BTN_OPEN: 'Открыть',
  676. QUESTION_COPY: 'Вопрос скопирован в буфер обмена',
  677. ANSWER_KNOWN: 'Ответ известен',
  678. ANSWER_NOT_KNOWN: 'ВНИМАНИЕ ОТВЕТ НЕ ИЗВЕСТЕН',
  679. BEING_RECALC: 'Идет прерасчет боя',
  680. THIS_TIME: 'На этот раз',
  681. VICTORY: '<span style="color:green;">ПОБЕДА</span>',
  682. DEFEAT: '<span style="color:red;">ПОРАЖЕНИЕ</span>',
  683. CHANCE_TO_WIN: 'Шансы на победу <span style="color:red;">на основе прерасчета</span>',
  684. OPEN_DOLLS: 'матрешек рекурсивно',
  685. SENT_QUESTION: 'Вопрос отправлен',
  686. SETTINGS: 'Настройки',
  687. MSG_BAN_ATTENTION: '<p style="color:red;">Использование этой функции может привести к бану.</p> Продолжить?',
  688. BTN_YES_I_AGREE: 'Да, я беру на себя все риски!',
  689. BTN_NO_I_AM_AGAINST: 'Нет, я отказываюсь от этого!',
  690. VALUES: 'Значения',
  691. EXPEDITIONS_SENT: 'Экспедиции:<br>Собрано: {countGet}<br>Отправлено: {countSend}',
  692. EXPEDITIONS_NOTHING: 'Нечего собирать/отправлять',
  693. EXPEDITIONS_NOTTIME: 'Не время для экспедиций',
  694. TITANIT: 'Титанит',
  695. COMPLETED: 'завершено',
  696. FLOOR: 'Этаж',
  697. LEVEL: 'Уровень',
  698. BATTLES: 'бои',
  699. EVENT: 'Эвент',
  700. NOT_AVAILABLE: 'недоступен',
  701. NO_HEROES: 'Нет героев',
  702. DAMAGE_AMOUNT: 'Количество урона',
  703. NOTHING_TO_COLLECT: 'Нечего собирать',
  704. COLLECTED: 'Собрано',
  705. REWARD: 'наград',
  706. REMAINING_ATTEMPTS: 'Осталось попыток',
  707. BATTLES_CANCELED: 'Битв отменено',
  708. MINION_RAID: 'Рейд прислужников',
  709. STOPPED: 'Остановлено',
  710. REPETITIONS: 'Повторений',
  711. MISSIONS_PASSED: 'Миссий пройдено',
  712. STOP: 'остановить',
  713. TOTAL_OPEN: 'Всего открыто',
  714. OPEN: 'Открыто',
  715. ROUND_STAT: 'Статистика урона за',
  716. BATTLE: 'боев',
  717. MINIMUM: 'Минимальный',
  718. MAXIMUM: 'Максимальный',
  719. AVERAGE: 'Средний',
  720. NOT_THIS_TIME: 'Не в этот раз',
  721. RETRY_LIMIT_EXCEEDED: 'Превышен лимит попыток',
  722. SUCCESS: 'Успех',
  723. RECEIVED: 'Получено',
  724. LETTERS: 'писем',
  725. PORTALS: 'порталов',
  726. ATTEMPTS: 'попыток',
  727. QUEST_10001: 'Улучши умения героев 3 раза',
  728. QUEST_10002: 'Пройди 10 миссий',
  729. QUEST_10003: 'Пройди 3 героические миссии',
  730. QUEST_10004: 'Сразись 3 раза на Арене или Гранд Арене',
  731. QUEST_10006: 'Используй обмен изумрудов 1 раз',
  732. QUEST_10007: 'Соверши 1 призыв в Атриуме Душ',
  733. QUEST_10016: 'Отправь подарки согильдийцам',
  734. QUEST_10018: 'Используй зелье опыта',
  735. QUEST_10019: 'Открой 1 сундук в Башне',
  736. QUEST_10020: 'Открой 3 сундука в Запределье',
  737. QUEST_10021: 'Собери 75 Титанита в Подземелье Гильдии',
  738. QUEST_10021: 'Собери 150 Титанита в Подземелье Гильдии',
  739. QUEST_10023: 'Прокачай Дар Стихий на 1 уровень',
  740. QUEST_10024: 'Повысь уровень любого артефакта один раз',
  741. QUEST_10025: 'Начни 1 Экспедицию',
  742. QUEST_10026: 'Начни 4 Экспедиции',
  743. QUEST_10027: 'Победи в 1 бою Турнира Стихий',
  744. QUEST_10028: 'Повысь уровень любого артефакта титанов',
  745. QUEST_10029: 'Открой сферу артефактов титанов',
  746. QUEST_10030: 'Улучши облик любого героя 1 раз',
  747. QUEST_10031: 'Победи в 6 боях Турнира Стихий',
  748. QUEST_10043: 'Начни или присоеденись к Приключению',
  749. QUEST_10044: 'Воспользуйся призывом питомцев 1 раз',
  750. QUEST_10046: 'Открой 3 сундука в Приключениях',
  751. QUEST_10047: 'Набери 150 очков активности в Гильдии',
  752. NOTHING_TO_DO: 'Нечего выполнять',
  753. YOU_CAN_COMPLETE: 'Можно выполнить квесты',
  754. BTN_DO_IT: 'Выполняй',
  755. NOT_QUEST_COMPLETED: 'Ни одного квеста не выполенно',
  756. COMPLETED_QUESTS: 'Выполнено квестов',
  757. /* everything button */
  758. ASSEMBLE_OUTLAND: 'Собрать Запределье',
  759. PASS_THE_TOWER: 'Пройти башню',
  760. CHECK_EXPEDITIONS: 'Проверить экспедиции',
  761. COMPLETE_TOE: 'Пройти Турнир Стихий',
  762. COMPLETE_DUNGEON: 'Пройти подземелье',
  763. COLLECT_MAIL: 'Собрать почту',
  764. COLLECT_MISC: 'Собрать всякую херню',
  765. COLLECT_MISC_TITLE: 'Собрать пасхалки, камни облика, ключи, монеты арены и Хрусталь души',
  766. COLLECT_QUEST_REWARDS: 'Собрать награды за квесты',
  767. MAKE_A_SYNC: 'Сделать синхронизацию',
  768.  
  769. RUN_FUNCTION: 'Выполнить следующие функции?',
  770. BTN_GO: 'Погнали!',
  771. PERFORMED: 'Выполняется',
  772. DONE: 'Выполнено',
  773. ERRORS_OCCURRES: 'Призошли ошибки при выполнении',
  774. COPY_ERROR: 'Скопировать в буфер информацию об ошибке',
  775. BTN_YES: 'Да',
  776. ALL_TASK_COMPLETED: 'Все задачи выполнены',
  777.  
  778. UNKNOWN: 'Неизвестно',
  779. ENTER_THE_PATH: 'Введите путь приключения через запятые или дефисы',
  780. START_ADVENTURE: 'Начать приключение по этому пути!',
  781. INCORRECT_WAY: 'Неверный путь в приключении: {from} -> {to}',
  782. BTN_CANCELED: 'Отменено',
  783. MUST_TWO_POINTS: 'Путь должен состоять минимум из 2х точек',
  784. MUST_ONLY_NUMBERS: 'Путь должен содержать только цифры и запятые',
  785. NOT_ON_AN_ADVENTURE: 'Вы не в приключении',
  786. YOU_IN_NOT_ON_THE_WAY: 'Указанный путь должен включать точку вашего положения',
  787. ATTEMPTS_NOT_ENOUGH: 'Ваших попыток не достаточно для завершения пути, продолжить?',
  788. YES_CONTINUE: 'Да, продолжай!',
  789. NOT_ENOUGH_AP: 'Попыток не достаточно',
  790. ATTEMPTS_ARE_OVER: 'Попытки закончились',
  791. MOVES: 'Ходы',
  792. BUFF_GET_ERROR: 'Ошибка при получении бафа',
  793. BATTLE_END_ERROR: 'Ошибка завершения боя',
  794. AUTOBOT: 'АвтоБой',
  795. FAILED_TO_WIN_AUTO: 'Не удалось победить в автобою',
  796. ERROR_OF_THE_BATTLE_COPY: 'Призошли ошибка в процессе прохождения боя<br>Скопировать ошибку в буфер обмена?',
  797. ERROR_DURING_THE_BATTLE: 'Ошибка в процессе прохождения боя',
  798. NO_CHANCE_WIN: 'Нет шансов победить в этом бою: 0/',
  799. LOST_HEROES: 'Вы победили, но потеряли одного или несколько героев!',
  800. VICTORY_IMPOSSIBLE: 'Победа не возможна, бъем на результат?',
  801. FIND_COEFF: 'Поиск коэффициента больше чем',
  802. BTN_PASS: 'ПРОПУСК',
  803. BRAWLS: 'Потасовки',
  804. BRAWLS_TITLE: 'Включает возможность автопотасовок',
  805. START_AUTO_BRAWLS: 'Запустить Автопотасовки?',
  806. LOSSES: 'Поражений',
  807. WINS: 'Побед',
  808. FIGHTS: 'Боев',
  809. STAGE: 'Стадия',
  810. DONT_HAVE_LIVES: 'У Вас нет жизней',
  811. LIVES: 'Жизни',
  812. SECRET_WEALTH_ALREADY: 'товар за Зелья питомцев уже куплен',
  813. SECRET_WEALTH_NOT_ENOUGH: 'Не достаточно Зелье Питомца, у Вас {available}, нужно {need}',
  814. SECRET_WEALTH_UPGRADE_NEW_PET: 'После покупки Зелье Питомца будет не достаточно для прокачки нового питомца',
  815. SECRET_WEALTH_PURCHASED: 'Куплено {count} {name}',
  816. SECRET_WEALTH_CANCELED: 'Тайное богатство: покупка отменена',
  817. SECRET_WEALTH_BUY: 'У вас {available} Зелье Питомца.<br>Вы хотите купить {countBuy} {name} за {price} Зелье Питомца?',
  818. DAILY_BONUS: 'Ежедневная награда',
  819. DO_DAILY_QUESTS: 'Сделать ежедневные квесты',
  820. ACTIONS: 'Действия',
  821. ACTIONS_TITLE: 'Диалоговое окно с различными действиями',
  822. OTHERS: 'Разное',
  823. OTHERS_TITLE: 'Диалоговое окно с дополнительными различными действиями',
  824. CHOOSE_ACTION: 'Выберите действие',
  825. OPEN_LOOTBOX: 'У Вас {lootBox} ящиков, откываем?',
  826. STAMINA: 'Энергия',
  827. BOXES_OVER: 'Ящики закончились',
  828. NO_BOXES: 'Нет ящиков',
  829. NO_MORE_ACTIVITY: 'Больше активности за предметы сегодня не получить',
  830. EXCHANGE_ITEMS: 'Обменять предметы на очки активности (не более {maxActive})?',
  831. GET_ACTIVITY: 'Получить активность',
  832. NOT_ENOUGH_ITEMS: 'Предметов недостаточно',
  833. ACTIVITY_RECEIVED: 'Получено активности',
  834. NO_PURCHASABLE_HERO_SOULS: 'Нет доступных для покупки душ героев',
  835. PURCHASED_HERO_SOULS: 'Куплено {countHeroSouls} душ героев',
  836. NOT_ENOUGH_EMERALDS_540: 'Недостаточно изюма, нужно {imgEmerald}540 у Вас {imgEmerald}{currentStarMoney}',
  837. BUY_OUTLAND_BTN: 'Купить {count} сундуков {imgEmerald}{countEmerald}',
  838. CHESTS_NOT_AVAILABLE: 'Сундуки не доступны',
  839. OUTLAND_CHESTS_RECEIVED: 'Получено сундуков Запределья',
  840. RAID_NOT_AVAILABLE: 'Рейд не доступен или сфер нет',
  841. RAID_ADVENTURE: 'Рейд {adventureId} приключения!',
  842. SOMETHING_WENT_WRONG: 'Что-то пошло не так',
  843. ADVENTURE_COMPLETED: 'Приключение {adventureId} пройдено {times} раз',
  844. CLAN_STAT_COPY: 'Клановая статистика скопирована в буфер обмена',
  845. GET_ENERGY: 'Получить энергию',
  846. GET_ENERGY_TITLE: 'Открывает платиновые шкатулки по одной до получения 250 энергии',
  847. ITEM_EXCHANGE: 'Обмен предметов',
  848. ITEM_EXCHANGE_TITLE: 'Обменивает предметы на указанное количество активности',
  849. BUY_SOULS: 'Купить души',
  850. BUY_SOULS_TITLE: 'Купить души героев из всех доступных магазинов',
  851. BUY_OUTLAND: 'Купить Запределье',
  852. BUY_OUTLAND_TITLE: 'Купить 9 сундуков в Запределье за 540 изумрудов',
  853. RAID: 'Рейд',
  854. AUTO_RAID_ADVENTURE: 'Рейд приключения',
  855. AUTO_RAID_ADVENTURE_TITLE: 'Рейд приключения заданное количество раз',
  856. CLAN_STAT: 'Клановая статистика',
  857. CLAN_STAT_TITLE: 'Копирует клановую статистику в буфер обмена',
  858. BTN_AUTO_F5: 'Авто (F5)',
  859. BOSS_DAMAGE: 'Урон по боссу: ',
  860. NOTHING_BUY: 'Нечего покупать',
  861. LOTS_BOUGHT: 'За золото куплено {countBuy} лотов',
  862. BUY_FOR_GOLD: 'Скупить за золото',
  863. BUY_FOR_GOLD_TITLE: 'Скупить предметы за золото в Городской лавке и в магазине Камней Душ Питомцев',
  864. REWARDS_AND_MAIL: 'Награды и почта',
  865. REWARDS_AND_MAIL_TITLE: 'Собирает награды и почту',
  866. COLLECT_REWARDS_AND_MAIL: 'Собрано {countQuests} наград и {countMail} писем',
  867. TIMER_ALREADY: 'Таймер уже запущен {time}',
  868. NO_ATTEMPTS_TIMER_START: 'Попыток нет, запущен таймер {time}',
  869. EPIC_BRAWL_RESULT: '{i} Победы: {wins}/{attempts}, Монеты: {coins}, Серия: {progress}/{nextStage} [Закрыть]{end}',
  870. ATTEMPT_ENDED: '<br>Попытки закончились, запущен таймер {time}',
  871. EPIC_BRAWL: 'Вселенская битва',
  872. EPIC_BRAWL_TITLE: 'Тратит попытки во Вселенской битве',
  873. RELOAD_GAME: 'Перезагрузить игру',
  874. TIMER: 'Таймер:',
  875. SHOW_ERRORS: 'Отображать ошибки',
  876. SHOW_ERRORS_TITLE: 'Отображать ошибки запросов к серверу',
  877. ERROR_MSG: 'Ошибка: {name}<br>{description}',
  878. EVENT_AUTO_BOSS:
  879. 'Максимальное количество боев для расчета:</br>{length} * {countTestBattle} = {maxCalcBattle}</br>Если у Вас слабый компьютер на это может потребоваться много времени, нажмите крестик для отмены.</br>Искать лучший пак из всех или первый подходящий?',
  880. BEST_SLOW: 'Лучший (медленее)',
  881. FIRST_FAST: 'Первый (быстрее)',
  882. FREEZE_INTERFACE: 'Идет расчет... <br> Интерфейс может зависнуть.',
  883. ERROR_F12: 'Ошибка, подробности в консоли (F12)',
  884. FAILED_FIND_WIN_PACK: 'Победный пак найти не удалось',
  885. BEST_PACK: 'Наилучший пак: ',
  886. BOSS_HAS_BEEN_DEF: 'Босс {bossLvl} побежден',
  887. NOT_ENOUGH_ATTEMPTS_BOSS: 'Для победы босса ${bossLvl} не хватило попыток, повторить?',
  888. BOSS_VICTORY_IMPOSSIBLE:
  889. 'По результатам прерасчета {battles} боев победу получить не удалось. Вы хотите продолжить поиск победного боя на реальных боях?',
  890. BOSS_HAS_BEEN_DEF_TEXT:
  891. 'Босс {bossLvl} побежден за<br>{countBattle}/{countMaxBattle} попыток{winTimer}<br>(Сделайте синхронизацию или перезагрузите игру для обновления данных)',
  892. MAP: 'Карта: ',
  893. PLAYER_POS: 'Позиции игроков:',
  894. NY_GIFTS: 'Подарки',
  895. NY_GIFTS_TITLE: 'Открыть все новогодние подарки',
  896. NY_NO_GIFTS: 'Нет не полученных подарков',
  897. NY_GIFTS_COLLECTED: 'Собрано {count} подарков',
  898. CHANGE_MAP: 'Карта острова',
  899. CHANGE_MAP_TITLE: 'Сменить карту острова',
  900. SELECT_ISLAND_MAP: 'Выберите карту острова:',
  901. MAP_NUM: 'Карта {num}',
  902. SECRET_WEALTH_SHOP: 'Тайное богатство {name}: ',
  903. SHOPS: 'Магазины',
  904. SHOPS_DEFAULT: 'Стандартные',
  905. SHOPS_DEFAULT_TITLE: 'Стандартные магазины',
  906. SHOPS_LIST: 'Магазины {number}',
  907. SHOPS_LIST_TITLE: 'Список магазинов {number}',
  908. SHOPS_WARNING:
  909. 'Магазины<br><span style="color:red">Если Вы купите монеты магазинов потасовок за изумруды, то их надо использовать сразу, иначе после перезагрузки игры они пропадут!</span>',
  910. MINIONS_WARNING: 'Пачки героев для атаки приспешников неполные, продолжить?',
  911. FAST_SEASON: 'Быстрый сезон',
  912. FAST_SEASON_TITLE: 'Пропуск экрана с выбором карты в сезоне',
  913. SET_NUMBER_LEVELS: 'Указать колличество уровней:',
  914. POSSIBLE_IMPROVE_LEVELS: 'Возможно улучшить только {count} уровней.<br>Улучшаем?',
  915. NOT_ENOUGH_RESOURECES: 'Не хватает ресурсов',
  916. IMPROVED_LEVELS: 'Улучшено уровней: {count}',
  917. ARTIFACTS_UPGRADE: 'Улучшение артефактов',
  918. ARTIFACTS_UPGRADE_TITLE: 'Улучшает указанное количество самых дешевых артефактов героев',
  919. SKINS_UPGRADE: 'Улучшение обликов',
  920. SKINS_UPGRADE_TITLE: 'Улучшает указанное количество самых дешевых обликов героев',
  921. HINT: '<br>Подсказка: ',
  922. PICTURE: '<br>На картинке: ',
  923. ANSWER: '<br>Ответ: ',
  924. NO_HEROES_PACK: 'Проведите хотя бы один бой для сохранения атакующей команды',
  925. BRAWL_AUTO_PACK: 'Автоподбор пачки',
  926. BRAWL_AUTO_PACK_NOT_CUR_HERO: 'Автоматический подбор пачки не подходит для текущего героя',
  927. BRAWL_DAILY_TASK_COMPLETED: 'Ежедневное задание выполнено, продолжить атаку?',
  928. CALC_STAT: 'Посчитать статистику',
  929. ELEMENT_TOURNAMENT_REWARD: 'Несобранная награда за Турнир Стихий',
  930. BTN_TRY_FIX_IT: 'Исправить',
  931. BTN_TRY_FIX_IT_TITLE: 'Включить исправление боев при автоатаке',
  932. DAMAGE_FIXED: 'Урон исправлен с {lastDamage} до {maxDamage}!',
  933. DAMAGE_NO_FIXED: 'Не удалось исправить урон: {lastDamage}',
  934. LETS_FIX: 'Исправляем',
  935. COUNT_FIXED: 'За {count} попыток',
  936. DEFEAT_TURN_TIMER: 'Поражение! Включить таймер для завершения миссии?',
  937. SEASON_REWARD: 'Награды сезонов',
  938. SEASON_REWARD_TITLE: 'Собирает доступные бесплатные награды со всех текущих сезонов',
  939. SEASON_REWARD_COLLECTED: 'Собрано {count} наград сезонов',
  940. SELL_HERO_SOULS: 'Продать души',
  941. SELL_HERO_SOULS_TITLE: 'Обменивает все души героев с абсолютной звездой на золото',
  942. GOLD_RECEIVED: 'Получено золота: {gold}',
  943. OPEN_ALL_EQUIP_BOXES: 'Открыть все ящики фрагментов экипировки?',
  944. SERVER_NOT_ACCEPT: 'Сервер не принял результат',
  945. INVASION_BOSS_BUFF: 'Для {bossLvl} босса нужен баф {needBuff} у вас {haveBuff}',
  946. HERO_POWER: 'Сила героев',
  947. HERO_POWER_TITLE: 'Отображает текущую и максимальную силу героев',
  948. MAX_POWER_REACHED: 'Максимальная достигнутая мощь: {power}',
  949. CURRENT_POWER: 'Текущая мощь: {power}',
  950. POWER_TO_MAX: 'До максимума мощи осталось: <span style="color:{color};">{power}</span><br>',
  951. BEST_RESULT: 'Лучший результат: {value}%',
  952. },
  953. };
  954.  
  955. function getLang() {
  956. let lang = '';
  957. if (typeof NXFlashVars !== 'undefined') {
  958. lang = NXFlashVars.interface_lang
  959. }
  960. if (!lang) {
  961. lang = (navigator.language || navigator.userLanguage).substr(0, 2);
  962. }
  963. if (lang == 'ru') {
  964. return lang;
  965. }
  966. return 'en';
  967. }
  968.  
  969. this.I18N = function (constant, replace) {
  970. const selectLang = getLang();
  971. if (constant && constant in i18nLangData[selectLang]) {
  972. const result = i18nLangData[selectLang][constant];
  973. if (replace) {
  974. return result.sprintf(replace);
  975. }
  976. return result;
  977. }
  978. return `% ${constant} %`;
  979. };
  980.  
  981. String.prototype.sprintf = String.prototype.sprintf ||
  982. function () {
  983. "use strict";
  984. var str = this.toString();
  985. if (arguments.length) {
  986. var t = typeof arguments[0];
  987. var key;
  988. var args = ("string" === t || "number" === t) ?
  989. Array.prototype.slice.call(arguments)
  990. : arguments[0];
  991.  
  992. for (key in args) {
  993. str = str.replace(new RegExp("\\{" + key + "\\}", "gi"), args[key]);
  994. }
  995. }
  996.  
  997. return str;
  998. };
  999.  
  1000. /**
  1001. * Checkboxes
  1002. *
  1003. * Чекбоксы
  1004. */
  1005. const checkboxes = {
  1006. passBattle: {
  1007. label: I18N('SKIP_FIGHTS'),
  1008. cbox: null,
  1009. title: I18N('SKIP_FIGHTS_TITLE'),
  1010. default: false,
  1011. },
  1012. sendExpedition: {
  1013. label: I18N('AUTO_EXPEDITION'),
  1014. cbox: null,
  1015. title: I18N('AUTO_EXPEDITION_TITLE'),
  1016. default: false,
  1017. },
  1018. cancelBattle: {
  1019. label: I18N('CANCEL_FIGHT'),
  1020. cbox: null,
  1021. title: I18N('CANCEL_FIGHT_TITLE'),
  1022. default: false,
  1023. },
  1024. preCalcBattle: {
  1025. label: I18N('BATTLE_RECALCULATION'),
  1026. cbox: null,
  1027. title: I18N('BATTLE_RECALCULATION_TITLE'),
  1028. default: false,
  1029. },
  1030. countControl: {
  1031. label: I18N('QUANTITY_CONTROL'),
  1032. cbox: null,
  1033. title: I18N('QUANTITY_CONTROL_TITLE'),
  1034. default: true,
  1035. },
  1036. repeatMission: {
  1037. label: I18N('REPEAT_CAMPAIGN'),
  1038. cbox: null,
  1039. title: I18N('REPEAT_CAMPAIGN_TITLE'),
  1040. default: false,
  1041. },
  1042. noOfferDonat: {
  1043. label: I18N('DISABLE_DONAT'),
  1044. cbox: null,
  1045. title: I18N('DISABLE_DONAT_TITLE'),
  1046. /**
  1047. * A crutch to get the field before getting the character id
  1048. *
  1049. * Костыль чтоб получать поле до получения id персонажа
  1050. */
  1051. default: (() => {
  1052. $result = false;
  1053. try {
  1054. $result = JSON.parse(localStorage[GM_info.script.name + ':noOfferDonat']);
  1055. } catch (e) {
  1056. $result = false;
  1057. }
  1058. return $result || false;
  1059. })(),
  1060. },
  1061. dailyQuests: {
  1062. label: I18N('DAILY_QUESTS'),
  1063. cbox: null,
  1064. title: I18N('DAILY_QUESTS_TITLE'),
  1065. default: false,
  1066. },
  1067. // Потасовки
  1068. autoBrawls: {
  1069. label: I18N('BRAWLS'),
  1070. cbox: null,
  1071. title: I18N('BRAWLS_TITLE'),
  1072. default: (() => {
  1073. $result = false;
  1074. try {
  1075. $result = JSON.parse(localStorage[GM_info.script.name + ':autoBrawls']);
  1076. } catch (e) {
  1077. $result = false;
  1078. }
  1079. return $result || false;
  1080. })(),
  1081. hide: false,
  1082. },
  1083. getAnswer: {
  1084. label: I18N('AUTO_QUIZ'),
  1085. cbox: null,
  1086. title: I18N('AUTO_QUIZ_TITLE'),
  1087. default: false,
  1088. hide: true,
  1089. },
  1090. tryFixIt_v2: {
  1091. label: I18N('BTN_TRY_FIX_IT'),
  1092. cbox: null,
  1093. title: I18N('BTN_TRY_FIX_IT_TITLE'),
  1094. default: false,
  1095. hide: false,
  1096. },
  1097. showErrors: {
  1098. label: I18N('SHOW_ERRORS'),
  1099. cbox: null,
  1100. title: I18N('SHOW_ERRORS_TITLE'),
  1101. default: true,
  1102. },
  1103. buyForGold: {
  1104. label: I18N('BUY_FOR_GOLD'),
  1105. cbox: null,
  1106. title: I18N('BUY_FOR_GOLD_TITLE'),
  1107. default: false,
  1108. },
  1109. hideServers: {
  1110. label: I18N('HIDE_SERVERS'),
  1111. cbox: null,
  1112. title: I18N('HIDE_SERVERS_TITLE'),
  1113. default: false,
  1114. },
  1115. fastSeason: {
  1116. label: I18N('FAST_SEASON'),
  1117. cbox: null,
  1118. title: I18N('FAST_SEASON_TITLE'),
  1119. default: false,
  1120. },
  1121. };
  1122. /**
  1123. * Get checkbox state
  1124. *
  1125. * Получить состояние чекбокса
  1126. */
  1127. function isChecked(checkBox) {
  1128. if (!(checkBox in checkboxes)) {
  1129. return false;
  1130. }
  1131. return checkboxes[checkBox].cbox?.checked;
  1132. }
  1133. /**
  1134. * Input fields
  1135. *
  1136. * Поля ввода
  1137. */
  1138. const inputs = {
  1139. countTitanit: {
  1140. input: null,
  1141. title: I18N('HOW_MUCH_TITANITE'),
  1142. default: 150,
  1143. },
  1144. speedBattle: {
  1145. input: null,
  1146. title: I18N('COMBAT_SPEED'),
  1147. default: 5,
  1148. },
  1149. countTestBattle: {
  1150. input: null,
  1151. title: I18N('NUMBER_OF_TEST'),
  1152. default: 10,
  1153. },
  1154. countAutoBattle: {
  1155. input: null,
  1156. title: I18N('NUMBER_OF_AUTO_BATTLE'),
  1157. default: 10,
  1158. },
  1159. FPS: {
  1160. input: null,
  1161. title: 'FPS',
  1162. default: 60,
  1163. }
  1164. }
  1165. /**
  1166. * Checks the checkbox
  1167. *
  1168. * Поплучить данные поля ввода
  1169. */
  1170. function getInput(inputName) {
  1171. return inputs[inputName]?.input?.value;
  1172. }
  1173.  
  1174. /**
  1175. * Control FPS
  1176. *
  1177. * Контроль FPS
  1178. */
  1179. let nextAnimationFrame = Date.now();
  1180. const oldRequestAnimationFrame = this.requestAnimationFrame;
  1181. this.requestAnimationFrame = async function (e) {
  1182. const FPS = Number(getInput('FPS')) || -1;
  1183. const now = Date.now();
  1184. const delay = nextAnimationFrame - now;
  1185. nextAnimationFrame = Math.max(now, nextAnimationFrame) + Math.min(1e3 / FPS, 1e3);
  1186. if (delay > 0) {
  1187. await new Promise((e) => setTimeout(e, delay));
  1188. }
  1189. oldRequestAnimationFrame(e);
  1190. };
  1191. /**
  1192. * Button List
  1193. *
  1194. * Список кнопочек
  1195. */
  1196. const buttons = {
  1197. getOutland: {
  1198. name: I18N('TO_DO_EVERYTHING'),
  1199. title: I18N('TO_DO_EVERYTHING_TITLE'),
  1200. func: testDoYourBest,
  1201. },
  1202. doActions: {
  1203. name: I18N('ACTIONS'),
  1204. title: I18N('ACTIONS_TITLE'),
  1205. func: async function () {
  1206. const popupButtons = [
  1207. {
  1208. msg: I18N('OUTLAND'),
  1209. result: function () {
  1210. confShow(`${I18N('RUN_SCRIPT')} ${I18N('OUTLAND')}?`, getOutland);
  1211. },
  1212. title: I18N('OUTLAND_TITLE'),
  1213. },
  1214. {
  1215. msg: I18N('TOWER'),
  1216. result: function () {
  1217. confShow(`${I18N('RUN_SCRIPT')} ${I18N('TOWER')}?`, testTower);
  1218. },
  1219. title: I18N('TOWER_TITLE'),
  1220. },
  1221. {
  1222. msg: I18N('EXPEDITIONS'),
  1223. result: function () {
  1224. confShow(`${I18N('RUN_SCRIPT')} ${I18N('EXPEDITIONS')}?`, checkExpedition);
  1225. },
  1226. title: I18N('EXPEDITIONS_TITLE'),
  1227. },
  1228. {
  1229. msg: I18N('MINIONS'),
  1230. result: function () {
  1231. confShow(`${I18N('RUN_SCRIPT')} ${I18N('MINIONS')}?`, testRaidNodes);
  1232. },
  1233. title: I18N('MINIONS_TITLE'),
  1234. },
  1235. {
  1236. msg: I18N('ESTER_EGGS'),
  1237. result: function () {
  1238. confShow(`${I18N('RUN_SCRIPT')} ${I18N('ESTER_EGGS')}?`, offerFarmAllReward);
  1239. },
  1240. title: I18N('ESTER_EGGS_TITLE'),
  1241. },
  1242. {
  1243. msg: I18N('STORM'),
  1244. result: function () {
  1245. testAdventure('solo');
  1246. },
  1247. title: I18N('STORM_TITLE'),
  1248. },
  1249. {
  1250. msg: I18N('REWARDS'),
  1251. result: function () {
  1252. confShow(`${I18N('RUN_SCRIPT')} ${I18N('REWARDS')}?`, questAllFarm);
  1253. },
  1254. title: I18N('REWARDS_TITLE'),
  1255. },
  1256. {
  1257. msg: I18N('MAIL'),
  1258. result: function () {
  1259. confShow(`${I18N('RUN_SCRIPT')} ${I18N('MAIL')}?`, mailGetAll);
  1260. },
  1261. title: I18N('MAIL_TITLE'),
  1262. },
  1263. {
  1264. msg: I18N('SEER'),
  1265. result: function () {
  1266. confShow(`${I18N('RUN_SCRIPT')} ${I18N('SEER')}?`, rollAscension);
  1267. },
  1268. title: I18N('SEER_TITLE'),
  1269. },
  1270. /*
  1271. {
  1272. msg: I18N('NY_GIFTS'),
  1273. result: getGiftNewYear,
  1274. title: I18N('NY_GIFTS_TITLE'),
  1275. },
  1276. */
  1277. ];
  1278. popupButtons.push({ result: false, isClose: true });
  1279. const answer = await popup.confirm(`${I18N('CHOOSE_ACTION')}:`, popupButtons);
  1280. if (typeof answer === 'function') {
  1281. answer();
  1282. }
  1283. },
  1284. },
  1285. doOthers: {
  1286. name: I18N('OTHERS'),
  1287. title: I18N('OTHERS_TITLE'),
  1288. func: async function () {
  1289. const popupButtons = [
  1290. {
  1291. msg: I18N('GET_ENERGY'),
  1292. result: farmStamina,
  1293. title: I18N('GET_ENERGY_TITLE'),
  1294. },
  1295. {
  1296. msg: I18N('ITEM_EXCHANGE'),
  1297. result: fillActive,
  1298. title: I18N('ITEM_EXCHANGE_TITLE'),
  1299. },
  1300. {
  1301. msg: I18N('BUY_SOULS'),
  1302. result: function () {
  1303. confShow(`${I18N('RUN_SCRIPT')} ${I18N('BUY_SOULS')}?`, buyHeroFragments);
  1304. },
  1305. title: I18N('BUY_SOULS_TITLE'),
  1306. },
  1307. {
  1308. msg: I18N('BUY_FOR_GOLD'),
  1309. result: function () {
  1310. confShow(`${I18N('RUN_SCRIPT')} ${I18N('BUY_FOR_GOLD')}?`, buyInStoreForGold);
  1311. },
  1312. title: I18N('BUY_FOR_GOLD_TITLE'),
  1313. },
  1314. {
  1315. msg: I18N('BUY_OUTLAND'),
  1316. result: bossOpenChestPay,
  1317. title: I18N('BUY_OUTLAND_TITLE'),
  1318. },
  1319. {
  1320. msg: I18N('AUTO_RAID_ADVENTURE'),
  1321. result: autoRaidAdventure,
  1322. title: I18N('AUTO_RAID_ADVENTURE_TITLE'),
  1323. },
  1324. {
  1325. msg: I18N('CLAN_STAT'),
  1326. result: clanStatistic,
  1327. title: I18N('CLAN_STAT_TITLE'),
  1328. },
  1329. {
  1330. msg: I18N('EPIC_BRAWL'),
  1331. result: async function () {
  1332. confShow(`${I18N('RUN_SCRIPT')} ${I18N('EPIC_BRAWL')}?`, () => {
  1333. const brawl = new epicBrawl();
  1334. brawl.start();
  1335. });
  1336. },
  1337. title: I18N('EPIC_BRAWL_TITLE'),
  1338. },
  1339. {
  1340. msg: I18N('ARTIFACTS_UPGRADE'),
  1341. result: updateArtifacts,
  1342. title: I18N('ARTIFACTS_UPGRADE_TITLE'),
  1343. },
  1344. {
  1345. msg: I18N('SKINS_UPGRADE'),
  1346. result: updateSkins,
  1347. title: I18N('SKINS_UPGRADE_TITLE'),
  1348. },
  1349. {
  1350. msg: I18N('SEASON_REWARD'),
  1351. result: farmBattlePass,
  1352. title: I18N('SEASON_REWARD_TITLE'),
  1353. },
  1354. {
  1355. msg: I18N('SELL_HERO_SOULS'),
  1356. result: sellHeroSoulsForGold,
  1357. title: I18N('SELL_HERO_SOULS_TITLE'),
  1358. },
  1359. {
  1360. msg: I18N('CHANGE_MAP'),
  1361. result: async function () {
  1362. const maps = Object.values(lib.data.seasonAdventure.list)
  1363. .filter((e) => e.map.cells.length > 2)
  1364. .map((i) => ({
  1365. msg: I18N('MAP_NUM', { num: i.id }),
  1366. result: i.id,
  1367. }));
  1368.  
  1369. const result = await popup.confirm(I18N('SELECT_ISLAND_MAP'), [...maps, { result: false, isClose: true }]);
  1370. if (result) {
  1371. cheats.changeIslandMap(result);
  1372. }
  1373. },
  1374. title: I18N('CHANGE_MAP_TITLE'),
  1375. },
  1376. {
  1377. msg: I18N('HERO_POWER'),
  1378. result: async () => {
  1379. const calls = ['userGetInfo', 'heroGetAll'].map((name) => ({
  1380. name,
  1381. args: {},
  1382. ident: name,
  1383. }));
  1384. const [maxHeroSumPower, heroSumPower] = await Send({ calls }).then((e) => [
  1385. e.results[0].result.response.maxSumPower.heroes,
  1386. Object.values(e.results[1].result.response).reduce((a, e) => a + e.power, 0),
  1387. ]);
  1388. const power = maxHeroSumPower - heroSumPower;
  1389. let msg =
  1390. I18N('MAX_POWER_REACHED', { power: maxHeroSumPower.toLocaleString() }) +
  1391. '<br>' +
  1392. I18N('CURRENT_POWER', { power: heroSumPower.toLocaleString() }) +
  1393. '<br>' +
  1394. I18N('POWER_TO_MAX', { power: power.toLocaleString(), color: power >= 4000 ? 'green' : 'red' });
  1395. await popup.confirm(msg, [{ msg: I18N('BTN_OK'), result: 0 }]);
  1396. },
  1397. title: I18N('HERO_POWER_TITLE'),
  1398. },
  1399. ];
  1400. popupButtons.push({ result: false, isClose: true });
  1401. const answer = await popup.confirm(`${I18N('CHOOSE_ACTION')}:`, popupButtons);
  1402. if (typeof answer === 'function') {
  1403. answer();
  1404. }
  1405. },
  1406. },
  1407. testTitanArena: {
  1408. name: I18N('TITAN_ARENA'),
  1409. title: I18N('TITAN_ARENA_TITLE'),
  1410. func: function () {
  1411. confShow(`${I18N('RUN_SCRIPT')} ${I18N('TITAN_ARENA')}?`, testTitanArena);
  1412. },
  1413. },
  1414. testDungeon: {
  1415. name: I18N('DUNGEON'),
  1416. title: I18N('DUNGEON_TITLE'),
  1417. func: function () {
  1418. confShow(`${I18N('RUN_SCRIPT')} ${I18N('DUNGEON')}?`, testDungeon);
  1419. },
  1420. },
  1421. // Архидемон
  1422. bossRatingEvent: {
  1423. name: I18N('ARCHDEMON'),
  1424. title: I18N('ARCHDEMON_TITLE'),
  1425. func: function () {
  1426. confShow(`${I18N('RUN_SCRIPT')} ${I18N('ARCHDEMON')}?`, bossRatingEvent);
  1427. },
  1428. hide: true,
  1429. },
  1430. // Горнило душ
  1431. bossRatingEvent: {
  1432. name: I18N('FURNACE_OF_SOULS'),
  1433. title: I18N('ARCHDEMON_TITLE'),
  1434. func: function () {
  1435. confShow(`${I18N('RUN_SCRIPT')} ${I18N('FURNACE_OF_SOULS')}?`, bossRatingEventSouls);
  1436. },
  1437. hide: true,
  1438. },
  1439. rewardsAndMailFarm: {
  1440. name: I18N('REWARDS_AND_MAIL'),
  1441. title: I18N('REWARDS_AND_MAIL_TITLE'),
  1442. func: function () {
  1443. confShow(`${I18N('RUN_SCRIPT')} ${I18N('REWARDS_AND_MAIL')}?`, rewardsAndMailFarm);
  1444. },
  1445. },
  1446. testAdventure: {
  1447. name: I18N('ADVENTURE'),
  1448. title: I18N('ADVENTURE_TITLE'),
  1449. func: () => {
  1450. testAdventure();
  1451. },
  1452. },
  1453. goToSanctuary: {
  1454. name: I18N('SANCTUARY'),
  1455. title: I18N('SANCTUARY_TITLE'),
  1456. func: cheats.goSanctuary,
  1457. },
  1458. goToClanWar: {
  1459. name: I18N('GUILD_WAR'),
  1460. title: I18N('GUILD_WAR_TITLE'),
  1461. func: cheats.goClanWar,
  1462. },
  1463. dailyQuests: {
  1464. name: I18N('DAILY_QUESTS'),
  1465. title: I18N('DAILY_QUESTS_TITLE'),
  1466. func: async function () {
  1467. const quests = new dailyQuests(
  1468. () => {},
  1469. () => {}
  1470. );
  1471. await quests.autoInit();
  1472. quests.start();
  1473. },
  1474. },
  1475. newDay: {
  1476. name: I18N('SYNC'),
  1477. title: I18N('SYNC_TITLE'),
  1478. func: function () {
  1479. confShow(`${I18N('RUN_SCRIPT')} ${I18N('SYNC')}?`, cheats.refreshGame);
  1480. },
  1481. },
  1482. };
  1483. /**
  1484. * Display buttons
  1485. *
  1486. * Вывести кнопочки
  1487. */
  1488. function addControlButtons() {
  1489. for (let name in buttons) {
  1490. button = buttons[name];
  1491. if (button.hide) {
  1492. continue;
  1493. }
  1494. button['button'] = scriptMenu.addButton(button.name, button.func, button.title);
  1495. }
  1496. }
  1497. /**
  1498. * Adds links
  1499. *
  1500. * Добавляет ссылки
  1501. */
  1502. function addBottomUrls() {
  1503. scriptMenu.addHeader(I18N('BOTTOM_URLS'));
  1504. }
  1505. /**
  1506. * Stop repetition of the mission
  1507. *
  1508. * Остановить повтор миссии
  1509. */
  1510. let isStopSendMission = false;
  1511. /**
  1512. * There is a repetition of the mission
  1513. *
  1514. * Идет повтор миссии
  1515. */
  1516. let isSendsMission = false;
  1517. /**
  1518. * Data on the past mission
  1519. *
  1520. * Данные о прошедшей мисии
  1521. */
  1522. let lastMissionStart = {}
  1523. /**
  1524. * Start time of the last battle in the company
  1525. *
  1526. * Время начала последнего боя в кампании
  1527. */
  1528. let lastMissionBattleStart = 0;
  1529. /**
  1530. * Data for calculating the last battle with the boss
  1531. *
  1532. * Данные для расчете последнего боя с боссом
  1533. */
  1534. let lastBossBattle = null;
  1535. /**
  1536. * Information about the last battle
  1537. *
  1538. * Данные о прошедшей битве
  1539. */
  1540. let lastBattleArg = {}
  1541. let lastBossBattleStart = null;
  1542. this.addBattleTimer = 4;
  1543. this.invasionTimer = 2500;
  1544. const invasionInfo = {
  1545. buff: 0,
  1546. bossLvl: 130,
  1547. };
  1548. const invasionDataPacks = {
  1549. 130: { buff: 0, pet: 6004, heroes: [58, 48, 16, 65, 59], favor: { 16: 6004, 48: 6001, 58: 6002, 59: 6005, 65: 6000 } },
  1550. 140: { buff: 0, pet: 6006, heroes: [1, 4, 13, 58, 65], favor: { 1: 6001, 4: 6006, 13: 6002, 58: 6005, 65: 6000 } },
  1551. 150: { buff: 0, pet: 6006, heroes: [1, 12, 17, 21, 65], favor: { 1: 6001, 12: 6003, 17: 6006, 21: 6002, 65: 6000 } },
  1552. 160: { buff: 0, pet: 6008, heroes: [12, 21, 34, 58, 65], favor: { 12: 6003, 21: 6006, 34: 6008, 58: 6002, 65: 6001 } },
  1553. 170: { buff: 0, pet: 6005, heroes: [33, 12, 65, 21, 4], favor: { 4: 6001, 12: 6003, 21: 6006, 33: 6008, 65: 6000 } },
  1554. 180: { buff: 20, pet: 6009, heroes: [58, 13, 5, 17, 65], favor: { 5: 6006, 13: 6003, 58: 6005 } },
  1555. 190: { buff: 0, pet: 6006, heroes: [1, 12, 21, 36, 65], favor: { 1: 6004, 12: 6003, 21: 6006, 36: 6005, 65: 6000 } },
  1556. 200: { buff: 0, pet: 6006, heroes: [12, 1, 13, 2, 65], favor: { 2: 6001, 12: 6003, 13: 6006, 65: 6000 } },
  1557. 210: { buff: 15, pet: 6005, heroes: [12, 21, 33, 58, 65], favor: { 12: 6003, 21: 6006, 33: 6008, 58: 6005, 65: 6001 } },
  1558. 220: { buff: 5, pet: 6006, heroes: [58, 13, 7, 34, 65], favor: { 7: 6002, 13: 6008, 34: 6006, 58: 6005, 65: 6001 } },
  1559. 230: { buff: 35, pet: 6005, heroes: [5, 7, 13, 58, 65], favor: { 5: 6006, 7: 6003, 13: 6002, 58: 6005, 65: 6000 } },
  1560. 240: { buff: 0, pet: 6005, heroes: [12, 58, 1, 36, 65], favor: { 1: 6006, 12: 6003, 36: 6005, 65: 6001 } },
  1561. 250: { buff: 15, pet: 6005, heroes: [12, 36, 4, 16, 65], favor: { 12: 6003, 16: 6004, 36: 6005, 65: 6001 } },
  1562. 260: { buff: 15, pet: 6005, heroes: [48, 12, 36, 65, 4], favor: { 4: 6006, 12: 6003, 36: 6005, 48: 6000, 65: 6007 } },
  1563. 270: { buff: 35, pet: 6005, heroes: [12, 58, 36, 4, 65], favor: { 4: 6006, 12: 6003, 36: 6005 } },
  1564. 280: { buff: 80, pet: 6005, heroes: [21, 36, 48, 7, 65], favor: { 7: 6003, 21: 6006, 36: 6005, 48: 6001, 65: 6000 } },
  1565. 290: { buff: 95, pet: 6008, heroes: [12, 21, 36, 35, 65], favor: { 12: 6003, 21: 6006, 36: 6005, 65: 6007 } },
  1566. 300: { buff: 25, pet: 6005, heroes: [12, 13, 4, 34, 65], favor: { 4: 6006, 12: 6003, 13: 6007, 34: 6002 } },
  1567. 310: { buff: 45, pet: 6005, heroes: [12, 21, 58, 33, 65], favor: { 12: 6003, 21: 6006, 33: 6002, 58: 6005, 65: 6007 } },
  1568. 320: { buff: 70, pet: 6005, heroes: [12, 48, 2, 6, 65], favor: { 6: 6005, 12: 6003 } },
  1569. 330: { buff: 70, pet: 6005, heroes: [12, 21, 36, 5, 65], favor: { 5: 6002, 12: 6003, 21: 6006, 36: 6005, 65: 6000 } },
  1570. 340: { buff: 55, pet: 6009, heroes: [12, 36, 13, 6, 65], favor: { 6: 6005, 12: 6003, 13: 6002, 36: 6006, 65: 6000 } },
  1571. 350: { buff: 100, pet: 6005, heroes: [12, 21, 58, 34, 65], favor: { 12: 6003, 21: 6006, 58: 6005 } },
  1572. 360: { buff: 85, pet: 6007, heroes: [12, 21, 36, 4, 65], favor: { 4: 6006, 12: 6003, 21: 6002, 36: 6005 } },
  1573. 370: { buff: 90, pet: 6008, heroes: [12, 21, 36, 13, 65], favor: { 12: 6003, 13: 6007, 21: 6006, 36: 6005, 65: 6001 } },
  1574. 380: { buff: 165, pet: 6005, heroes: [12, 33, 36, 4, 65], favor: { 4: 6001, 12: 6003, 33: 6006 } },
  1575. 390: { buff: 235, pet: 6005, heroes: [21, 58, 48, 2, 65], favor: { 2: 6005, 21: 6002 } },
  1576. 400: { buff: 125, pet: 6006, heroes: [12, 21, 36, 48, 65], favor: { 12: 6003, 21: 6006, 36: 6005, 48: 6001, 65: 6007 } },
  1577. };
  1578. /**
  1579. * The name of the function of the beginning of the battle
  1580. *
  1581. * Имя функции начала боя
  1582. */
  1583. let nameFuncStartBattle = '';
  1584. /**
  1585. * The name of the function of the end of the battle
  1586. *
  1587. * Имя функции конца боя
  1588. */
  1589. let nameFuncEndBattle = '';
  1590. /**
  1591. * Data for calculating the last battle
  1592. *
  1593. * Данные для расчета последнего боя
  1594. */
  1595. let lastBattleInfo = null;
  1596. /**
  1597. * The ability to cancel the battle
  1598. *
  1599. * Возможность отменить бой
  1600. */
  1601. let isCancalBattle = true;
  1602.  
  1603. function setIsCancalBattle(value) {
  1604. isCancalBattle = value;
  1605. }
  1606.  
  1607. /**
  1608. * Certificator of the last open nesting doll
  1609. *
  1610. * Идетификатор последней открытой матрешки
  1611. */
  1612. let lastRussianDollId = null;
  1613. /**
  1614. * Cancel the training guide
  1615. *
  1616. * Отменить обучающее руководство
  1617. */
  1618. this.isCanceledTutorial = false;
  1619.  
  1620. /**
  1621. * Data from the last question of the quiz
  1622. *
  1623. * Данные последнего вопроса викторины
  1624. */
  1625. let lastQuestion = null;
  1626. /**
  1627. * Answer to the last question of the quiz
  1628. *
  1629. * Ответ на последний вопрос викторины
  1630. */
  1631. let lastAnswer = null;
  1632. /**
  1633. * Flag for opening keys or titan artifact spheres
  1634. *
  1635. * Флаг открытия ключей или сфер артефактов титанов
  1636. */
  1637. let artifactChestOpen = false;
  1638. /**
  1639. * The name of the function to open keys or orbs of titan artifacts
  1640. *
  1641. * Имя функции открытия ключей или сфер артефактов титанов
  1642. */
  1643. let artifactChestOpenCallName = '';
  1644. let correctShowOpenArtifact = 0;
  1645. /**
  1646. * Data for the last battle in the dungeon
  1647. * (Fix endless cards)
  1648. *
  1649. * Данные для последнего боя в подземке
  1650. * (Исправление бесконечных карт)
  1651. */
  1652. let lastDungeonBattleData = null;
  1653. /**
  1654. * Start time of the last battle in the dungeon
  1655. *
  1656. * Время начала последнего боя в подземелье
  1657. */
  1658. let lastDungeonBattleStart = 0;
  1659. /**
  1660. * Subscription end time
  1661. *
  1662. * Время окончания подписки
  1663. */
  1664. let subEndTime = 0;
  1665. /**
  1666. * Number of prediction cards
  1667. *
  1668. * Количество карт предсказаний
  1669. */
  1670. let countPredictionCard = 0;
  1671.  
  1672. /**
  1673. * Brawl pack
  1674. *
  1675. * Пачка для потасовок
  1676. */
  1677. let brawlsPack = null;
  1678. /**
  1679. * Autobrawl started
  1680. *
  1681. * Автопотасовка запущена
  1682. */
  1683. let isBrawlsAutoStart = false;
  1684. let clanDominationGetInfo = null;
  1685. /**
  1686. * Copies the text to the clipboard
  1687. *
  1688. * Копирует тест в буфер обмена
  1689. * @param {*} text copied text // копируемый текст
  1690. */
  1691. function copyText(text) {
  1692. let copyTextarea = document.createElement("textarea");
  1693. copyTextarea.style.opacity = "0";
  1694. copyTextarea.textContent = text;
  1695. document.body.appendChild(copyTextarea);
  1696. copyTextarea.select();
  1697. document.execCommand("copy");
  1698. document.body.removeChild(copyTextarea);
  1699. delete copyTextarea;
  1700. }
  1701. /**
  1702. * Returns the history of requests
  1703. *
  1704. * Возвращает историю запросов
  1705. */
  1706. this.getRequestHistory = function() {
  1707. return requestHistory;
  1708. }
  1709. /**
  1710. * Generates a random integer from min to max
  1711. *
  1712. * Гененирует случайное целое число от min до max
  1713. */
  1714. const random = function (min, max) {
  1715. return Math.floor(Math.random() * (max - min + 1) + min);
  1716. }
  1717. const randf = function (min, max) {
  1718. return Math.random() * (max - min + 1) + min;
  1719. };
  1720. /**
  1721. * Clearing the request history
  1722. *
  1723. * Очистка истоии запросов
  1724. */
  1725. setInterval(function () {
  1726. let now = Date.now();
  1727. for (let i in requestHistory) {
  1728. const time = +i.split('_')[0];
  1729. if (now - time > 300000) {
  1730. delete requestHistory[i];
  1731. }
  1732. }
  1733. }, 300000);
  1734. /**
  1735. * Displays the dialog box
  1736. *
  1737. * Отображает диалоговое окно
  1738. */
  1739. function confShow(message, yesCallback, noCallback) {
  1740. let buts = [];
  1741. message = message || I18N('DO_YOU_WANT');
  1742. noCallback = noCallback || (() => {});
  1743. if (yesCallback) {
  1744. buts = [
  1745. { msg: I18N('BTN_RUN'), result: true},
  1746. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true},
  1747. ]
  1748. } else {
  1749. yesCallback = () => {};
  1750. buts = [
  1751. { msg: I18N('BTN_OK'), result: true},
  1752. ];
  1753. }
  1754. popup.confirm(message, buts).then((e) => {
  1755. // dialogPromice = null;
  1756. if (e) {
  1757. yesCallback();
  1758. } else {
  1759. noCallback();
  1760. }
  1761. });
  1762. }
  1763. /**
  1764. * Override/proxy the method for creating a WS package send
  1765. *
  1766. * Переопределяем/проксируем метод создания отправки WS пакета
  1767. */
  1768. WebSocket.prototype.send = function (data) {
  1769. if (!this.isSetOnMessage) {
  1770. const oldOnmessage = this.onmessage;
  1771. this.onmessage = function (event) {
  1772. try {
  1773. const data = JSON.parse(event.data);
  1774. if (!this.isWebSocketLogin && data.result.type == "iframeEvent.login") {
  1775. this.isWebSocketLogin = true;
  1776. } else if (data.result.type == "iframeEvent.login") {
  1777. return;
  1778. }
  1779. } catch (e) { }
  1780. return oldOnmessage.apply(this, arguments);
  1781. }
  1782. this.isSetOnMessage = true;
  1783. }
  1784. original.SendWebSocket.call(this, data);
  1785. }
  1786. /**
  1787. * Overriding/Proxying the Ajax Request Creation Method
  1788. *
  1789. * Переопределяем/проксируем метод создания Ajax запроса
  1790. */
  1791. XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
  1792. this.uniqid = Date.now() + '_' + random(1000000, 10000000);
  1793. this.errorRequest = false;
  1794. if (method == 'POST' && url.includes('.nextersglobal.com/api/') && /api\/$/.test(url)) {
  1795. if (!apiUrl) {
  1796. apiUrl = url;
  1797. const socialInfo = /heroes-(.+?)\./.exec(apiUrl);
  1798. console.log(socialInfo);
  1799. }
  1800. requestHistory[this.uniqid] = {
  1801. method,
  1802. url,
  1803. error: [],
  1804. headers: {},
  1805. request: null,
  1806. response: null,
  1807. signature: [],
  1808. calls: {},
  1809. };
  1810. } else if (method == 'POST' && url.includes('error.nextersglobal.com/client/')) {
  1811. this.errorRequest = true;
  1812. }
  1813. return original.open.call(this, method, url, async, user, password);
  1814. };
  1815. /**
  1816. * Overriding/Proxying the header setting method for the AJAX request
  1817. *
  1818. * Переопределяем/проксируем метод установки заголовков для AJAX запроса
  1819. */
  1820. XMLHttpRequest.prototype.setRequestHeader = function (name, value, check) {
  1821. if (this.uniqid in requestHistory) {
  1822. requestHistory[this.uniqid].headers[name] = value;
  1823. } else {
  1824. check = true;
  1825. }
  1826.  
  1827. if (name == 'X-Auth-Signature') {
  1828. requestHistory[this.uniqid].signature.push(value);
  1829. if (!check) {
  1830. return;
  1831. }
  1832. }
  1833.  
  1834. return original.setRequestHeader.call(this, name, value);
  1835. };
  1836. /**
  1837. * Overriding/Proxying the AJAX Request Sending Method
  1838. *
  1839. * Переопределяем/проксируем метод отправки AJAX запроса
  1840. */
  1841. XMLHttpRequest.prototype.send = async function (sourceData) {
  1842. if (this.uniqid in requestHistory) {
  1843. let tempData = null;
  1844. if (getClass(sourceData) == "ArrayBuffer") {
  1845. tempData = decoder.decode(sourceData);
  1846. } else {
  1847. tempData = sourceData;
  1848. }
  1849. requestHistory[this.uniqid].request = tempData;
  1850. let headers = requestHistory[this.uniqid].headers;
  1851. lastHeaders = Object.assign({}, headers);
  1852. /**
  1853. * Game loading event
  1854. *
  1855. * Событие загрузки игры
  1856. */
  1857. if (headers["X-Request-Id"] > 2 && !isLoadGame) {
  1858. isLoadGame = true;
  1859. if (cheats.libGame) {
  1860. lib.setData(cheats.libGame);
  1861. } else {
  1862. lib.setData(await cheats.LibLoad());
  1863. }
  1864. addControls();
  1865. addControlButtons();
  1866. addBottomUrls();
  1867.  
  1868. if (isChecked('sendExpedition')) {
  1869. const isTimeBetweenDays = isTimeBetweenNewDays();
  1870. if (!isTimeBetweenDays) {
  1871. checkExpedition();
  1872. } else {
  1873. setProgress(I18N('EXPEDITIONS_NOTTIME'), true);
  1874. }
  1875. }
  1876.  
  1877. getAutoGifts();
  1878.  
  1879. cheats.activateHacks();
  1880. justInfo();
  1881. if (isChecked('dailyQuests')) {
  1882. testDailyQuests();
  1883. }
  1884.  
  1885. if (isChecked('buyForGold')) {
  1886. buyInStoreForGold();
  1887. }
  1888. }
  1889. /**
  1890. * Outgoing request data processing
  1891. *
  1892. * Обработка данных исходящего запроса
  1893. */
  1894. sourceData = await checkChangeSend.call(this, sourceData, tempData);
  1895. /**
  1896. * Handling incoming request data
  1897. *
  1898. * Обработка данных входящего запроса
  1899. */
  1900. const oldReady = this.onreadystatechange;
  1901. this.onreadystatechange = async function (e) {
  1902. if (this.errorRequest) {
  1903. return oldReady.apply(this, arguments);
  1904. }
  1905. if(this.readyState == 4 && this.status == 200) {
  1906. isTextResponse = this.responseType === "text" || this.responseType === "";
  1907. let response = isTextResponse ? this.responseText : this.response;
  1908. requestHistory[this.uniqid].response = response;
  1909. /**
  1910. * Replacing incoming request data
  1911. *
  1912. * Заменна данных входящего запроса
  1913. */
  1914. if (isTextResponse) {
  1915. await checkChangeResponse.call(this, response);
  1916. }
  1917. /**
  1918. * A function to run after the request is executed
  1919. *
  1920. * Функция запускаемая после выполения запроса
  1921. */
  1922. if (typeof this.onReadySuccess == 'function') {
  1923. setTimeout(this.onReadySuccess, 500);
  1924. }
  1925. /** Удаляем из истории запросов битвы с боссом */
  1926. if ('invasion_bossStart' in requestHistory[this.uniqid].calls) delete requestHistory[this.uniqid];
  1927. }
  1928. if (oldReady) {
  1929. try {
  1930. return oldReady.apply(this, arguments);
  1931. } catch(e) {
  1932. console.log(oldReady);
  1933. console.error('Error in oldReady:', e);
  1934. }
  1935.  
  1936. }
  1937. }
  1938. }
  1939. if (this.errorRequest) {
  1940. const oldReady = this.onreadystatechange;
  1941. this.onreadystatechange = function () {
  1942. Object.defineProperty(this, 'status', {
  1943. writable: true
  1944. });
  1945. this.status = 200;
  1946. Object.defineProperty(this, 'readyState', {
  1947. writable: true
  1948. });
  1949. this.readyState = 4;
  1950. Object.defineProperty(this, 'responseText', {
  1951. writable: true
  1952. });
  1953. this.responseText = JSON.stringify({
  1954. "result": true
  1955. });
  1956. if (typeof this.onReadySuccess == 'function') {
  1957. setTimeout(this.onReadySuccess, 200);
  1958. }
  1959. return oldReady.apply(this, arguments);
  1960. }
  1961. this.onreadystatechange();
  1962. } else {
  1963. try {
  1964. return original.send.call(this, sourceData);
  1965. } catch(e) {
  1966. debugger;
  1967. }
  1968. }
  1969. };
  1970. /**
  1971. * Processing and substitution of outgoing data
  1972. *
  1973. * Обработка и подмена исходящих данных
  1974. */
  1975. async function checkChangeSend(sourceData, tempData) {
  1976. try {
  1977. /**
  1978. * A function that replaces battle data with incorrect ones to cancel combatя
  1979. *
  1980. * Функция заменяющая данные боя на неверные для отмены боя
  1981. */
  1982. const fixBattle = function (heroes) {
  1983. for (const ids in heroes) {
  1984. hero = heroes[ids];
  1985. hero.energy = random(1, 999);
  1986. if (hero.hp > 0) {
  1987. hero.hp = random(1, hero.hp);
  1988. }
  1989. }
  1990. }
  1991. /**
  1992. * Dialog window 2
  1993. *
  1994. * Диалоговое окно 2
  1995. */
  1996. const showMsg = async function (msg, ansF, ansS) {
  1997. if (typeof popup == 'object') {
  1998. return await popup.confirm(msg, [
  1999. {msg: ansF, result: false},
  2000. {msg: ansS, result: true},
  2001. ]);
  2002. } else {
  2003. return !confirm(`${msg}\n ${ansF} (${I18N('BTN_OK')})\n ${ansS} (${I18N('BTN_CANCEL')})`);
  2004. }
  2005. }
  2006. /**
  2007. * Dialog window 3
  2008. *
  2009. * Диалоговое окно 3
  2010. */
  2011. const showMsgs = async function (msg, ansF, ansS, ansT) {
  2012. return await popup.confirm(msg, [
  2013. {msg: ansF, result: 0},
  2014. {msg: ansS, result: 1},
  2015. {msg: ansT, result: 2},
  2016. ]);
  2017. }
  2018.  
  2019. let changeRequest = false;
  2020. testData = JSON.parse(tempData);
  2021. for (const call of testData.calls) {
  2022. if (!artifactChestOpen) {
  2023. requestHistory[this.uniqid].calls[call.name] = call.ident;
  2024. }
  2025. /**
  2026. * Cancellation of the battle in adventures, on VG and with minions of Asgard
  2027. * Отмена боя в приключениях, на ВГ и с прислужниками Асгарда
  2028. */
  2029. if ((call.name == 'adventure_endBattle' ||
  2030. call.name == 'adventureSolo_endBattle' ||
  2031. call.name == 'clanWarEndBattle' &&
  2032. isChecked('cancelBattle') ||
  2033. call.name == 'crossClanWar_endBattle' &&
  2034. isChecked('cancelBattle') ||
  2035. call.name == 'brawl_endBattle' ||
  2036. call.name == 'towerEndBattle' ||
  2037. call.name == 'invasion_bossEnd' ||
  2038. call.name == 'titanArenaEndBattle' ||
  2039. call.name == 'bossEndBattle' ||
  2040. call.name == 'clanRaid_endNodeBattle') &&
  2041. isCancalBattle) {
  2042. nameFuncEndBattle = call.name;
  2043.  
  2044. if (isChecked('tryFixIt_v2') &&
  2045. !call.args.result.win &&
  2046. (call.name == 'brawl_endBattle' ||
  2047. //call.name == 'crossClanWar_endBattle' ||
  2048. call.name == 'epicBrawl_endBattle' ||
  2049. //call.name == 'clanWarEndBattle' ||
  2050. call.name == 'adventure_endBattle' ||
  2051. call.name == 'titanArenaEndBattle' ||
  2052. call.name == 'bossEndBattle' ||
  2053. call.name == 'adventureSolo_endBattle') &&
  2054. lastBattleInfo) {
  2055. const noFixWin = call.name == 'clanWarEndBattle' || call.name == 'crossClanWar_endBattle';
  2056. const cloneBattle = structuredClone(lastBattleInfo);
  2057. lastBattleInfo = null;
  2058. try {
  2059. const { BestOrWinFixBattle } = HWHClasses;
  2060. const bFix = new BestOrWinFixBattle(cloneBattle);
  2061. bFix.setNoMakeWin(noFixWin);
  2062. let endTime = Date.now() + 3e4;
  2063. if (endTime < cloneBattle.endTime) {
  2064. endTime = cloneBattle.endTime;
  2065. }
  2066. const result = await bFix.start(cloneBattle.endTime, 150);
  2067.  
  2068. if (result.result.win) {
  2069. call.args.result = result.result;
  2070. call.args.progress = result.progress;
  2071. changeRequest = true;
  2072. } else if (result.value) {
  2073. if (
  2074. await popup.confirm(I18N('DEFEAT') + '<br>' + I18N('BEST_RESULT', { value: result.value }), [
  2075. { msg: I18N('BTN_CANCEL'), result: 0 },
  2076. { msg: I18N('BTN_ACCEPT'), result: 1 },
  2077. ])
  2078. ) {
  2079. call.args.result = result.result;
  2080. call.args.progress = result.progress;
  2081. changeRequest = true;
  2082. }
  2083. }
  2084. } catch (error) {
  2085. console.error(error);
  2086. }
  2087. }
  2088.  
  2089. if (!call.args.result.win) {
  2090. let resultPopup = false;
  2091. if (call.name == 'adventure_endBattle' ||
  2092. //call.name == 'invasion_bossEnd' ||
  2093. call.name == 'bossEndBattle' ||
  2094. call.name == 'adventureSolo_endBattle') {
  2095. resultPopup = await showMsgs(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_CANCEL'), I18N('BTN_AUTO'));
  2096. } else if (call.name == 'clanWarEndBattle' ||
  2097. call.name == 'crossClanWar_endBattle') {
  2098. resultPopup = await showMsg(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_AUTO_F5'));
  2099. } else if (call.name !== 'epicBrawl_endBattle' && call.name !== 'titanArenaEndBattle') {
  2100. resultPopup = await showMsg(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_CANCEL'));
  2101. }
  2102. if (resultPopup) {
  2103. if (call.name == 'invasion_bossEnd') {
  2104. this.errorRequest = true;
  2105. }
  2106. fixBattle(call.args.progress[0].attackers.heroes);
  2107. fixBattle(call.args.progress[0].defenders.heroes);
  2108. changeRequest = true;
  2109. if (resultPopup > 1) {
  2110. this.onReadySuccess = testAutoBattle;
  2111. // setTimeout(bossBattle, 1000);
  2112. }
  2113. }
  2114. } else if (call.args.result.stars < 3 && call.name == 'towerEndBattle') {
  2115. resultPopup = await showMsg(I18N('LOST_HEROES'), I18N('BTN_OK'), I18N('BTN_CANCEL'), I18N('BTN_AUTO'));
  2116. if (resultPopup) {
  2117. fixBattle(call.args.progress[0].attackers.heroes);
  2118. fixBattle(call.args.progress[0].defenders.heroes);
  2119. changeRequest = true;
  2120. if (resultPopup > 1) {
  2121. this.onReadySuccess = testAutoBattle;
  2122. }
  2123. }
  2124. }
  2125. // Потасовки
  2126. if (isChecked('autoBrawls') && !isBrawlsAutoStart && call.name == 'brawl_endBattle') {}
  2127. }
  2128. /**
  2129. * Save pack for Brawls
  2130. *
  2131. * Сохраняем пачку для потасовок
  2132. */
  2133. if (isChecked('autoBrawls') && !isBrawlsAutoStart && call.name == 'brawl_startBattle') {
  2134. console.log(JSON.stringify(call.args));
  2135. brawlsPack = call.args;
  2136. if (
  2137. await popup.confirm(
  2138. I18N('START_AUTO_BRAWLS'),
  2139. [
  2140. { msg: I18N('BTN_NO'), result: false },
  2141. { msg: I18N('BTN_YES'), result: true },
  2142. ],
  2143. [
  2144. {
  2145. name: 'isAuto',
  2146. label: I18N('BRAWL_AUTO_PACK'),
  2147. checked: false,
  2148. },
  2149. ]
  2150. )
  2151. ) {
  2152. isBrawlsAutoStart = true;
  2153. const isAuto = popup.getCheckBoxes().find((e) => e.name === 'isAuto');
  2154. this.errorRequest = true;
  2155. testBrawls(isAuto.checked);
  2156. }
  2157. }
  2158. /**
  2159. * Canceled fight in Asgard
  2160. * Отмена боя в Асгарде
  2161. */
  2162. if (call.name == 'clanRaid_endBossBattle' && isChecked('cancelBattle')) {
  2163. const bossDamage = call.args.progress[0].defenders.heroes[1].extra;
  2164. let maxDamage = bossDamage.damageTaken + bossDamage.damageTakenNextLevel;
  2165. const lastDamage = maxDamage;
  2166.  
  2167. const testFunc = [];
  2168.  
  2169. if (testFuntions.masterFix) {
  2170. testFunc.push({ msg: 'masterFix', isInput: true, default: 100 });
  2171. }
  2172.  
  2173. const resultPopup = await popup.confirm(
  2174. `${I18N('MSG_YOU_APPLIED')} ${lastDamage.toLocaleString()} ${I18N('MSG_DAMAGE')}.`,
  2175. [
  2176. { msg: I18N('BTN_OK'), result: false },
  2177. { msg: I18N('BTN_AUTO_F5'), result: 1 },
  2178. { msg: I18N('BTN_TRY_FIX_IT'), result: 2 },
  2179. ...testFunc,
  2180. ],
  2181. [
  2182. {
  2183. name: 'isStat',
  2184. label: I18N('CALC_STAT'),
  2185. checked: false,
  2186. },
  2187. ]
  2188. );
  2189. if (resultPopup) {
  2190. if (resultPopup == 2) {
  2191. setProgress(I18N('LETS_FIX'), false);
  2192. await new Promise((e) => setTimeout(e, 0));
  2193. const cloneBattle = structuredClone(lastBossBattle);
  2194. const endTime = cloneBattle.endTime - 1e4;
  2195. console.log('fixBossBattleStart');
  2196.  
  2197. const { BossFixBattle } = HWHClasses;
  2198. const bFix = new BossFixBattle(cloneBattle);
  2199. const result = await bFix.start(endTime, 300);
  2200. console.log(result);
  2201.  
  2202. let msgResult = I18N('DAMAGE_NO_FIXED', {
  2203. lastDamage: lastDamage.toLocaleString()
  2204. });
  2205. if (result.value > lastDamage) {
  2206. call.args.result = result.result;
  2207. call.args.progress = result.progress;
  2208. msgResult = I18N('DAMAGE_FIXED', {
  2209. lastDamage: lastDamage.toLocaleString(),
  2210. maxDamage: result.value.toLocaleString(),
  2211. });
  2212. }
  2213. console.log(lastDamage, '>', result.value);
  2214. setProgress(
  2215. msgResult +
  2216. '<br/>' +
  2217. I18N('COUNT_FIXED', {
  2218. count: result.maxCount,
  2219. }),
  2220. false,
  2221. hideProgress
  2222. );
  2223. } else if (resultPopup > 3) {
  2224. const cloneBattle = structuredClone(lastBossBattle);
  2225. const { masterFixBattle } = HWHClasses;
  2226. const mFix = new masterFixBattle(cloneBattle);
  2227. const result = await mFix.start(cloneBattle.endTime, resultPopup);
  2228. console.log(result);
  2229. let msgResult = I18N('DAMAGE_NO_FIXED', {
  2230. lastDamage: lastDamage.toLocaleString(),
  2231. });
  2232. if (result.value > lastDamage) {
  2233. maxDamage = result.value;
  2234. call.args.result = result.result;
  2235. call.args.progress = result.progress;
  2236. msgResult = I18N('DAMAGE_FIXED', {
  2237. lastDamage: lastDamage.toLocaleString(),
  2238. maxDamage: maxDamage.toLocaleString(),
  2239. });
  2240. }
  2241. console.log('Урон:', lastDamage, maxDamage);
  2242. setProgress(msgResult, false, hideProgress);
  2243. } else {
  2244. fixBattle(call.args.progress[0].attackers.heroes);
  2245. fixBattle(call.args.progress[0].defenders.heroes);
  2246. }
  2247. changeRequest = true;
  2248. }
  2249. const isStat = popup.getCheckBoxes().find((e) => e.name === 'isStat');
  2250. if (isStat.checked) {
  2251. this.onReadySuccess = testBossBattle;
  2252. }
  2253. }
  2254. /**
  2255. * Save the Asgard Boss Attack Pack
  2256. * Сохраняем пачку для атаки босса Асгарда
  2257. */
  2258. if (call.name == 'clanRaid_startBossBattle') {
  2259. console.log(JSON.stringify(call.args));
  2260. }
  2261. /**
  2262. * Saving the request to start the last battle
  2263. * Сохранение запроса начала последнего боя
  2264. */
  2265. if (
  2266. call.name == 'clanWarAttack' ||
  2267. call.name == 'crossClanWar_startBattle' ||
  2268. call.name == 'adventure_turnStartBattle' ||
  2269. call.name == 'adventureSolo_turnStartBattle' ||
  2270. call.name == 'bossAttack' ||
  2271. call.name == 'invasion_bossStart' ||
  2272. call.name == 'towerStartBattle'
  2273. ) {
  2274. nameFuncStartBattle = call.name;
  2275. lastBattleArg = call.args;
  2276.  
  2277. if (call.name == 'invasion_bossStart') {
  2278. const timePassed = Date.now() - lastBossBattleStart;
  2279. if (timePassed < invasionTimer) {
  2280. await new Promise((e) => setTimeout(e, invasionTimer - timePassed));
  2281. }
  2282. invasionTimer -= 1;
  2283. }
  2284. lastBossBattleStart = Date.now();
  2285. }
  2286. if (call.name == 'invasion_bossEnd') {
  2287. const lastBattle = lastBattleInfo;
  2288. if (lastBattle && call.args.result.win) {
  2289. lastBattle.progress = call.args.progress;
  2290. const result = await Calc(lastBattle);
  2291. let timer = getTimer(result.battleTime, 1) + addBattleTimer;
  2292. const period = Math.ceil((Date.now() - lastBossBattleStart) / 1000);
  2293. console.log(timer, period);
  2294. if (period < timer) {
  2295. timer = timer - period;
  2296. await countdownTimer(timer);
  2297. }
  2298. }
  2299. }
  2300. /**
  2301. * Disable spending divination cards
  2302. * Отключить трату карт предсказаний
  2303. */
  2304. if (call.name == 'dungeonEndBattle') {
  2305. if (call.args.isRaid) {
  2306. if (countPredictionCard <= 0) {
  2307. delete call.args.isRaid;
  2308. changeRequest = true;
  2309. } else if (countPredictionCard > 0) {
  2310. countPredictionCard--;
  2311. }
  2312. }
  2313. console.log(`Cards: ${countPredictionCard}`);
  2314. /**
  2315. * Fix endless cards
  2316. * Исправление бесконечных карт
  2317. */
  2318. const lastBattle = lastDungeonBattleData;
  2319. if (lastBattle && !call.args.isRaid) {
  2320. if (changeRequest) {
  2321. lastBattle.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  2322. } else {
  2323. lastBattle.progress = call.args.progress;
  2324. }
  2325. const result = await Calc(lastBattle);
  2326.  
  2327. if (changeRequest) {
  2328. call.args.progress = result.progress;
  2329. call.args.result = result.result;
  2330. }
  2331. let timer = result.battleTimer + addBattleTimer;
  2332. const period = Math.ceil((Date.now() - lastDungeonBattleStart) / 1000);
  2333. console.log(timer, period);
  2334. if (period < timer) {
  2335. timer = timer - period;
  2336. await countdownTimer(timer);
  2337. }
  2338. }
  2339. }
  2340. /**
  2341. * Quiz Answer
  2342. * Ответ на викторину
  2343. */
  2344. if (call.name == 'quizAnswer') {
  2345. /**
  2346. * Automatically changes the answer to the correct one if there is one.
  2347. * Автоматически меняет ответ на правильный если он есть
  2348. */
  2349. if (lastAnswer && isChecked('getAnswer')) {
  2350. call.args.answerId = lastAnswer;
  2351. lastAnswer = null;
  2352. changeRequest = true;
  2353. }
  2354. }
  2355. /**
  2356. * Present
  2357. * Подарки
  2358. */
  2359. if (call.name == 'freebieCheck') {
  2360. freebieCheckInfo = call;
  2361. }
  2362. /** missionTimer */
  2363. if (call.name == 'missionEnd' && missionBattle) {
  2364. let startTimer = false;
  2365. if (!call.args.result.win) {
  2366. startTimer = await popup.confirm(I18N('DEFEAT_TURN_TIMER'), [
  2367. { msg: I18N('BTN_NO'), result: false },
  2368. { msg: I18N('BTN_YES'), result: true },
  2369. ]);
  2370. }
  2371.  
  2372. if (call.args.result.win || startTimer) {
  2373. missionBattle.progress = call.args.progress;
  2374. missionBattle.result = call.args.result;
  2375. const result = await Calc(missionBattle);
  2376.  
  2377. let timer = result.battleTimer + addBattleTimer;
  2378. const period = Math.ceil((Date.now() - lastMissionBattleStart) / 1000);
  2379. if (period < timer) {
  2380. timer = timer - period;
  2381. await countdownTimer(timer);
  2382. }
  2383. missionBattle = null;
  2384. } else {
  2385. this.errorRequest = true;
  2386. }
  2387. }
  2388. /**
  2389. * Getting mission data for auto-repeat
  2390. * Получение данных миссии для автоповтора
  2391. */
  2392. if (isChecked('repeatMission') &&
  2393. call.name == 'missionEnd') {
  2394. let missionInfo = {
  2395. id: call.args.id,
  2396. result: call.args.result,
  2397. heroes: call.args.progress[0].attackers.heroes,
  2398. count: 0,
  2399. }
  2400. setTimeout(async () => {
  2401. if (!isSendsMission && await popup.confirm(I18N('MSG_REPEAT_MISSION'), [
  2402. { msg: I18N('BTN_REPEAT'), result: true},
  2403. { msg: I18N('BTN_NO'), result: false},
  2404. ])) {
  2405. isStopSendMission = false;
  2406. isSendsMission = true;
  2407. sendsMission(missionInfo);
  2408. }
  2409. }, 0);
  2410. }
  2411. /**
  2412. * Getting mission data
  2413. * Получение данных миссии
  2414. * missionTimer
  2415. */
  2416. if (call.name == 'missionStart') {
  2417. lastMissionStart = call.args;
  2418. lastMissionBattleStart = Date.now();
  2419. }
  2420. /**
  2421. * Specify the quantity for Titan Orbs and Pet Eggs
  2422. * Указать количество для сфер титанов и яиц петов
  2423. */
  2424. if (isChecked('countControl') &&
  2425. (call.name == 'pet_chestOpen' ||
  2426. call.name == 'titanUseSummonCircle') &&
  2427. call.args.amount > 1) {
  2428. const startAmount = call.args.amount;
  2429. const result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2430. { msg: I18N('BTN_OPEN'), isInput: true, default: 1},
  2431. ]);
  2432. if (result) {
  2433. const item = call.name == 'pet_chestOpen' ? { id: 90, type: 'consumable' } : { id: 13, type: 'coin' };
  2434. cheats.updateInventory({
  2435. [item.type]: {
  2436. [item.id]: -(result - startAmount),
  2437. },
  2438. });
  2439. call.args.amount = result;
  2440. changeRequest = true;
  2441. }
  2442. }
  2443. /**
  2444. * Specify the amount for keys and spheres of titan artifacts
  2445. * Указать колличество для ключей и сфер артефактов титанов
  2446. */
  2447. if (isChecked('countControl') &&
  2448. (call.name == 'artifactChestOpen' ||
  2449. call.name == 'titanArtifactChestOpen') &&
  2450. call.args.amount > 1 &&
  2451. call.args.free &&
  2452. !changeRequest) {
  2453. artifactChestOpenCallName = call.name;
  2454. const startAmount = call.args.amount;
  2455. let result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2456. { msg: I18N('BTN_OPEN'), isInput: true, default: 1 },
  2457. ]);
  2458. if (result) {
  2459. const openChests = result;
  2460. let sphere = result < 10 ? 1 : 10;
  2461. call.args.amount = sphere;
  2462. for (let count = openChests - sphere; count > 0; count -= sphere) {
  2463. if (count < 10) sphere = 1;
  2464. const ident = artifactChestOpenCallName + "_" + count;
  2465. testData.calls.push({
  2466. name: artifactChestOpenCallName,
  2467. args: {
  2468. amount: sphere,
  2469. free: true,
  2470. },
  2471. ident: ident
  2472. });
  2473. if (!Array.isArray(requestHistory[this.uniqid].calls[call.name])) {
  2474. requestHistory[this.uniqid].calls[call.name] = [requestHistory[this.uniqid].calls[call.name]];
  2475. }
  2476. requestHistory[this.uniqid].calls[call.name].push(ident);
  2477. }
  2478.  
  2479. const consumableId = call.name == 'artifactChestOpen' ? 45 : 55;
  2480. cheats.updateInventory({
  2481. consumable: {
  2482. [consumableId]: -(openChests - startAmount),
  2483. },
  2484. });
  2485. artifactChestOpen = true;
  2486. changeRequest = true;
  2487. }
  2488. }
  2489. if (call.name == 'consumableUseLootBox') {
  2490. lastRussianDollId = call.args.libId;
  2491. /**
  2492. * Specify quantity for gold caskets
  2493. * Указать количество для золотых шкатулок
  2494. */
  2495. if (isChecked('countControl') &&
  2496. call.args.libId == 148 &&
  2497. call.args.amount > 1) {
  2498. const result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2499. { msg: I18N('BTN_OPEN'), isInput: true, default: call.args.amount},
  2500. ]);
  2501. call.args.amount = result;
  2502. changeRequest = true;
  2503. }
  2504. if (isChecked('countControl') && call.args.libId >= 362 && call.args.libId <= 389) {
  2505. this.massOpen = call.args.libId;
  2506. }
  2507. }
  2508. if (call.name == 'invasion_bossStart' && isChecked('tryFixIt_v2') && call.args.id == 217) {
  2509. const pack = invasionDataPacks[invasionInfo.bossLvl];
  2510. if (pack.buff != invasionInfo.buff) {
  2511. setProgress(
  2512. I18N('INVASION_BOSS_BUFF', {
  2513. bossLvl: invasionInfo.bossLvl,
  2514. needBuff: pack.buff,
  2515. haveBuff: invasionInfo.buff,
  2516. }),
  2517. false
  2518. );
  2519. } else {
  2520. call.args.pet = pack.pet;
  2521. call.args.heroes = pack.heroes;
  2522. call.args.favor = pack.favor;
  2523. changeRequest = true;
  2524. }
  2525. }
  2526. /**
  2527. * Changing the maximum number of raids in the campaign
  2528. * Изменение максимального количества рейдов в кампании
  2529. */
  2530. // if (call.name == 'missionRaid') {
  2531. // if (isChecked('countControl') && call.args.times > 1) {
  2532. // const result = +(await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2533. // { msg: I18N('BTN_RUN'), isInput: true, default: call.args.times },
  2534. // ]));
  2535. // call.args.times = result > call.args.times ? call.args.times : result;
  2536. // changeRequest = true;
  2537. // }
  2538. // }
  2539. }
  2540.  
  2541. let headers = requestHistory[this.uniqid].headers;
  2542. if (changeRequest) {
  2543. sourceData = JSON.stringify(testData);
  2544. headers['X-Auth-Signature'] = getSignature(headers, sourceData);
  2545. }
  2546.  
  2547. let signature = headers['X-Auth-Signature'];
  2548. if (signature) {
  2549. original.setRequestHeader.call(this, 'X-Auth-Signature', signature);
  2550. }
  2551. } catch (err) {
  2552. console.log("Request(send, " + this.uniqid + "):\n", sourceData, "Error:\n", err);
  2553. }
  2554. return sourceData;
  2555. }
  2556. /**
  2557. * Processing and substitution of incoming data
  2558. *
  2559. * Обработка и подмена входящих данных
  2560. */
  2561. async function checkChangeResponse(response) {
  2562. try {
  2563. isChange = false;
  2564. let nowTime = Math.round(Date.now() / 1000);
  2565. callsIdent = requestHistory[this.uniqid].calls;
  2566. respond = JSON.parse(response);
  2567. /**
  2568. * If the request returned an error removes the error (removes synchronization errors)
  2569. * Если запрос вернул ошибку удаляет ошибку (убирает ошибки синхронизации)
  2570. */
  2571. if (respond.error) {
  2572. isChange = true;
  2573. console.error(respond.error);
  2574. if (isChecked('showErrors')) {
  2575. popup.confirm(I18N('ERROR_MSG', {
  2576. name: respond.error.name,
  2577. description: respond.error.description,
  2578. }));
  2579. }
  2580. if (respond.error.name != 'AccountBan') {
  2581. delete respond.error;
  2582. respond.results = [];
  2583. }
  2584. }
  2585. let mainReward = null;
  2586. const allReward = {};
  2587. let countTypeReward = 0;
  2588. let readQuestInfo = false;
  2589. for (const call of respond.results) {
  2590. /**
  2591. * Obtaining initial data for completing quests
  2592. * Получение исходных данных для выполнения квестов
  2593. */
  2594. if (readQuestInfo) {
  2595. questsInfo[call.ident] = call.result.response;
  2596. }
  2597. /**
  2598. * Getting a user ID
  2599. * Получение идетификатора пользователя
  2600. */
  2601. if (call.ident == callsIdent['registration']) {
  2602. userId = call.result.response.userId;
  2603. if (localStorage['userId'] != userId) {
  2604. localStorage['newGiftSendIds'] = '';
  2605. localStorage['userId'] = userId;
  2606. }
  2607. await openOrMigrateDatabase(userId);
  2608. readQuestInfo = true;
  2609. }
  2610. /**
  2611. * Hiding donation offers 1
  2612. * Скрываем предложения доната 1
  2613. */
  2614. if (call.ident == callsIdent['billingGetAll'] && getSaveVal('noOfferDonat')) {
  2615. const billings = call.result.response?.billings;
  2616. const bundle = call.result.response?.bundle;
  2617. if (billings && bundle) {
  2618. call.result.response.billings = call.result.response.billings.filter((e) => ['repeatableOffer'].includes(e.type));
  2619. call.result.response.bundle = [];
  2620. isChange = true;
  2621. }
  2622. }
  2623. /**
  2624. * Hiding donation offers 2
  2625. * Скрываем предложения доната 2
  2626. */
  2627. if (getSaveVal('noOfferDonat') &&
  2628. (call.ident == callsIdent['offerGetAll'] ||
  2629. call.ident == callsIdent['specialOffer_getAll'])) {
  2630. let offers = call.result.response;
  2631. if (offers) {
  2632. call.result.response = offers.filter(
  2633. (e) => !['addBilling', 'bundleCarousel'].includes(e.type) || ['idleResource', 'stagesOffer'].includes(e.offerType)
  2634. );
  2635. isChange = true;
  2636. }
  2637. }
  2638. /**
  2639. * Hiding donation offers 3
  2640. * Скрываем предложения доната 3
  2641. */
  2642. if (getSaveVal('noOfferDonat') && call.result?.bundleUpdate) {
  2643. delete call.result.bundleUpdate;
  2644. isChange = true;
  2645. }
  2646. /**
  2647. * Hiding donation offers 4
  2648. * Скрываем предложения доната 4
  2649. */
  2650. if (call.result?.specialOffers) {
  2651. const offers = call.result.specialOffers;
  2652. call.result.specialOffers = offers.filter(
  2653. (e) => !['addBilling', 'bundleCarousel'].includes(e.type) || ['idleResource', 'stagesOffer'].includes(e.offerType)
  2654. );
  2655. isChange = true;
  2656. }
  2657. /**
  2658. * Copies a quiz question to the clipboard
  2659. * Копирует вопрос викторины в буфер обмена и получает на него ответ если есть
  2660. */
  2661. if (call.ident == callsIdent['quizGetNewQuestion']) {
  2662. let quest = call.result.response;
  2663. console.log(quest.question);
  2664. copyText(quest.question);
  2665. setProgress(I18N('QUESTION_COPY'), true);
  2666. quest.lang = null;
  2667. if (typeof NXFlashVars !== 'undefined') {
  2668. quest.lang = NXFlashVars.interface_lang;
  2669. }
  2670. lastQuestion = quest;
  2671. if (isChecked('getAnswer')) {
  2672. const answer = await getAnswer(lastQuestion);
  2673. let showText = '';
  2674. if (answer) {
  2675. lastAnswer = answer;
  2676. console.log(answer);
  2677. showText = `${I18N('ANSWER_KNOWN')}: ${answer}`;
  2678. } else {
  2679. showText = I18N('ANSWER_NOT_KNOWN');
  2680. }
  2681.  
  2682. try {
  2683. const hint = hintQuest(quest);
  2684. if (hint) {
  2685. showText += I18N('HINT') + hint;
  2686. }
  2687. } catch(e) {}
  2688.  
  2689. setProgress(showText, true);
  2690. }
  2691. }
  2692. /**
  2693. * Submits a question with an answer to the database
  2694. * Отправляет вопрос с ответом в базу данных
  2695. */
  2696. if (call.ident == callsIdent['quizAnswer']) {
  2697. const answer = call.result.response;
  2698. if (lastQuestion) {
  2699. const answerInfo = {
  2700. answer,
  2701. question: lastQuestion,
  2702. lang: null,
  2703. }
  2704. if (typeof NXFlashVars !== 'undefined') {
  2705. answerInfo.lang = NXFlashVars.interface_lang;
  2706. }
  2707. lastQuestion = null;
  2708. setTimeout(sendAnswerInfo, 0, answerInfo);
  2709. }
  2710. }
  2711. /**
  2712. * Get user data
  2713. * Получить даныне пользователя
  2714. */
  2715. if (call.ident == callsIdent['userGetInfo']) {
  2716. let user = call.result.response;
  2717. document.title = user.name;
  2718. userInfo = Object.assign({}, user);
  2719. delete userInfo.refillable;
  2720. if (!questsInfo['userGetInfo']) {
  2721. questsInfo['userGetInfo'] = user;
  2722. }
  2723. }
  2724. /**
  2725. * Start of the battle for recalculation
  2726. * Начало боя для прерасчета
  2727. */
  2728. if (call.ident == callsIdent['clanWarAttack'] ||
  2729. call.ident == callsIdent['crossClanWar_startBattle'] ||
  2730. call.ident == callsIdent['bossAttack'] ||
  2731. call.ident == callsIdent['battleGetReplay'] ||
  2732. call.ident == callsIdent['brawl_startBattle'] ||
  2733. call.ident == callsIdent['adventureSolo_turnStartBattle'] ||
  2734. call.ident == callsIdent['invasion_bossStart'] ||
  2735. call.ident == callsIdent['titanArenaStartBattle'] ||
  2736. call.ident == callsIdent['towerStartBattle'] ||
  2737. call.ident == callsIdent['epicBrawl_startBattle'] ||
  2738. call.ident == callsIdent['adventure_turnStartBattle']) {
  2739. let battle = call.result.response.battle || call.result.response.replay;
  2740. if (call.ident == callsIdent['brawl_startBattle'] ||
  2741. call.ident == callsIdent['bossAttack'] ||
  2742. call.ident == callsIdent['towerStartBattle'] ||
  2743. call.ident == callsIdent['invasion_bossStart']) {
  2744. battle = call.result.response;
  2745. }
  2746. lastBattleInfo = battle;
  2747. if (call.ident == callsIdent['battleGetReplay'] && call.result.response.replay.type === "clan_raid") {
  2748. if (call?.result?.response?.replay?.result?.damage) {
  2749. const damages = Object.values(call.result.response.replay.result.damage);
  2750. const bossDamage = damages.reduce((a, v) => a + v, 0);
  2751. setProgress(I18N('BOSS_DAMAGE') + bossDamage.toLocaleString(), false, hideProgress);
  2752. continue;
  2753. }
  2754. }
  2755. if (!isChecked('preCalcBattle')) {
  2756. continue;
  2757. }
  2758. const preCalcBattle = structuredClone(battle);
  2759. setProgress(I18N('BEING_RECALC'));
  2760. let battleDuration = 120;
  2761. try {
  2762. const typeBattle = getBattleType(preCalcBattle.type);
  2763. battleDuration = +lib.data.battleConfig[typeBattle.split('_')[1]].config.battleDuration;
  2764. } catch (e) { }
  2765. //console.log(battle.type);
  2766. function getBattleInfo(battle, isRandSeed) {
  2767. return new Promise(function (resolve) {
  2768. if (isRandSeed) {
  2769. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  2770. }
  2771. BattleCalc(battle, getBattleType(battle.type), e => resolve(e));
  2772. });
  2773. }
  2774. let actions = [getBattleInfo(preCalcBattle, false)];
  2775. let countTestBattle = getInput('countTestBattle');
  2776. if (call.ident == callsIdent['invasion_bossStart'] ) {
  2777. countTestBattle = 0;
  2778. }
  2779. if (call.ident == callsIdent['battleGetReplay']) {
  2780. preCalcBattle.progress = [{ attackers: { input: ['auto', 0, 0, 'auto', 0, 0] } }];
  2781. }
  2782. for (let i = 0; i < countTestBattle; i++) {
  2783. actions.push(getBattleInfo(preCalcBattle, true));
  2784. }
  2785. Promise.all(actions)
  2786. .then(e => {
  2787. e = e.map(n => ({win: n.result.win, time: n.battleTime}));
  2788. let firstBattle = e.shift();
  2789. const timer = Math.floor(battleDuration - firstBattle.time);
  2790. const min = ('00' + Math.floor(timer / 60)).slice(-2);
  2791. const sec = ('00' + Math.floor(timer - min * 60)).slice(-2);
  2792. let msg = `${I18N('THIS_TIME')} ${firstBattle.win ? I18N('VICTORY') : I18N('DEFEAT')}`;
  2793. if (e.length) {
  2794. const countWin = e.reduce((w, s) => w + s.win, 0);
  2795. msg += ` ${I18N('CHANCE_TO_WIN')}: ${Math.floor((countWin / e.length) * 100)}% (${e.length})`;
  2796. }
  2797. msg += `, ${min}:${sec}`
  2798. setProgress(msg, false, hideProgress)
  2799. });
  2800. }
  2801. /**
  2802. * Start of the Asgard boss fight
  2803. * Начало боя с боссом Асгарда
  2804. */
  2805. if (call.ident == callsIdent['clanRaid_startBossBattle']) {
  2806. lastBossBattle = call.result.response.battle;
  2807. lastBossBattle.endTime = Date.now() + 160 * 1000;
  2808. if (isChecked('preCalcBattle')) {
  2809. const result = await Calc(lastBossBattle).then(e => e.progress[0].defenders.heroes[1].extra);
  2810. const bossDamage = result.damageTaken + result.damageTakenNextLevel;
  2811. setProgress(I18N('BOSS_DAMAGE') + bossDamage.toLocaleString(), false, hideProgress);
  2812. }
  2813. }
  2814. /**
  2815. * Cancel tutorial
  2816. * Отмена туториала
  2817. */
  2818. if (isCanceledTutorial && call.ident == callsIdent['tutorialGetInfo']) {
  2819. let chains = call.result.response.chains;
  2820. for (let n in chains) {
  2821. chains[n] = 9999;
  2822. }
  2823. isChange = true;
  2824. }
  2825. /**
  2826. * Opening keys and spheres of titan artifacts
  2827. * Открытие ключей и сфер артефактов титанов
  2828. */
  2829. if (artifactChestOpen &&
  2830. (call.ident == callsIdent[artifactChestOpenCallName] ||
  2831. (callsIdent[artifactChestOpenCallName] && callsIdent[artifactChestOpenCallName].includes(call.ident)))) {
  2832. let reward = call.result.response[artifactChestOpenCallName == 'artifactChestOpen' ? 'chestReward' : 'reward'];
  2833.  
  2834. reward.forEach(e => {
  2835. for (let f in e) {
  2836. if (!allReward[f]) {
  2837. allReward[f] = {};
  2838. }
  2839. for (let o in e[f]) {
  2840. if (!allReward[f][o]) {
  2841. allReward[f][o] = e[f][o];
  2842. countTypeReward++;
  2843. } else {
  2844. allReward[f][o] += e[f][o];
  2845. }
  2846. }
  2847. }
  2848. });
  2849.  
  2850. if (!call.ident.includes(artifactChestOpenCallName)) {
  2851. mainReward = call.result.response;
  2852. }
  2853. }
  2854.  
  2855. if (countTypeReward > 20) {
  2856. correctShowOpenArtifact = 3;
  2857. } else {
  2858. correctShowOpenArtifact = 0;
  2859. }
  2860. /**
  2861. * Sum the result of opening Pet Eggs
  2862. * Суммирование результата открытия яиц питомцев
  2863. */
  2864. if (isChecked('countControl') && call.ident == callsIdent['pet_chestOpen']) {
  2865. const rewards = call.result.response.rewards;
  2866. if (rewards.length > 10) {
  2867. /**
  2868. * Removing pet cards
  2869. * Убираем карточки петов
  2870. */
  2871. for (const reward of rewards) {
  2872. if (reward.petCard) {
  2873. delete reward.petCard;
  2874. }
  2875. }
  2876. }
  2877. rewards.forEach(e => {
  2878. for (let f in e) {
  2879. if (!allReward[f]) {
  2880. allReward[f] = {};
  2881. }
  2882. for (let o in e[f]) {
  2883. if (!allReward[f][o]) {
  2884. allReward[f][o] = e[f][o];
  2885. } else {
  2886. allReward[f][o] += e[f][o];
  2887. }
  2888. }
  2889. }
  2890. });
  2891. call.result.response.rewards = [allReward];
  2892. isChange = true;
  2893. }
  2894. /**
  2895. * Removing titan cards
  2896. * Убираем карточки титанов
  2897. */
  2898. if (call.ident == callsIdent['titanUseSummonCircle']) {
  2899. if (call.result.response.rewards.length > 10) {
  2900. for (const reward of call.result.response.rewards) {
  2901. if (reward.titanCard) {
  2902. delete reward.titanCard;
  2903. }
  2904. }
  2905. isChange = true;
  2906. }
  2907. }
  2908. /**
  2909. * Auto-repeat opening matryoshkas
  2910. * АвтоПовтор открытия матрешек
  2911. */
  2912. if (isChecked('countControl') && call.ident == callsIdent['consumableUseLootBox']) {
  2913. let [countLootBox, lootBox] = Object.entries(call.result.response).pop();
  2914. countLootBox = +countLootBox;
  2915. let newCount = 0;
  2916. if (lootBox?.consumable && lootBox.consumable[lastRussianDollId]) {
  2917. newCount += lootBox.consumable[lastRussianDollId];
  2918. delete lootBox.consumable[lastRussianDollId];
  2919. }
  2920. if (
  2921. newCount &&
  2922. (await popup.confirm(`${I18N('BTN_OPEN')} ${newCount} ${I18N('OPEN_DOLLS')}?`, [
  2923. { msg: I18N('BTN_OPEN'), result: true },
  2924. { msg: I18N('BTN_NO'), result: false, isClose: true },
  2925. ]))
  2926. ) {
  2927. const [count, recursionResult] = await openRussianDolls(lastRussianDollId, newCount);
  2928. countLootBox += +count;
  2929. mergeItemsObj(lootBox, recursionResult);
  2930. isChange = true;
  2931. }
  2932.  
  2933. if (this.massOpen) {
  2934. if (
  2935. await popup.confirm(I18N('OPEN_ALL_EQUIP_BOXES'), [
  2936. { msg: I18N('BTN_OPEN'), result: true },
  2937. { msg: I18N('BTN_NO'), result: false, isClose: true },
  2938. ])
  2939. ) {
  2940. const consumable = await Send({ calls: [{ name: 'inventoryGet', args: {}, ident: 'inventoryGet' }] }).then((e) =>
  2941. Object.entries(e.results[0].result.response.consumable)
  2942. );
  2943. const calls = [];
  2944. const deleteItems = {};
  2945. for (const [libId, amount] of consumable) {
  2946. if (libId != this.massOpen && libId >= 362 && libId <= 389) {
  2947. calls.push({
  2948. name: 'consumableUseLootBox',
  2949. args: { libId, amount },
  2950. ident: 'consumableUseLootBox_' + libId,
  2951. });
  2952. deleteItems[libId] = -amount;
  2953. }
  2954. }
  2955. const responses = await Send({ calls }).then((e) => e.results.map((r) => r.result.response).flat());
  2956.  
  2957. for (const loot of responses) {
  2958. const [count, result] = Object.entries(loot).pop();
  2959. countLootBox += +count;
  2960.  
  2961. mergeItemsObj(lootBox, result);
  2962. }
  2963. isChange = true;
  2964.  
  2965. this.onReadySuccess = () => {
  2966. cheats.updateInventory({ consumable: deleteItems });
  2967. cheats.refreshInventory();
  2968. };
  2969. }
  2970. }
  2971.  
  2972. if (isChange) {
  2973. call.result.response = {
  2974. [countLootBox]: lootBox,
  2975. };
  2976. }
  2977. }
  2978. /**
  2979. * Dungeon recalculation (fix endless cards)
  2980. * Прерасчет подземки (исправление бесконечных карт)
  2981. */
  2982. if (call.ident == callsIdent['dungeonStartBattle']) {
  2983. lastDungeonBattleData = call.result.response;
  2984. lastDungeonBattleStart = Date.now();
  2985. }
  2986. /**
  2987. * Getting the number of prediction cards
  2988. * Получение количества карт предсказаний
  2989. */
  2990. if (call.ident == callsIdent['inventoryGet']) {
  2991. countPredictionCard = call.result.response.consumable[81] || 0;
  2992. }
  2993. /**
  2994. * Getting subscription status
  2995. * Получение состояния подписки
  2996. */
  2997. if (call.ident == callsIdent['subscriptionGetInfo']) {
  2998. const subscription = call.result.response.subscription;
  2999. if (subscription) {
  3000. subEndTime = subscription.endTime * 1000;
  3001. }
  3002. }
  3003. /**
  3004. * Getting prediction cards
  3005. * Получение карт предсказаний
  3006. */
  3007. if (call.ident == callsIdent['questFarm']) {
  3008. const consumable = call.result.response?.consumable;
  3009. if (consumable && consumable[81]) {
  3010. countPredictionCard += consumable[81];
  3011. console.log(`Cards: ${countPredictionCard}`);
  3012. }
  3013. }
  3014. /**
  3015. * Hiding extra servers
  3016. * Скрытие лишних серверов
  3017. */
  3018. if (call.ident == callsIdent['serverGetAll'] && isChecked('hideServers')) {
  3019. let servers = call.result.response.users.map(s => s.serverId)
  3020. call.result.response.servers = call.result.response.servers.filter(s => servers.includes(s.id));
  3021. isChange = true;
  3022. }
  3023. /**
  3024. * Displays player positions in the adventure
  3025. * Отображает позиции игроков в приключении
  3026. */
  3027. if (call.ident == callsIdent['adventure_getLobbyInfo']) {
  3028. const users = Object.values(call.result.response.users);
  3029. const mapIdent = call.result.response.mapIdent;
  3030. const adventureId = call.result.response.adventureId;
  3031. const maps = {
  3032. adv_strongford_3pl_hell: 9,
  3033. adv_valley_3pl_hell: 10,
  3034. adv_ghirwil_3pl_hell: 11,
  3035. adv_angels_3pl_hell: 12,
  3036. }
  3037. let msg = I18N('MAP') + (mapIdent in maps ? maps[mapIdent] : adventureId);
  3038. msg += '<br>' + I18N('PLAYER_POS');
  3039. for (const user of users) {
  3040. msg += `<br>${user.user.name} - ${user.currentNode}`;
  3041. }
  3042. setProgress(msg, false, hideProgress);
  3043. }
  3044. /**
  3045. * Automatic launch of a raid at the end of the adventure
  3046. * Автоматический запуск рейда при окончании приключения
  3047. */
  3048. if (call.ident == callsIdent['adventure_end']) {
  3049. autoRaidAdventure()
  3050. }
  3051. /** Удаление лавки редкостей */
  3052. if (call.ident == callsIdent['missionRaid']) {
  3053. if (call.result?.heroesMerchant) {
  3054. delete call.result.heroesMerchant;
  3055. isChange = true;
  3056. }
  3057. }
  3058. /** missionTimer */
  3059. if (call.ident == callsIdent['missionStart']) {
  3060. missionBattle = call.result.response;
  3061. }
  3062. /** Награды турнира стихий */
  3063. if (call.ident == callsIdent['hallOfFameGetTrophies']) {
  3064. const trophys = call.result.response;
  3065. const calls = [];
  3066. for (const week in trophys) {
  3067. const trophy = trophys[week];
  3068. if (!trophy.championRewardFarmed) {
  3069. calls.push({
  3070. name: 'hallOfFameFarmTrophyReward',
  3071. args: { trophyId: week, rewardType: 'champion' },
  3072. ident: 'body_champion_' + week,
  3073. });
  3074. }
  3075. if (Object.keys(trophy.clanReward).length && !trophy.clanRewardFarmed) {
  3076. calls.push({
  3077. name: 'hallOfFameFarmTrophyReward',
  3078. args: { trophyId: week, rewardType: 'clan' },
  3079. ident: 'body_clan_' + week,
  3080. });
  3081. }
  3082. }
  3083. if (calls.length) {
  3084. Send({ calls })
  3085. .then((e) => e.results.map((e) => e.result.response))
  3086. .then(async results => {
  3087. let coin18 = 0,
  3088. coin19 = 0,
  3089. gold = 0,
  3090. starmoney = 0;
  3091. for (const r of results) {
  3092. coin18 += r?.coin ? +r.coin[18] : 0;
  3093. coin19 += r?.coin ? +r.coin[19] : 0;
  3094. gold += r?.gold ? +r.gold : 0;
  3095. starmoney += r?.starmoney ? +r.starmoney : 0;
  3096. }
  3097.  
  3098. let msg = I18N('ELEMENT_TOURNAMENT_REWARD') + '<br>';
  3099. if (coin18) {
  3100. msg += cheats.translate('LIB_COIN_NAME_18') + `: ${coin18}<br>`;
  3101. }
  3102. if (coin19) {
  3103. msg += cheats.translate('LIB_COIN_NAME_19') + `: ${coin19}<br>`;
  3104. }
  3105. if (gold) {
  3106. msg += cheats.translate('LIB_PSEUDO_COIN') + `: ${gold}<br>`;
  3107. }
  3108. if (starmoney) {
  3109. msg += cheats.translate('LIB_PSEUDO_STARMONEY') + `: ${starmoney}<br>`;
  3110. }
  3111.  
  3112. await popup.confirm(msg, [{ msg: I18N('BTN_OK'), result: 0 }]);
  3113. });
  3114. }
  3115. }
  3116. if (call.ident == callsIdent['clanDomination_getInfo']) {
  3117. clanDominationGetInfo = call.result.response;
  3118. }
  3119. if (call.ident == callsIdent['clanRaid_endBossBattle']) {
  3120. console.log(call.result.response);
  3121. const damage = Object.values(call.result.response.damage).reduce((a, e) => a + e);
  3122. if (call.result.response.result.afterInvalid) {
  3123. addProgress('<br>' + I18N('SERVER_NOT_ACCEPT'));
  3124. }
  3125. addProgress('<br>Server > ' + I18N('BOSS_DAMAGE') + damage.toLocaleString());
  3126. }
  3127. if (call.ident == callsIdent['invasion_getInfo']) {
  3128. const r = call.result.response;
  3129. if (r?.actions?.length) {
  3130. const boss = r.actions.find((e) => e.payload.id === 217);
  3131. invasionInfo.buff = r.buffAmount;
  3132. invasionInfo.bossLvl = boss.payload.level;
  3133. if (isChecked('tryFixIt_v2')) {
  3134. const pack = invasionDataPacks[invasionInfo.bossLvl];
  3135. setProgress(
  3136. I18N('INVASION_BOSS_BUFF', {
  3137. bossLvl: invasionInfo.bossLvl,
  3138. needBuff: pack.buff,
  3139. haveBuff: invasionInfo.buff
  3140. }),
  3141. false
  3142. );
  3143. }
  3144. }
  3145. }
  3146. if (call.ident == callsIdent['workshopBuff_create']) {
  3147. const r = call.result.response;
  3148. if (r.id == 1) {
  3149. invasionInfo.buff = r.amount;
  3150. if (isChecked('tryFixIt_v2')) {
  3151. const pack = invasionDataPacks[invasionInfo.bossLvl];
  3152. setProgress(
  3153. I18N('INVASION_BOSS_BUFF', {
  3154. bossLvl: invasionInfo.bossLvl,
  3155. needBuff: pack.buff,
  3156. haveBuff: invasionInfo.buff,
  3157. }),
  3158. false
  3159. );
  3160. }
  3161. }
  3162. }
  3163. /*
  3164. if (call.ident == callsIdent['chatGetAll'] && call.args.chatType == 'clanDomination' && !callsIdent['clanDomination_mapState']) {
  3165. this.onReadySuccess = async function () {
  3166. const result = await Send({
  3167. calls: [
  3168. {
  3169. name: 'clanDomination_mapState',
  3170. args: {},
  3171. ident: 'clanDomination_mapState',
  3172. },
  3173. ],
  3174. }).then((e) => e.results[0].result.response);
  3175. let townPositions = result.townPositions;
  3176. let positions = {};
  3177. for (let pos in townPositions) {
  3178. let townPosition = townPositions[pos];
  3179. positions[townPosition.position] = townPosition;
  3180. }
  3181. Object.assign(clanDominationGetInfo, {
  3182. townPositions: positions,
  3183. });
  3184. let userPositions = result.userPositions;
  3185. for (let pos in clanDominationGetInfo.townPositions) {
  3186. let townPosition = clanDominationGetInfo.townPositions[pos];
  3187. if (townPosition.status) {
  3188. userPositions[townPosition.userId] = +pos;
  3189. }
  3190. }
  3191. cheats.updateMap(result);
  3192. };
  3193. }
  3194. if (call.ident == callsIdent['clanDomination_mapState']) {
  3195. const townPositions = call.result.response.townPositions;
  3196. const userPositions = call.result.response.userPositions;
  3197. for (let pos in townPositions) {
  3198. let townPos = townPositions[pos];
  3199. if (townPos.status) {
  3200. userPositions[townPos.userId] = townPos.position;
  3201. }
  3202. }
  3203. isChange = true;
  3204. }
  3205. */
  3206. }
  3207.  
  3208. if (mainReward && artifactChestOpen) {
  3209. console.log(allReward);
  3210. mainReward[artifactChestOpenCallName == 'artifactChestOpen' ? 'chestReward' : 'reward'] = [allReward];
  3211. artifactChestOpen = false;
  3212. artifactChestOpenCallName = '';
  3213. isChange = true;
  3214. }
  3215. } catch(err) {
  3216. console.log("Request(response, " + this.uniqid + "):\n", "Error:\n", response, err);
  3217. }
  3218.  
  3219. if (isChange) {
  3220. Object.defineProperty(this, 'responseText', {
  3221. writable: true
  3222. });
  3223. this.responseText = JSON.stringify(respond);
  3224. }
  3225. }
  3226.  
  3227. /**
  3228. * Request an answer to a question
  3229. *
  3230. * Запрос ответа на вопрос
  3231. */
  3232. async function getAnswer(question) {
  3233. // c29tZSBzdHJhbmdlIHN5bWJvbHM=
  3234. const quizAPI = new ZingerYWebsiteAPI('getAnswer.php', arguments, { question });
  3235. return new Promise((resolve, reject) => {
  3236. quizAPI.request().then((data) => {
  3237. if (data.result) {
  3238. resolve(data.result);
  3239. } else {
  3240. resolve(false);
  3241. }
  3242. }).catch((error) => {
  3243. console.error(error);
  3244. resolve(false);
  3245. });
  3246. })
  3247. }
  3248.  
  3249. /**
  3250. * Submitting a question and answer to a database
  3251. *
  3252. * Отправка вопроса и ответа в базу данных
  3253. */
  3254. function sendAnswerInfo(answerInfo) {
  3255. // c29tZSBub25zZW5zZQ==
  3256. const quizAPI = new ZingerYWebsiteAPI('setAnswer.php', arguments, { answerInfo });
  3257. quizAPI.request().then((data) => {
  3258. if (data.result) {
  3259. console.log(I18N('SENT_QUESTION'));
  3260. }
  3261. });
  3262. }
  3263.  
  3264. /**
  3265. * Returns the battle type by preset type
  3266. *
  3267. * Возвращает тип боя по типу пресета
  3268. */
  3269. function getBattleType(strBattleType) {
  3270. if (!strBattleType) {
  3271. return null;
  3272. }
  3273. switch (strBattleType) {
  3274. case 'titan_pvp':
  3275. return 'get_titanPvp';
  3276. case 'titan_pvp_manual':
  3277. case 'titan_clan_pvp':
  3278. case 'clan_pvp_titan':
  3279. case 'clan_global_pvp_titan':
  3280. case 'brawl_titan':
  3281. case 'challenge_titan':
  3282. case 'titan_mission':
  3283. return 'get_titanPvpManual';
  3284. case 'clan_raid': // Asgard Boss // Босс асгарда
  3285. case 'adventure': // Adventures // Приключения
  3286. case 'clan_global_pvp':
  3287. case 'epic_brawl':
  3288. case 'clan_pvp':
  3289. return 'get_clanPvp';
  3290. case 'dungeon_titan':
  3291. case 'titan_tower':
  3292. return 'get_titan';
  3293. case 'tower':
  3294. case 'clan_dungeon':
  3295. return 'get_tower';
  3296. case 'pve':
  3297. case 'mission':
  3298. return 'get_pve';
  3299. case 'mission_boss':
  3300. return 'get_missionBoss';
  3301. case 'challenge':
  3302. case 'pvp_manual':
  3303. return 'get_pvpManual';
  3304. case 'grand':
  3305. case 'arena':
  3306. case 'pvp':
  3307. case 'clan_domination':
  3308. return 'get_pvp';
  3309. case 'core':
  3310. return 'get_core';
  3311. default: {
  3312. if (strBattleType.includes('invasion')) {
  3313. return 'get_invasion';
  3314. }
  3315. if (strBattleType.includes('boss')) {
  3316. return 'get_boss';
  3317. }
  3318. if (strBattleType.includes('titan_arena')) {
  3319. return 'get_titanPvpManual';
  3320. }
  3321. return 'get_clanPvp';
  3322. }
  3323. }
  3324. }
  3325. /**
  3326. * Returns the class name of the passed object
  3327. *
  3328. * Возвращает название класса переданного объекта
  3329. */
  3330. function getClass(obj) {
  3331. return {}.toString.call(obj).slice(8, -1);
  3332. }
  3333. /**
  3334. * Calculates the request signature
  3335. *
  3336. * Расчитывает сигнатуру запроса
  3337. */
  3338. this.getSignature = function(headers, data) {
  3339. const sign = {
  3340. signature: '',
  3341. length: 0,
  3342. add: function (text) {
  3343. this.signature += text;
  3344. if (this.length < this.signature.length) {
  3345. this.length = 3 * (this.signature.length + 1) >> 1;
  3346. }
  3347. },
  3348. }
  3349. sign.add(headers["X-Request-Id"]);
  3350. sign.add(':');
  3351. sign.add(headers["X-Auth-Token"]);
  3352. sign.add(':');
  3353. sign.add(headers["X-Auth-Session-Id"]);
  3354. sign.add(':');
  3355. sign.add(data);
  3356. sign.add(':');
  3357. sign.add('LIBRARY-VERSION=1');
  3358. sign.add('UNIQUE-SESSION-ID=' + headers["X-Env-Unique-Session-Id"]);
  3359.  
  3360. return md5(sign.signature);
  3361. }
  3362.  
  3363. class HotkeyManager {
  3364. constructor() {
  3365. if (HotkeyManager.instance) {
  3366. return HotkeyManager.instance;
  3367. }
  3368. this.hotkeys = [];
  3369. document.addEventListener('keydown', this.handleKeyDown.bind(this));
  3370. HotkeyManager.instance = this;
  3371. }
  3372.  
  3373. handleKeyDown(event) {
  3374. const key = event.key.toLowerCase();
  3375. const mods = {
  3376. ctrl: event.ctrlKey,
  3377. alt: event.altKey,
  3378. shift: event.shiftKey,
  3379. };
  3380.  
  3381. this.hotkeys.forEach((hotkey) => {
  3382. if (hotkey.key === key && hotkey.ctrl === mods.ctrl && hotkey.alt === mods.alt && hotkey.shift === mods.shift) {
  3383. hotkey.callback(hotkey);
  3384. }
  3385. });
  3386. }
  3387.  
  3388. add(key, opt = {}, callback) {
  3389. this.hotkeys.push({
  3390. key: key.toLowerCase(),
  3391. callback,
  3392. ctrl: opt.ctrl || false,
  3393. alt: opt.alt || false,
  3394. shift: opt.shift || false,
  3395. });
  3396. }
  3397.  
  3398. remove(key, opt = {}) {
  3399. this.hotkeys = this.hotkeys.filter((hotkey) => {
  3400. return !(
  3401. hotkey.key === key.toLowerCase() &&
  3402. hotkey.ctrl === (opt.ctrl || false) &&
  3403. hotkey.alt === (opt.alt || false) &&
  3404. hotkey.shift === (opt.shift || false)
  3405. );
  3406. });
  3407. }
  3408.  
  3409. static getInst() {
  3410. if (!HotkeyManager.instance) {
  3411. new HotkeyManager();
  3412. }
  3413. return HotkeyManager.instance;
  3414. }
  3415. }
  3416.  
  3417. class MouseClicker {
  3418. constructor(element) {
  3419. if (MouseClicker.instance) {
  3420. return MouseClicker.instance;
  3421. }
  3422. this.element = element;
  3423. this.mouse = {
  3424. bubbles: true,
  3425. cancelable: true,
  3426. clientX: 0,
  3427. clientY: 0,
  3428. };
  3429. this.element.addEventListener('mousemove', this.handleMouseMove.bind(this));
  3430. this.clickInfo = {};
  3431. this.nextTimeoutId = 1;
  3432. MouseClicker.instance = this;
  3433. }
  3434.  
  3435. handleMouseMove(event) {
  3436. this.mouse.clientX = event.clientX;
  3437. this.mouse.clientY = event.clientY;
  3438. }
  3439.  
  3440. click(options) {
  3441. options = options || this.mouse;
  3442. this.element.dispatchEvent(new MouseEvent('mousedown', options));
  3443. this.element.dispatchEvent(new MouseEvent('mouseup', options));
  3444. }
  3445.  
  3446. start(interval = 1000, clickCount = Infinity) {
  3447. const currentMouse = { ...this.mouse };
  3448. const timeoutId = this.nextTimeoutId++;
  3449. let count = 0;
  3450.  
  3451. const clickTimeout = () => {
  3452. this.click(currentMouse);
  3453. count++;
  3454. if (count < clickCount) {
  3455. this.clickInfo[timeoutId].timeout = setTimeout(clickTimeout, interval);
  3456. } else {
  3457. delete this.clickInfo[timeoutId];
  3458. }
  3459. };
  3460.  
  3461. this.clickInfo[timeoutId] = {
  3462. timeout: setTimeout(clickTimeout, interval),
  3463. count: clickCount,
  3464. };
  3465. return timeoutId;
  3466. }
  3467.  
  3468. stop(timeoutId) {
  3469. if (this.clickInfo[timeoutId]) {
  3470. clearTimeout(this.clickInfo[timeoutId].timeout);
  3471. delete this.clickInfo[timeoutId];
  3472. }
  3473. }
  3474.  
  3475. stopAll() {
  3476. for (const timeoutId in this.clickInfo) {
  3477. clearTimeout(this.clickInfo[timeoutId].timeout);
  3478. }
  3479. this.clickInfo = {};
  3480. }
  3481.  
  3482. static getInst(element) {
  3483. if (!MouseClicker.instance) {
  3484. new MouseClicker(element);
  3485. }
  3486. return MouseClicker.instance;
  3487. }
  3488. }
  3489.  
  3490. let extintionsList = [];
  3491. /**
  3492. * Creates an interface
  3493. *
  3494. * Создает интерфейс
  3495. */
  3496. function createInterface() {
  3497. popup.init();
  3498. scriptMenu.init({
  3499. showMenu: true
  3500. });
  3501. scriptMenu.addHeader(GM_info.script.name, justInfo);
  3502. const versionHeader = scriptMenu.addHeader('v' + GM_info.script.version);
  3503. if (extintionsList.length) {
  3504. versionHeader.title = '';
  3505. versionHeader.style.color = 'red';
  3506. for (const extintion of extintionsList) {
  3507. const { name, ver, author } = extintion;
  3508. versionHeader.title += name + ', v' + ver + ' by ' + author + '\n';
  3509. }
  3510. }
  3511. // AutoClicker
  3512. const hkm = new HotkeyManager();
  3513. const fc = document.getElementById('flash-content') || document.getElementById('game');
  3514. const mc = new MouseClicker(fc);
  3515. function toggleClicker(self, timeout) {
  3516. if (self.onClick) {
  3517. console.log('Останавливаем клики');
  3518. mc.stop(self.onClick);
  3519. self.onClick = false;
  3520. } else {
  3521. console.log('Стартуем клики');
  3522. self.onClick = mc.start(timeout);
  3523. }
  3524. }
  3525. hkm.add('C', { shift: true }, (self) => {
  3526. console.log('Нажата комбинация "Shift + C"');
  3527. toggleClicker(self, 20);
  3528. });
  3529. hkm.add('V', { shift: true }, (self) => {
  3530. console.log('Нажата комбинация "Shift + V"');
  3531. toggleClicker(self, 100);
  3532. });
  3533. }
  3534.  
  3535. function addExtentionName(name, ver, author) {
  3536. extintionsList.push({
  3537. name,
  3538. ver,
  3539. author,
  3540. });
  3541. }
  3542.  
  3543. function addControls() {
  3544. createInterface();
  3545. const checkboxDetails = scriptMenu.addDetails(I18N('SETTINGS'));
  3546. for (let name in checkboxes) {
  3547. if (checkboxes[name].hide) {
  3548. continue;
  3549. }
  3550. checkboxes[name].cbox = scriptMenu.addCheckbox(checkboxes[name].label, checkboxes[name].title, checkboxDetails);
  3551. /**
  3552. * Getting the state of checkboxes from storage
  3553. * Получаем состояние чекбоксов из storage
  3554. */
  3555. let val = storage.get(name, null);
  3556. if (val != null) {
  3557. checkboxes[name].cbox.checked = val;
  3558. } else {
  3559. storage.set(name, checkboxes[name].default);
  3560. checkboxes[name].cbox.checked = checkboxes[name].default;
  3561. }
  3562. /**
  3563. * Tracing the change event of the checkbox for writing to storage
  3564. * Отсеживание события изменения чекбокса для записи в storage
  3565. */
  3566. checkboxes[name].cbox.dataset['name'] = name;
  3567. checkboxes[name].cbox.addEventListener('change', async function (event) {
  3568. const nameCheckbox = this.dataset['name'];
  3569. /*
  3570. if (this.checked && nameCheckbox == 'cancelBattle') {
  3571. this.checked = false;
  3572. if (await popup.confirm(I18N('MSG_BAN_ATTENTION'), [
  3573. { msg: I18N('BTN_NO_I_AM_AGAINST'), result: true },
  3574. { msg: I18N('BTN_YES_I_AGREE'), result: false },
  3575. ])) {
  3576. return;
  3577. }
  3578. this.checked = true;
  3579. }
  3580. */
  3581. storage.set(nameCheckbox, this.checked);
  3582. })
  3583. }
  3584.  
  3585. const inputDetails = scriptMenu.addDetails(I18N('VALUES'));
  3586. for (let name in inputs) {
  3587. inputs[name].input = scriptMenu.addInputText(inputs[name].title, false, inputDetails);
  3588. /**
  3589. * Get inputText state from storage
  3590. * Получаем состояние inputText из storage
  3591. */
  3592. let val = storage.get(name, null);
  3593. if (val != null) {
  3594. inputs[name].input.value = val;
  3595. } else {
  3596. storage.set(name, inputs[name].default);
  3597. inputs[name].input.value = inputs[name].default;
  3598. }
  3599. /**
  3600. * Tracing a field change event for a record in storage
  3601. * Отсеживание события изменения поля для записи в storage
  3602. */
  3603. inputs[name].input.dataset['name'] = name;
  3604. inputs[name].input.addEventListener('input', function () {
  3605. const inputName = this.dataset['name'];
  3606. let value = +this.value;
  3607. if (!value || Number.isNaN(value)) {
  3608. value = storage.get(inputName, inputs[inputName].default);
  3609. inputs[name].input.value = value;
  3610. }
  3611. storage.set(inputName, value);
  3612. })
  3613. }
  3614. }
  3615.  
  3616. /**
  3617. * Sending a request
  3618. *
  3619. * Отправка запроса
  3620. */
  3621. function send(json, callback, pr) {
  3622. if (typeof json == 'string') {
  3623. json = JSON.parse(json);
  3624. }
  3625. for (const call of json.calls) {
  3626. if (!call?.context?.actionTs) {
  3627. call.context = {
  3628. actionTs: Math.floor(performance.now())
  3629. }
  3630. }
  3631. }
  3632. json = JSON.stringify(json);
  3633. /**
  3634. * We get the headlines of the previous intercepted request
  3635. * Получаем заголовки предыдущего перехваченого запроса
  3636. */
  3637. let headers = lastHeaders;
  3638. /**
  3639. * We increase the header of the query Certifier by 1
  3640. * Увеличиваем заголовок идетификатора запроса на 1
  3641. */
  3642. headers["X-Request-Id"]++;
  3643. /**
  3644. * We calculate the title with the signature
  3645. * Расчитываем заголовок с сигнатурой
  3646. */
  3647. headers["X-Auth-Signature"] = getSignature(headers, json);
  3648. /**
  3649. * Create a new ajax request
  3650. * Создаем новый AJAX запрос
  3651. */
  3652. let xhr = new XMLHttpRequest;
  3653. /**
  3654. * Indicate the previously saved URL for API queries
  3655. * Указываем ранее сохраненный URL для API запросов
  3656. */
  3657. xhr.open('POST', apiUrl, true);
  3658. /**
  3659. * Add the function to the event change event
  3660. * Добавляем функцию к событию смены статуса запроса
  3661. */
  3662. xhr.onreadystatechange = function() {
  3663. /**
  3664. * If the result of the request is obtained, we call the flask function
  3665. * Если результат запроса получен вызываем колбек функцию
  3666. */
  3667. if(xhr.readyState == 4) {
  3668. callback(xhr.response, pr);
  3669. }
  3670. };
  3671. /**
  3672. * Indicate the type of request
  3673. * Указываем тип запроса
  3674. */
  3675. xhr.responseType = 'json';
  3676. /**
  3677. * We set the request headers
  3678. * Задаем заголовки запроса
  3679. */
  3680. for(let nameHeader in headers) {
  3681. let head = headers[nameHeader];
  3682. xhr.setRequestHeader(nameHeader, head);
  3683. }
  3684. /**
  3685. * Sending a request
  3686. * Отправляем запрос
  3687. */
  3688. xhr.send(json);
  3689. }
  3690.  
  3691. let hideTimeoutProgress = 0;
  3692. /**
  3693. * Hide progress
  3694. *
  3695. * Скрыть прогресс
  3696. */
  3697. function hideProgress(timeout) {
  3698. timeout = timeout || 0;
  3699. clearTimeout(hideTimeoutProgress);
  3700. hideTimeoutProgress = setTimeout(function () {
  3701. scriptMenu.setStatus('');
  3702. }, timeout);
  3703. }
  3704. /**
  3705. * Progress display
  3706. *
  3707. * Отображение прогресса
  3708. */
  3709. function setProgress(text, hide, onclick) {
  3710. scriptMenu.setStatus(text, onclick);
  3711. hide = hide || false;
  3712. if (hide) {
  3713. hideProgress(3000);
  3714. }
  3715. }
  3716.  
  3717. /**
  3718. * Progress added
  3719. *
  3720. * Дополнение прогресса
  3721. */
  3722. function addProgress(text) {
  3723. scriptMenu.addStatus(text);
  3724. }
  3725.  
  3726. /**
  3727. * Returns the timer value depending on the subscription
  3728. *
  3729. * Возвращает значение таймера в зависимости от подписки
  3730. */
  3731. function getTimer(time, div) {
  3732. let speedDiv = 5;
  3733. if (subEndTime < Date.now()) {
  3734. speedDiv = div || 1.5;
  3735. }
  3736. return Math.max(Math.ceil(time / speedDiv + 1.5), 4);
  3737. }
  3738.  
  3739. function startSlave() {
  3740. const { slaveFixBattle } = HWHClasses;
  3741. const sFix = new slaveFixBattle();
  3742. sFix.wsStart();
  3743. }
  3744.  
  3745. this.testFuntions = {
  3746. hideProgress,
  3747. setProgress,
  3748. addProgress,
  3749. masterFix: false,
  3750. startSlave,
  3751. };
  3752.  
  3753. this.HWHFuncs = {
  3754. send,
  3755. I18N,
  3756. isChecked,
  3757. getInput,
  3758. copyText,
  3759. confShow,
  3760. hideProgress,
  3761. setProgress,
  3762. addProgress,
  3763. getTimer,
  3764. addExtentionName,
  3765. getUserInfo,
  3766. setIsCancalBattle,
  3767. random,
  3768. };
  3769.  
  3770. this.HWHClasses = {
  3771. checkChangeSend,
  3772. checkChangeResponse,
  3773. };
  3774. /**
  3775. * Calculates HASH MD5 from string
  3776. *
  3777. * Расчитывает HASH MD5 из строки
  3778. *
  3779. * [js-md5]{@link https://github.com/emn178/js-md5}
  3780. *
  3781. * @namespace md5
  3782. * @version 0.7.3
  3783. * @author Chen, Yi-Cyuan [emn178@gmail.com]
  3784. * @copyright Chen, Yi-Cyuan 2014-2017
  3785. * @license MIT
  3786. */
  3787. !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 _}))}();
  3788.  
  3789. class Caller {
  3790. static globalHooks = {
  3791. onError: null,
  3792. };
  3793.  
  3794. constructor(calls = null) {
  3795. this.calls = [];
  3796. this.results = {};
  3797. if (calls) {
  3798. this.add(calls);
  3799. }
  3800. }
  3801.  
  3802. static setGlobalHook(event, callback) {
  3803. if (this.globalHooks[event] !== undefined) {
  3804. this.globalHooks[event] = callback;
  3805. } else {
  3806. throw new Error(`Unknown event: ${event}`);
  3807. }
  3808. }
  3809.  
  3810. addCall(call) {
  3811. const { name = call, args = {} } = typeof call === 'object' ? call : { name: call };
  3812. this.calls.push({ name, args });
  3813. return this;
  3814. }
  3815.  
  3816. add(name) {
  3817. if (Array.isArray(name)) {
  3818. name.forEach((call) => this.addCall(call));
  3819. } else {
  3820. this.addCall(name);
  3821. }
  3822. return this;
  3823. }
  3824.  
  3825. handleError(error) {
  3826. const errorName = error.name;
  3827. const errorDescription = error.description;
  3828.  
  3829. if (Caller.globalHooks.onError) {
  3830. const shouldThrow = Caller.globalHooks.onError(error);
  3831. if (shouldThrow === false) {
  3832. return;
  3833. }
  3834. }
  3835.  
  3836. if (error.call) {
  3837. const callInfo = error.call;
  3838. throw new Error(`${errorName} in ${callInfo.name}: ${errorDescription}\n` + `Args: ${JSON.stringify(callInfo.args)}\n`);
  3839. } else if (errorName === 'common\\rpc\\exception\\InvalidRequest') {
  3840. throw new Error(`Invalid request: ${errorDescription}`);
  3841. } else {
  3842. throw new Error(`Unknown error: ${errorName} - ${errorDescription}`);
  3843. }
  3844. }
  3845.  
  3846. async send() {
  3847. if (!this.calls.length) {
  3848. throw new Error('No calls to send.');
  3849. }
  3850.  
  3851. const identToNameMap = {};
  3852. const callsWithIdent = this.calls.map((call, index) => {
  3853. const ident = this.calls.length === 1 ? 'body' : `group_${index}_body`;
  3854. identToNameMap[ident] = call.name;
  3855. return { ...call, ident };
  3856. });
  3857.  
  3858. try {
  3859. const response = await Send({ calls: callsWithIdent });
  3860.  
  3861. if (response.error) {
  3862. this.handleError(response.error);
  3863. }
  3864.  
  3865. if (!response.results) {
  3866. throw new Error('Invalid response format: missing "results" field');
  3867. }
  3868.  
  3869. response.results.forEach((result) => {
  3870. const name = identToNameMap[result.ident];
  3871. if (!this.results[name]) {
  3872. this.results[name] = [];
  3873. }
  3874. this.results[name].push(result.result.response);
  3875. });
  3876. } catch (error) {
  3877. throw error;
  3878. }
  3879. return this;
  3880. }
  3881.  
  3882. result(name, forceArray = false) {
  3883. const results = name ? this.results[name] || [] : Object.values(this.results).flat();
  3884. return forceArray || results.length !== 1 ? results : results[0];
  3885. }
  3886.  
  3887. async execute(name) {
  3888. try {
  3889. await this.send();
  3890. return this.result(name);
  3891. } catch (error) {
  3892. throw error;
  3893. }
  3894. }
  3895.  
  3896. clear() {
  3897. this.calls = [];
  3898. this.results = {};
  3899. return this;
  3900. }
  3901.  
  3902. isEmpty() {
  3903. return this.calls.length === 0 && Object.keys(this.results).length === 0;
  3904. }
  3905. }
  3906.  
  3907. this.Caller = Caller;
  3908.  
  3909. /*
  3910. // Примеры использования
  3911. (async () => {
  3912. // Короткий вызов
  3913. await new Caller('inventoryGet').execute();
  3914. // Простой вызов
  3915. let result = await new Caller().add('inventoryGet').execute();
  3916. console.log('Inventory Get Result:', result);
  3917.  
  3918. // Сложный вызов
  3919. let caller = new Caller();
  3920. await caller
  3921. .add([
  3922. {
  3923. name: 'inventoryGet',
  3924. args: {},
  3925. },
  3926. {
  3927. name: 'heroGetAll',
  3928. args: {},
  3929. },
  3930. ])
  3931. .send();
  3932. console.log('Inventory Get Result:', caller.result('inventoryGet'));
  3933. console.log('Hero Get All Result:', caller.result('heroGetAll'));
  3934.  
  3935. // Очистка всех данных
  3936. caller.clear();
  3937. })();
  3938. */
  3939.  
  3940. /**
  3941. * Script for beautiful dialog boxes
  3942. *
  3943. * Скрипт для красивых диалоговых окошек
  3944. */
  3945. const popup = new (function () {
  3946. this.popUp,
  3947. this.downer,
  3948. this.middle,
  3949. this.msgText,
  3950. this.buttons = [];
  3951. this.checkboxes = [];
  3952. this.dialogPromice = null;
  3953. this.isInit = false;
  3954.  
  3955. this.init = function () {
  3956. if (this.isInit) {
  3957. return;
  3958. }
  3959. addStyle();
  3960. addBlocks();
  3961. addEventListeners();
  3962. this.isInit = true;
  3963. }
  3964.  
  3965. const addEventListeners = () => {
  3966. document.addEventListener('keyup', (e) => {
  3967. if (e.key == 'Escape') {
  3968. if (this.dialogPromice) {
  3969. const { func, result } = this.dialogPromice;
  3970. this.dialogPromice = null;
  3971. popup.hide();
  3972. func(result);
  3973. }
  3974. }
  3975. });
  3976. }
  3977.  
  3978. const addStyle = () => {
  3979. let style = document.createElement('style');
  3980. style.innerText = `
  3981. .PopUp_ {
  3982. position: absolute;
  3983. min-width: 300px;
  3984. max-width: 500px;
  3985. max-height: 600px;
  3986. background-color: #190e08e6;
  3987. z-index: 10001;
  3988. top: 169px;
  3989. left: 345px;
  3990. border: 3px #ce9767 solid;
  3991. border-radius: 10px;
  3992. display: flex;
  3993. flex-direction: column;
  3994. justify-content: space-around;
  3995. padding: 15px 9px;
  3996. box-sizing: border-box;
  3997. }
  3998.  
  3999. .PopUp_back {
  4000. position: absolute;
  4001. background-color: #00000066;
  4002. width: 100%;
  4003. height: 100%;
  4004. z-index: 10000;
  4005. top: 0;
  4006. left: 0;
  4007. }
  4008.  
  4009. .PopUp_close {
  4010. width: 40px;
  4011. height: 40px;
  4012. position: absolute;
  4013. right: -18px;
  4014. top: -18px;
  4015. border: 3px solid #c18550;
  4016. border-radius: 20px;
  4017. background: radial-gradient(circle, rgba(190,30,35,1) 0%, rgba(0,0,0,1) 100%);
  4018. background-position-y: 3px;
  4019. box-shadow: -1px 1px 3px black;
  4020. cursor: pointer;
  4021. box-sizing: border-box;
  4022. }
  4023.  
  4024. .PopUp_close:hover {
  4025. filter: brightness(1.2);
  4026. }
  4027.  
  4028. .PopUp_crossClose {
  4029. width: 100%;
  4030. height: 100%;
  4031. background-size: 65%;
  4032. background-position: center;
  4033. background-repeat: no-repeat;
  4034. 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")
  4035. }
  4036.  
  4037. .PopUp_blocks {
  4038. width: 100%;
  4039. height: 50%;
  4040. display: flex;
  4041. justify-content: space-evenly;
  4042. align-items: center;
  4043. flex-wrap: wrap;
  4044. justify-content: center;
  4045. }
  4046.  
  4047. .PopUp_blocks:last-child {
  4048. margin-top: 25px;
  4049. }
  4050.  
  4051. .PopUp_buttons {
  4052. display: flex;
  4053. margin: 7px 10px;
  4054. flex-direction: column;
  4055. }
  4056.  
  4057. .PopUp_button {
  4058. background-color: #52A81C;
  4059. border-radius: 5px;
  4060. box-shadow: inset 0px -4px 10px, inset 0px 3px 2px #99fe20, 0px 0px 4px, 0px -3px 1px #d7b275, 0px 0px 0px 3px #ce9767;
  4061. cursor: pointer;
  4062. padding: 4px 12px 6px;
  4063. }
  4064.  
  4065. .PopUp_input {
  4066. text-align: center;
  4067. font-size: 16px;
  4068. height: 27px;
  4069. border: 1px solid #cf9250;
  4070. border-radius: 9px 9px 0px 0px;
  4071. background: transparent;
  4072. color: #fce1ac;
  4073. padding: 1px 10px;
  4074. box-sizing: border-box;
  4075. box-shadow: 0px 0px 4px, 0px 0px 0px 3px #ce9767;
  4076. }
  4077.  
  4078. .PopUp_checkboxes {
  4079. display: flex;
  4080. flex-direction: column;
  4081. margin: 15px 15px -5px 15px;
  4082. align-items: flex-start;
  4083. }
  4084.  
  4085. .PopUp_ContCheckbox {
  4086. margin: 2px 0px;
  4087. }
  4088.  
  4089. .PopUp_checkbox {
  4090. position: absolute;
  4091. z-index: -1;
  4092. opacity: 0;
  4093. }
  4094. .PopUp_checkbox+label {
  4095. display: inline-flex;
  4096. align-items: center;
  4097. user-select: none;
  4098.  
  4099. font-size: 15px;
  4100. font-family: sans-serif;
  4101. font-weight: 600;
  4102. font-stretch: condensed;
  4103. letter-spacing: 1px;
  4104. color: #fce1ac;
  4105. text-shadow: 0px 0px 1px;
  4106. }
  4107. .PopUp_checkbox+label::before {
  4108. content: '';
  4109. display: inline-block;
  4110. width: 20px;
  4111. height: 20px;
  4112. border: 1px solid #cf9250;
  4113. border-radius: 7px;
  4114. margin-right: 7px;
  4115. }
  4116. .PopUp_checkbox:checked+label::before {
  4117. 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");
  4118. }
  4119.  
  4120. .PopUp_input::placeholder {
  4121. color: #fce1ac75;
  4122. }
  4123.  
  4124. .PopUp_input:focus {
  4125. outline: 0;
  4126. }
  4127.  
  4128. .PopUp_input + .PopUp_button {
  4129. border-radius: 0px 0px 5px 5px;
  4130. padding: 2px 18px 5px;
  4131. }
  4132.  
  4133. .PopUp_button:hover {
  4134. filter: brightness(1.2);
  4135. }
  4136.  
  4137. .PopUp_button:active {
  4138. box-shadow: inset 0px 5px 10px, inset 0px 1px 2px #99fe20, 0px 0px 4px, 0px -3px 1px #d7b275, 0px 0px 0px 3px #ce9767;
  4139. }
  4140.  
  4141. .PopUp_text {
  4142. font-size: 22px;
  4143. font-family: sans-serif;
  4144. font-weight: 600;
  4145. font-stretch: condensed;
  4146. letter-spacing: 1px;
  4147. text-align: center;
  4148. }
  4149.  
  4150. .PopUp_buttonText {
  4151. color: #E4FF4C;
  4152. text-shadow: 0px 1px 2px black;
  4153. }
  4154.  
  4155. .PopUp_msgText {
  4156. color: #FDE5B6;
  4157. text-shadow: 0px 0px 2px;
  4158. }
  4159.  
  4160. .PopUp_hideBlock {
  4161. display: none;
  4162. }
  4163. `;
  4164. document.head.appendChild(style);
  4165. }
  4166.  
  4167. const addBlocks = () => {
  4168. this.back = document.createElement('div');
  4169. this.back.classList.add('PopUp_back');
  4170. this.back.classList.add('PopUp_hideBlock');
  4171. document.body.append(this.back);
  4172.  
  4173. this.popUp = document.createElement('div');
  4174. this.popUp.classList.add('PopUp_');
  4175. this.back.append(this.popUp);
  4176.  
  4177. let upper = document.createElement('div')
  4178. upper.classList.add('PopUp_blocks');
  4179. this.popUp.append(upper);
  4180.  
  4181. this.middle = document.createElement('div')
  4182. this.middle.classList.add('PopUp_blocks');
  4183. this.middle.classList.add('PopUp_checkboxes');
  4184. this.popUp.append(this.middle);
  4185.  
  4186. this.downer = document.createElement('div')
  4187. this.downer.classList.add('PopUp_blocks');
  4188. this.popUp.append(this.downer);
  4189.  
  4190. this.msgText = document.createElement('div');
  4191. this.msgText.classList.add('PopUp_text', 'PopUp_msgText');
  4192. upper.append(this.msgText);
  4193. }
  4194.  
  4195. this.showBack = function () {
  4196. this.back.classList.remove('PopUp_hideBlock');
  4197. }
  4198.  
  4199. this.hideBack = function () {
  4200. this.back.classList.add('PopUp_hideBlock');
  4201. }
  4202.  
  4203. this.show = function () {
  4204. if (this.checkboxes.length) {
  4205. this.middle.classList.remove('PopUp_hideBlock');
  4206. }
  4207. this.showBack();
  4208. this.popUp.classList.remove('PopUp_hideBlock');
  4209. this.popUp.style.left = (window.innerWidth - this.popUp.offsetWidth) / 2 + 'px';
  4210. this.popUp.style.top = (window.innerHeight - this.popUp.offsetHeight) / 3 + 'px';
  4211. }
  4212.  
  4213. this.hide = function () {
  4214. this.hideBack();
  4215. this.popUp.classList.add('PopUp_hideBlock');
  4216. }
  4217.  
  4218. this.addAnyButton = (option) => {
  4219. const contButton = document.createElement('div');
  4220. contButton.classList.add('PopUp_buttons');
  4221. this.downer.append(contButton);
  4222.  
  4223. let inputField = {
  4224. value: option.result || option.default
  4225. }
  4226. if (option.isInput) {
  4227. inputField = document.createElement('input');
  4228. inputField.type = 'text';
  4229. if (option.placeholder) {
  4230. inputField.placeholder = option.placeholder;
  4231. }
  4232. if (option.default) {
  4233. inputField.value = option.default;
  4234. }
  4235. inputField.classList.add('PopUp_input');
  4236. contButton.append(inputField);
  4237. }
  4238.  
  4239. const button = document.createElement('div');
  4240. button.classList.add('PopUp_button');
  4241. button.title = option.title || '';
  4242. contButton.append(button);
  4243.  
  4244. const buttonText = document.createElement('div');
  4245. buttonText.classList.add('PopUp_text', 'PopUp_buttonText');
  4246. buttonText.innerHTML = option.msg;
  4247. button.append(buttonText);
  4248.  
  4249. return { button, contButton, inputField };
  4250. }
  4251.  
  4252. this.addCloseButton = () => {
  4253. let button = document.createElement('div')
  4254. button.classList.add('PopUp_close');
  4255. this.popUp.append(button);
  4256.  
  4257. let crossClose = document.createElement('div')
  4258. crossClose.classList.add('PopUp_crossClose');
  4259. button.append(crossClose);
  4260.  
  4261. return { button, contButton: button };
  4262. }
  4263.  
  4264. this.addButton = (option, buttonClick) => {
  4265.  
  4266. const { button, contButton, inputField } = option.isClose ? this.addCloseButton() : this.addAnyButton(option);
  4267. if (option.isClose) {
  4268. this.dialogPromice = { func: buttonClick, result: option.result };
  4269. }
  4270. button.addEventListener('click', () => {
  4271. let result = '';
  4272. if (option.isInput) {
  4273. result = inputField.value;
  4274. }
  4275. if (option.isClose || option.isCancel) {
  4276. this.dialogPromice = null;
  4277. }
  4278. buttonClick(result);
  4279. });
  4280.  
  4281. this.buttons.push(contButton);
  4282. }
  4283.  
  4284. this.clearButtons = () => {
  4285. while (this.buttons.length) {
  4286. this.buttons.pop().remove();
  4287. }
  4288. }
  4289.  
  4290. this.addCheckBox = (checkBox) => {
  4291. const contCheckbox = document.createElement('div');
  4292. contCheckbox.classList.add('PopUp_ContCheckbox');
  4293. this.middle.append(contCheckbox);
  4294.  
  4295. const checkbox = document.createElement('input');
  4296. checkbox.type = 'checkbox';
  4297. checkbox.id = 'PopUpCheckbox' + this.checkboxes.length;
  4298. checkbox.dataset.name = checkBox.name;
  4299. checkbox.checked = checkBox.checked;
  4300. checkbox.label = checkBox.label;
  4301. checkbox.title = checkBox.title || '';
  4302. checkbox.classList.add('PopUp_checkbox');
  4303. contCheckbox.appendChild(checkbox)
  4304.  
  4305. const checkboxLabel = document.createElement('label');
  4306. checkboxLabel.innerText = checkBox.label;
  4307. checkboxLabel.title = checkBox.title || '';
  4308. checkboxLabel.setAttribute('for', checkbox.id);
  4309. contCheckbox.appendChild(checkboxLabel);
  4310.  
  4311. this.checkboxes.push(checkbox);
  4312. }
  4313.  
  4314. this.clearCheckBox = () => {
  4315. this.middle.classList.add('PopUp_hideBlock');
  4316. while (this.checkboxes.length) {
  4317. this.checkboxes.pop().parentNode.remove();
  4318. }
  4319. }
  4320.  
  4321. this.setMsgText = (text) => {
  4322. this.msgText.innerHTML = text;
  4323. }
  4324.  
  4325. this.getCheckBoxes = () => {
  4326. const checkBoxes = [];
  4327.  
  4328. for (const checkBox of this.checkboxes) {
  4329. checkBoxes.push({
  4330. name: checkBox.dataset.name,
  4331. label: checkBox.label,
  4332. checked: checkBox.checked
  4333. });
  4334. }
  4335.  
  4336. return checkBoxes;
  4337. }
  4338.  
  4339. this.confirm = async (msg, buttOpt, checkBoxes = []) => {
  4340. if (!this.isInit) {
  4341. this.init();
  4342. }
  4343. this.clearButtons();
  4344. this.clearCheckBox();
  4345. return new Promise((complete, failed) => {
  4346. this.setMsgText(msg);
  4347. if (!buttOpt) {
  4348. buttOpt = [{ msg: 'Ok', result: true, isInput: false }];
  4349. }
  4350. for (const checkBox of checkBoxes) {
  4351. this.addCheckBox(checkBox);
  4352. }
  4353. for (let butt of buttOpt) {
  4354. this.addButton(butt, (result) => {
  4355. result = result || butt.result;
  4356. complete(result);
  4357. popup.hide();
  4358. });
  4359. if (butt.isCancel) {
  4360. this.dialogPromice = { func: complete, result: butt.result };
  4361. }
  4362. }
  4363. this.show();
  4364. });
  4365. }
  4366. });
  4367.  
  4368. this.HWHFuncs.popup = popup;
  4369.  
  4370. /**
  4371. * Script control panel
  4372. *
  4373. * Панель управления скриптом
  4374. */
  4375. const scriptMenu = new (function () {
  4376.  
  4377. this.mainMenu,
  4378. this.buttons = [],
  4379. this.checkboxes = [];
  4380. this.option = {
  4381. showMenu: false,
  4382. showDetails: {}
  4383. };
  4384.  
  4385. this.init = function (option = {}) {
  4386. this.option = Object.assign(this.option, option);
  4387. this.option.showDetails = this.loadShowDetails();
  4388. addStyle();
  4389. addBlocks();
  4390. }
  4391.  
  4392. const addStyle = () => {
  4393. style = document.createElement('style');
  4394. style.innerText = `
  4395. .scriptMenu_status {
  4396. position: absolute;
  4397. z-index: 10001;
  4398. /* max-height: 30px; */
  4399. top: -1px;
  4400. left: 30%;
  4401. cursor: pointer;
  4402. border-radius: 0px 0px 10px 10px;
  4403. background: #190e08e6;
  4404. border: 1px #ce9767 solid;
  4405. font-size: 18px;
  4406. font-family: sans-serif;
  4407. font-weight: 600;
  4408. font-stretch: condensed;
  4409. letter-spacing: 1px;
  4410. color: #fce1ac;
  4411. text-shadow: 0px 0px 1px;
  4412. transition: 0.5s;
  4413. padding: 2px 10px 3px;
  4414. }
  4415. .scriptMenu_statusHide {
  4416. top: -35px;
  4417. height: 30px;
  4418. overflow: hidden;
  4419. }
  4420. .scriptMenu_label {
  4421. position: absolute;
  4422. top: 30%;
  4423. left: -4px;
  4424. z-index: 9999;
  4425. cursor: pointer;
  4426. width: 30px;
  4427. height: 30px;
  4428. background: radial-gradient(circle, #47a41b 0%, #1a2f04 100%);
  4429. border: 1px solid #1a2f04;
  4430. border-radius: 5px;
  4431. box-shadow:
  4432. inset 0px 2px 4px #83ce26,
  4433. inset 0px -4px 6px #1a2f04,
  4434. 0px 0px 2px black,
  4435. 0px 0px 0px 2px #ce9767;
  4436. }
  4437. .scriptMenu_label:hover {
  4438. filter: brightness(1.2);
  4439. }
  4440. .scriptMenu_arrowLabel {
  4441. width: 100%;
  4442. height: 100%;
  4443. background-size: 75%;
  4444. background-position: center;
  4445. background-repeat: no-repeat;
  4446. 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");
  4447. box-shadow: 0px 1px 2px #000;
  4448. border-radius: 5px;
  4449. filter: drop-shadow(0px 1px 2px #000D);
  4450. }
  4451. .scriptMenu_main {
  4452. position: absolute;
  4453. max-width: 285px;
  4454. z-index: 9999;
  4455. top: 50%;
  4456. transform: translateY(-40%);
  4457. background: #190e08e6;
  4458. border: 1px #ce9767 solid;
  4459. border-radius: 0px 10px 10px 0px;
  4460. border-left: none;
  4461. padding: 5px 10px 5px 5px;
  4462. box-sizing: border-box;
  4463. font-size: 15px;
  4464. font-family: sans-serif;
  4465. font-weight: 600;
  4466. font-stretch: condensed;
  4467. letter-spacing: 1px;
  4468. color: #fce1ac;
  4469. text-shadow: 0px 0px 1px;
  4470. transition: 1s;
  4471. display: flex;
  4472. flex-direction: column;
  4473. flex-wrap: nowrap;
  4474. }
  4475. .scriptMenu_showMenu {
  4476. display: none;
  4477. }
  4478. .scriptMenu_showMenu:checked~.scriptMenu_main {
  4479. left: 0px;
  4480. }
  4481. .scriptMenu_showMenu:not(:checked)~.scriptMenu_main {
  4482. left: -300px;
  4483. }
  4484. .scriptMenu_divInput {
  4485. margin: 2px;
  4486. }
  4487. .scriptMenu_divInputText {
  4488. margin: 2px;
  4489. align-self: center;
  4490. display: flex;
  4491. }
  4492. .scriptMenu_checkbox {
  4493. position: absolute;
  4494. z-index: -1;
  4495. opacity: 0;
  4496. }
  4497. .scriptMenu_checkbox+label {
  4498. display: inline-flex;
  4499. align-items: center;
  4500. user-select: none;
  4501. }
  4502. .scriptMenu_checkbox+label::before {
  4503. content: '';
  4504. display: inline-block;
  4505. width: 20px;
  4506. height: 20px;
  4507. border: 1px solid #cf9250;
  4508. border-radius: 7px;
  4509. margin-right: 7px;
  4510. }
  4511. .scriptMenu_checkbox:checked+label::before {
  4512. 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");
  4513. }
  4514. .scriptMenu_close {
  4515. width: 40px;
  4516. height: 40px;
  4517. position: absolute;
  4518. right: -18px;
  4519. top: -18px;
  4520. border: 3px solid #c18550;
  4521. border-radius: 20px;
  4522. background: radial-gradient(circle, rgba(190,30,35,1) 0%, rgba(0,0,0,1) 100%);
  4523. background-position-y: 3px;
  4524. box-shadow: -1px 1px 3px black;
  4525. cursor: pointer;
  4526. box-sizing: border-box;
  4527. }
  4528. .scriptMenu_close:hover {
  4529. filter: brightness(1.2);
  4530. }
  4531. .scriptMenu_crossClose {
  4532. width: 100%;
  4533. height: 100%;
  4534. background-size: 65%;
  4535. background-position: center;
  4536. background-repeat: no-repeat;
  4537. 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")
  4538. }
  4539. .scriptMenu_button {
  4540. user-select: none;
  4541. border-radius: 5px;
  4542. cursor: pointer;
  4543. padding: 5px 14px 8px;
  4544. margin: 4px;
  4545. background: radial-gradient(circle, rgba(165,120,56,1) 80%, rgba(0,0,0,1) 110%);
  4546. box-shadow: inset 0px -4px 6px #442901, inset 0px 1px 6px #442901, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 2px #ce9767;
  4547. }
  4548. .scriptMenu_button:hover {
  4549. filter: brightness(1.2);
  4550. }
  4551. .scriptMenu_button:active {
  4552. box-shadow: inset 0px 4px 6px #442901, inset 0px 4px 6px #442901, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 2px #ce9767;
  4553. }
  4554. .scriptMenu_buttonText {
  4555. color: #fce5b7;
  4556. text-shadow: 0px 1px 2px black;
  4557. text-align: center;
  4558. }
  4559. .scriptMenu_header {
  4560. text-align: center;
  4561. align-self: center;
  4562. font-size: 15px;
  4563. margin: 0px 15px;
  4564. }
  4565. .scriptMenu_header a {
  4566. color: #fce5b7;
  4567. text-decoration: none;
  4568. }
  4569. .scriptMenu_InputText {
  4570. text-align: center;
  4571. width: 130px;
  4572. height: 24px;
  4573. border: 1px solid #cf9250;
  4574. border-radius: 9px;
  4575. background: transparent;
  4576. color: #fce1ac;
  4577. padding: 0px 10px;
  4578. box-sizing: border-box;
  4579. }
  4580. .scriptMenu_InputText:focus {
  4581. filter: brightness(1.2);
  4582. outline: 0;
  4583. }
  4584. .scriptMenu_InputText::placeholder {
  4585. color: #fce1ac75;
  4586. }
  4587. .scriptMenu_Summary {
  4588. cursor: pointer;
  4589. margin-left: 7px;
  4590. }
  4591. .scriptMenu_Details {
  4592. align-self: center;
  4593. }
  4594. `;
  4595. document.head.appendChild(style);
  4596. }
  4597.  
  4598. const addBlocks = () => {
  4599. const main = document.createElement('div');
  4600. document.body.appendChild(main);
  4601.  
  4602. this.status = document.createElement('div');
  4603. this.status.classList.add('scriptMenu_status');
  4604. this.setStatus('');
  4605. main.appendChild(this.status);
  4606.  
  4607. const label = document.createElement('label');
  4608. label.classList.add('scriptMenu_label');
  4609. label.setAttribute('for', 'checkbox_showMenu');
  4610. main.appendChild(label);
  4611.  
  4612. const arrowLabel = document.createElement('div');
  4613. arrowLabel.classList.add('scriptMenu_arrowLabel');
  4614. label.appendChild(arrowLabel);
  4615.  
  4616. const checkbox = document.createElement('input');
  4617. checkbox.type = 'checkbox';
  4618. checkbox.id = 'checkbox_showMenu';
  4619. checkbox.checked = this.option.showMenu;
  4620. checkbox.classList.add('scriptMenu_showMenu');
  4621. main.appendChild(checkbox);
  4622.  
  4623. this.mainMenu = document.createElement('div');
  4624. this.mainMenu.classList.add('scriptMenu_main');
  4625. main.appendChild(this.mainMenu);
  4626.  
  4627. const closeButton = document.createElement('label');
  4628. closeButton.classList.add('scriptMenu_close');
  4629. closeButton.setAttribute('for', 'checkbox_showMenu');
  4630. this.mainMenu.appendChild(closeButton);
  4631.  
  4632. const crossClose = document.createElement('div');
  4633. crossClose.classList.add('scriptMenu_crossClose');
  4634. closeButton.appendChild(crossClose);
  4635. }
  4636.  
  4637. this.setStatus = (text, onclick) => {
  4638. if (!text) {
  4639. this.status.classList.add('scriptMenu_statusHide');
  4640. this.status.innerHTML = '';
  4641. } else {
  4642. this.status.classList.remove('scriptMenu_statusHide');
  4643. this.status.innerHTML = text;
  4644. }
  4645.  
  4646. if (typeof onclick == 'function') {
  4647. this.status.addEventListener("click", onclick, {
  4648. once: true
  4649. });
  4650. }
  4651. }
  4652.  
  4653. this.addStatus = (text) => {
  4654. if (!this.status.innerHTML) {
  4655. this.status.classList.remove('scriptMenu_statusHide');
  4656. }
  4657. this.status.innerHTML += text;
  4658. }
  4659.  
  4660. /**
  4661. * Adding a text element
  4662. *
  4663. * Добавление текстового элемента
  4664. * @param {String} text text // текст
  4665. * @param {Function} func Click function // функция по клику
  4666. * @param {HTMLDivElement} main parent // родитель
  4667. */
  4668. this.addHeader = (text, func, main) => {
  4669. main = main || this.mainMenu;
  4670. const header = document.createElement('div');
  4671. header.classList.add('scriptMenu_header');
  4672. header.innerHTML = text;
  4673. if (typeof func == 'function') {
  4674. header.addEventListener('click', func);
  4675. }
  4676. main.appendChild(header);
  4677. return header;
  4678. }
  4679.  
  4680. /**
  4681. * Adding a button
  4682. *
  4683. * Добавление кнопки
  4684. * @param {String} text
  4685. * @param {Function} func
  4686. * @param {String} title
  4687. * @param {HTMLDivElement} main parent // родитель
  4688. */
  4689. this.addButton = (text, func, title, main) => {
  4690. main = main || this.mainMenu;
  4691. const button = document.createElement('div');
  4692. button.classList.add('scriptMenu_button');
  4693. button.title = title;
  4694. button.addEventListener('click', func);
  4695. main.appendChild(button);
  4696.  
  4697. const buttonText = document.createElement('div');
  4698. buttonText.classList.add('scriptMenu_buttonText');
  4699. buttonText.innerText = text;
  4700. button.appendChild(buttonText);
  4701. this.buttons.push(button);
  4702.  
  4703. return button;
  4704. }
  4705.  
  4706. /**
  4707. * Adding checkbox
  4708. *
  4709. * Добавление чекбокса
  4710. * @param {String} label
  4711. * @param {String} title
  4712. * @param {HTMLDivElement} main parent // родитель
  4713. * @returns
  4714. */
  4715. this.addCheckbox = (label, title, main) => {
  4716. main = main || this.mainMenu;
  4717. const divCheckbox = document.createElement('div');
  4718. divCheckbox.classList.add('scriptMenu_divInput');
  4719. divCheckbox.title = title;
  4720. main.appendChild(divCheckbox);
  4721.  
  4722. const checkbox = document.createElement('input');
  4723. checkbox.type = 'checkbox';
  4724. checkbox.id = 'scriptMenuCheckbox' + this.checkboxes.length;
  4725. checkbox.classList.add('scriptMenu_checkbox');
  4726. divCheckbox.appendChild(checkbox)
  4727.  
  4728. const checkboxLabel = document.createElement('label');
  4729. checkboxLabel.innerText = label;
  4730. checkboxLabel.setAttribute('for', checkbox.id);
  4731. divCheckbox.appendChild(checkboxLabel);
  4732.  
  4733. this.checkboxes.push(checkbox);
  4734. return checkbox;
  4735. }
  4736.  
  4737. /**
  4738. * Adding input field
  4739. *
  4740. * Добавление поля ввода
  4741. * @param {String} title
  4742. * @param {String} placeholder
  4743. * @param {HTMLDivElement} main parent // родитель
  4744. * @returns
  4745. */
  4746. this.addInputText = (title, placeholder, main) => {
  4747. main = main || this.mainMenu;
  4748. const divInputText = document.createElement('div');
  4749. divInputText.classList.add('scriptMenu_divInputText');
  4750. divInputText.title = title;
  4751. main.appendChild(divInputText);
  4752.  
  4753. const newInputText = document.createElement('input');
  4754. newInputText.type = 'text';
  4755. if (placeholder) {
  4756. newInputText.placeholder = placeholder;
  4757. }
  4758. newInputText.classList.add('scriptMenu_InputText');
  4759. divInputText.appendChild(newInputText)
  4760. return newInputText;
  4761. }
  4762.  
  4763. /**
  4764. * Adds a dropdown block
  4765. *
  4766. * Добавляет раскрывающийся блок
  4767. * @param {String} summary
  4768. * @param {String} name
  4769. * @returns
  4770. */
  4771. this.addDetails = (summaryText, name = null) => {
  4772. const details = document.createElement('details');
  4773. details.classList.add('scriptMenu_Details');
  4774. this.mainMenu.appendChild(details);
  4775.  
  4776. const summary = document.createElement('summary');
  4777. summary.classList.add('scriptMenu_Summary');
  4778. summary.innerText = summaryText;
  4779. if (name) {
  4780. const self = this;
  4781. details.open = this.option.showDetails[name];
  4782. details.dataset.name = name;
  4783. summary.addEventListener('click', () => {
  4784. self.option.showDetails[details.dataset.name] = !details.open;
  4785. self.saveShowDetails(self.option.showDetails);
  4786. });
  4787. }
  4788. details.appendChild(summary);
  4789.  
  4790. return details;
  4791. }
  4792.  
  4793. /**
  4794. * Saving the expanded state of the details blocks
  4795. *
  4796. * Сохранение состояния развенутости блоков details
  4797. * @param {*} value
  4798. */
  4799. this.saveShowDetails = (value) => {
  4800. localStorage.setItem('scriptMenu_showDetails', JSON.stringify(value));
  4801. }
  4802.  
  4803. /**
  4804. * Loading the state of expanded blocks details
  4805. *
  4806. * Загрузка состояния развенутости блоков details
  4807. * @returns
  4808. */
  4809. this.loadShowDetails = () => {
  4810. let showDetails = localStorage.getItem('scriptMenu_showDetails');
  4811.  
  4812. if (!showDetails) {
  4813. return {};
  4814. }
  4815.  
  4816. try {
  4817. showDetails = JSON.parse(showDetails);
  4818. } catch (e) {
  4819. return {};
  4820. }
  4821.  
  4822. return showDetails;
  4823. }
  4824. });
  4825.  
  4826. /**
  4827. * Пример использования
  4828. scriptMenu.init();
  4829. scriptMenu.addHeader('v1.508');
  4830. scriptMenu.addCheckbox('testHack', 'Тестовый взлом игры!');
  4831. scriptMenu.addButton('Запуск!', () => console.log('click'), 'подсказака');
  4832. scriptMenu.addInputText('input подсказака');
  4833. */
  4834. /**
  4835. * Game Library
  4836. *
  4837. * Игровая библиотека
  4838. */
  4839. class Library {
  4840. defaultLibUrl = 'https://heroesru-a.akamaihd.net/vk/v1101/lib/lib.json';
  4841.  
  4842. constructor() {
  4843. if (!Library.instance) {
  4844. Library.instance = this;
  4845. }
  4846.  
  4847. return Library.instance;
  4848. }
  4849.  
  4850. async load() {
  4851. try {
  4852. await this.getUrlLib();
  4853. console.log(this.defaultLibUrl);
  4854. this.data = await fetch(this.defaultLibUrl).then(e => e.json())
  4855. } catch (error) {
  4856. console.error('Не удалось загрузить библиотеку', error)
  4857. }
  4858. }
  4859.  
  4860. async getUrlLib() {
  4861. try {
  4862. const db = new Database('hw_cache', 'cache');
  4863. await db.open();
  4864. const cacheLibFullUrl = await db.get('lib/lib.json.gz', false);
  4865. this.defaultLibUrl = cacheLibFullUrl.fullUrl.split('.gz').shift();
  4866. } catch(e) {}
  4867. }
  4868.  
  4869. getData(id) {
  4870. return this.data[id];
  4871. }
  4872.  
  4873. setData(data) {
  4874. this.data = data;
  4875. }
  4876. }
  4877.  
  4878. this.lib = new Library();
  4879. /**
  4880. * Database
  4881. *
  4882. * База данных
  4883. */
  4884. class Database {
  4885. constructor(dbName, storeName) {
  4886. this.dbName = dbName;
  4887. this.storeName = storeName;
  4888. this.db = null;
  4889. }
  4890.  
  4891. async open() {
  4892. return new Promise((resolve, reject) => {
  4893. const request = indexedDB.open(this.dbName);
  4894.  
  4895. request.onerror = () => {
  4896. reject(new Error(`Failed to open database ${this.dbName}`));
  4897. };
  4898.  
  4899. request.onsuccess = () => {
  4900. this.db = request.result;
  4901. resolve();
  4902. };
  4903.  
  4904. request.onupgradeneeded = (event) => {
  4905. const db = event.target.result;
  4906. if (!db.objectStoreNames.contains(this.storeName)) {
  4907. db.createObjectStore(this.storeName);
  4908. }
  4909. };
  4910. });
  4911. }
  4912.  
  4913. async set(key, value) {
  4914. return new Promise((resolve, reject) => {
  4915. const transaction = this.db.transaction([this.storeName], 'readwrite');
  4916. const store = transaction.objectStore(this.storeName);
  4917. const request = store.put(value, key);
  4918.  
  4919. request.onerror = () => {
  4920. reject(new Error(`Failed to save value with key ${key}`));
  4921. };
  4922.  
  4923. request.onsuccess = () => {
  4924. resolve();
  4925. };
  4926. });
  4927. }
  4928.  
  4929. async get(key, def) {
  4930. return new Promise((resolve, reject) => {
  4931. const transaction = this.db.transaction([this.storeName], 'readonly');
  4932. const store = transaction.objectStore(this.storeName);
  4933. const request = store.get(key);
  4934.  
  4935. request.onerror = () => {
  4936. resolve(def);
  4937. };
  4938.  
  4939. request.onsuccess = () => {
  4940. resolve(request.result);
  4941. };
  4942. });
  4943. }
  4944.  
  4945. async delete(key) {
  4946. return new Promise((resolve, reject) => {
  4947. const transaction = this.db.transaction([this.storeName], 'readwrite');
  4948. const store = transaction.objectStore(this.storeName);
  4949. const request = store.delete(key);
  4950.  
  4951. request.onerror = () => {
  4952. reject(new Error(`Failed to delete value with key ${key}`));
  4953. };
  4954.  
  4955. request.onsuccess = () => {
  4956. resolve();
  4957. };
  4958. });
  4959. }
  4960. }
  4961.  
  4962. /**
  4963. * Returns the stored value
  4964. *
  4965. * Возвращает сохраненное значение
  4966. */
  4967. function getSaveVal(saveName, def) {
  4968. const result = storage.get(saveName, def);
  4969. return result;
  4970. }
  4971. this.HWHFuncs.getSaveVal = getSaveVal;
  4972.  
  4973. /**
  4974. * Stores value
  4975. *
  4976. * Сохраняет значение
  4977. */
  4978. function setSaveVal(saveName, value) {
  4979. storage.set(saveName, value);
  4980. }
  4981. this.HWHFuncs.setSaveVal = setSaveVal;
  4982.  
  4983. /**
  4984. * Database initialization
  4985. *
  4986. * Инициализация базы данных
  4987. */
  4988. const db = new Database(GM_info.script.name, 'settings');
  4989.  
  4990. /**
  4991. * Data store
  4992. *
  4993. * Хранилище данных
  4994. */
  4995. const storage = {
  4996. userId: 0,
  4997. /**
  4998. * Default values
  4999. *
  5000. * Значения по умолчанию
  5001. */
  5002. values: [
  5003. ...Object.entries(checkboxes).map(e => ({ [e[0]]: e[1].default })),
  5004. ...Object.entries(inputs).map(e => ({ [e[0]]: e[1].default })),
  5005. ].reduce((acc, obj) => ({ ...acc, ...obj }), {}),
  5006. name: GM_info.script.name,
  5007. get: function (key, def) {
  5008. if (key in this.values) {
  5009. return this.values[key];
  5010. }
  5011. return def;
  5012. },
  5013. set: function (key, value) {
  5014. this.values[key] = value;
  5015. db.set(this.userId, this.values).catch(
  5016. e => null
  5017. );
  5018. localStorage[this.name + ':' + key] = value;
  5019. },
  5020. delete: function (key) {
  5021. delete this.values[key];
  5022. db.set(this.userId, this.values);
  5023. delete localStorage[this.name + ':' + key];
  5024. }
  5025. }
  5026.  
  5027. /**
  5028. * Returns all keys from localStorage that start with prefix (for migration)
  5029. *
  5030. * Возвращает все ключи из localStorage которые начинаются с prefix (для миграции)
  5031. */
  5032. function getAllValuesStartingWith(prefix) {
  5033. const values = [];
  5034. for (let i = 0; i < localStorage.length; i++) {
  5035. const key = localStorage.key(i);
  5036. if (key.startsWith(prefix)) {
  5037. const val = localStorage.getItem(key);
  5038. const keyValue = key.split(':')[1];
  5039. values.push({ key: keyValue, val });
  5040. }
  5041. }
  5042. return values;
  5043. }
  5044.  
  5045. /**
  5046. * Opens or migrates to a database
  5047. *
  5048. * Открывает или мигрирует в базу данных
  5049. */
  5050. async function openOrMigrateDatabase(userId) {
  5051. storage.userId = userId;
  5052. try {
  5053. await db.open();
  5054. } catch(e) {
  5055. return;
  5056. }
  5057. let settings = await db.get(userId, false);
  5058.  
  5059. if (settings) {
  5060. storage.values = settings;
  5061. return;
  5062. }
  5063.  
  5064. const values = getAllValuesStartingWith(GM_info.script.name);
  5065. for (const value of values) {
  5066. let val = null;
  5067. try {
  5068. val = JSON.parse(value.val);
  5069. } catch {
  5070. break;
  5071. }
  5072. storage.values[value.key] = val;
  5073. }
  5074. await db.set(userId, storage.values);
  5075. }
  5076.  
  5077. class ZingerYWebsiteAPI {
  5078. /**
  5079. * Class for interaction with the API of the zingery.ru website
  5080. * Intended only for use with the HeroWarsHelper script:
  5081. * https://greasyfork.org/ru/scripts/450693-herowarshelper
  5082. * Copyright ZingerY
  5083. */
  5084. url = 'https://zingery.ru/heroes/';
  5085. // YWJzb2x1dGVseSB1c2VsZXNzIGxpbmU=
  5086. constructor(urn, env, data = {}) {
  5087. this.urn = urn;
  5088. this.fd = {
  5089. now: Date.now(),
  5090. fp: this.constructor.toString().replaceAll(/\s/g, ''),
  5091. env: env.callee.toString().replaceAll(/\s/g, ''),
  5092. info: (({ name, version, author }) => [name, version, author])(GM_info.script),
  5093. ...data,
  5094. };
  5095. }
  5096.  
  5097. sign() {
  5098. return md5([...this.fd.info, ~(this.fd.now % 1e3), this.fd.fp].join('_'));
  5099. }
  5100.  
  5101. encode(data) {
  5102. return btoa(encodeURIComponent(JSON.stringify(data)));
  5103. }
  5104.  
  5105. decode(data) {
  5106. return JSON.parse(decodeURIComponent(atob(data)));
  5107. }
  5108.  
  5109. headers() {
  5110. return {
  5111. 'X-Request-Signature': this.sign(),
  5112. 'X-Script-Name': GM_info.script.name,
  5113. 'X-Script-Version': GM_info.script.version,
  5114. 'X-Script-Author': GM_info.script.author,
  5115. 'X-Script-ZingerY': 42,
  5116. };
  5117. }
  5118.  
  5119. async request() {
  5120. try {
  5121. const response = await fetch(this.url + this.urn, {
  5122. method: 'POST',
  5123. headers: this.headers(),
  5124. body: this.encode(this.fd),
  5125. });
  5126. const text = await response.text();
  5127. return this.decode(text);
  5128. } catch (e) {
  5129. console.error(e);
  5130. return [];
  5131. }
  5132. }
  5133. /**
  5134. * Класс для взаимодействия с API сайта zingery.ru
  5135. * Предназначен только для использования со скриптом HeroWarsHelper:
  5136. * https://greasyfork.org/ru/scripts/450693-herowarshelper
  5137. * Copyright ZingerY
  5138. */
  5139. }
  5140.  
  5141. /**
  5142. * Sending expeditions
  5143. *
  5144. * Отправка экспедиций
  5145. */
  5146. function checkExpedition() {
  5147. const { Expedition } = HWHClasses;
  5148. return new Promise((resolve, reject) => {
  5149. const expedition = new Expedition(resolve, reject);
  5150. expedition.start();
  5151. });
  5152. }
  5153.  
  5154. class Expedition {
  5155. checkExpedInfo = {
  5156. calls: [
  5157. {
  5158. name: 'expeditionGet',
  5159. args: {},
  5160. ident: 'expeditionGet',
  5161. },
  5162. {
  5163. name: 'heroGetAll',
  5164. args: {},
  5165. ident: 'heroGetAll',
  5166. },
  5167. ],
  5168. };
  5169.  
  5170. constructor(resolve, reject) {
  5171. this.resolve = resolve;
  5172. this.reject = reject;
  5173. }
  5174.  
  5175. async start() {
  5176. const data = await Send(JSON.stringify(this.checkExpedInfo));
  5177.  
  5178. const expedInfo = data.results[0].result.response;
  5179. const dataHeroes = data.results[1].result.response;
  5180. const dataExped = { useHeroes: [], exped: [] };
  5181. const calls = [];
  5182.  
  5183. /**
  5184. * Adding expeditions to collect
  5185. * Добавляем экспедиции для сбора
  5186. */
  5187. let countGet = 0;
  5188. for (var n in expedInfo) {
  5189. const exped = expedInfo[n];
  5190. const dateNow = Date.now() / 1000;
  5191. if (exped.status == 2 && exped.endTime != 0 && dateNow > exped.endTime) {
  5192. countGet++;
  5193. calls.push({
  5194. name: 'expeditionFarm',
  5195. args: { expeditionId: exped.id },
  5196. ident: 'expeditionFarm_' + exped.id,
  5197. });
  5198. } else {
  5199. dataExped.useHeroes = dataExped.useHeroes.concat(exped.heroes);
  5200. }
  5201. if (exped.status == 1) {
  5202. dataExped.exped.push({ id: exped.id, power: exped.power });
  5203. }
  5204. }
  5205. dataExped.exped = dataExped.exped.sort((a, b) => b.power - a.power);
  5206.  
  5207. /**
  5208. * Putting together a list of heroes
  5209. * Собираем список героев
  5210. */
  5211. const heroesArr = [];
  5212. for (let n in dataHeroes) {
  5213. const hero = dataHeroes[n];
  5214. if (hero.xp > 0 && !dataExped.useHeroes.includes(hero.id)) {
  5215. let heroPower = hero.power;
  5216. // Лара Крофт * 3
  5217. if (hero.id == 63 && hero.color >= 16) {
  5218. heroPower *= 3;
  5219. }
  5220. heroesArr.push({ id: hero.id, power: heroPower });
  5221. }
  5222. }
  5223.  
  5224. /**
  5225. * Adding expeditions to send
  5226. * Добавляем экспедиции для отправки
  5227. */
  5228. let countSend = 0;
  5229. heroesArr.sort((a, b) => a.power - b.power);
  5230. for (const exped of dataExped.exped) {
  5231. let heroesIds = this.selectionHeroes(heroesArr, exped.power);
  5232. if (heroesIds && heroesIds.length > 4) {
  5233. for (let q in heroesArr) {
  5234. if (heroesIds.includes(heroesArr[q].id)) {
  5235. delete heroesArr[q];
  5236. }
  5237. }
  5238. countSend++;
  5239. calls.push({
  5240. name: 'expeditionSendHeroes',
  5241. args: {
  5242. expeditionId: exped.id,
  5243. heroes: heroesIds,
  5244. },
  5245. ident: 'expeditionSendHeroes_' + exped.id,
  5246. });
  5247. }
  5248. }
  5249.  
  5250. if (calls.length) {
  5251. await Send({ calls });
  5252. this.end(I18N('EXPEDITIONS_SENT', {countGet, countSend}));
  5253. return;
  5254. }
  5255.  
  5256. this.end(I18N('EXPEDITIONS_NOTHING'));
  5257. }
  5258.  
  5259. /**
  5260. * Selection of heroes for expeditions
  5261. *
  5262. * Подбор героев для экспедиций
  5263. */
  5264. selectionHeroes(heroes, power) {
  5265. const resultHeroers = [];
  5266. const heroesIds = [];
  5267. for (let q = 0; q < 5; q++) {
  5268. for (let i in heroes) {
  5269. let hero = heroes[i];
  5270. if (heroesIds.includes(hero.id)) {
  5271. continue;
  5272. }
  5273.  
  5274. const summ = resultHeroers.reduce((acc, hero) => acc + hero.power, 0);
  5275. const need = Math.round((power - summ) / (5 - resultHeroers.length));
  5276. if (hero.power > need) {
  5277. resultHeroers.push(hero);
  5278. heroesIds.push(hero.id);
  5279. break;
  5280. }
  5281. }
  5282. }
  5283.  
  5284. const summ = resultHeroers.reduce((acc, hero) => acc + hero.power, 0);
  5285. if (summ < power) {
  5286. return false;
  5287. }
  5288. return heroesIds;
  5289. }
  5290.  
  5291. /**
  5292. * Ends expedition script
  5293. *
  5294. * Завершает скрипт экспедиции
  5295. */
  5296. end(msg) {
  5297. setProgress(msg, true);
  5298. this.resolve();
  5299. }
  5300. }
  5301.  
  5302. this.HWHClasses.Expedition = Expedition;
  5303.  
  5304. /**
  5305. * Walkthrough of the dungeon
  5306. *
  5307. * Прохождение подземелья
  5308. */
  5309. function testDungeon() {
  5310. const { executeDungeon } = HWHClasses;
  5311. return new Promise((resolve, reject) => {
  5312. const dung = new executeDungeon(resolve, reject);
  5313. const titanit = getInput('countTitanit');
  5314. dung.start(titanit);
  5315. });
  5316. }
  5317.  
  5318. /**
  5319. * Walkthrough of the dungeon
  5320. *
  5321. * Прохождение подземелья
  5322. */
  5323. function executeDungeon(resolve, reject) {
  5324. dungeonActivity = 0;
  5325. maxDungeonActivity = 150;
  5326.  
  5327. titanGetAll = [];
  5328.  
  5329. teams = {
  5330. heroes: [],
  5331. earth: [],
  5332. fire: [],
  5333. neutral: [],
  5334. water: [],
  5335. }
  5336.  
  5337. titanStats = [];
  5338.  
  5339. titansStates = {};
  5340.  
  5341. let talentMsg = '';
  5342. let talentMsgReward = '';
  5343.  
  5344. callsExecuteDungeon = {
  5345. calls: [{
  5346. name: "dungeonGetInfo",
  5347. args: {},
  5348. ident: "dungeonGetInfo"
  5349. }, {
  5350. name: "teamGetAll",
  5351. args: {},
  5352. ident: "teamGetAll"
  5353. }, {
  5354. name: "teamGetFavor",
  5355. args: {},
  5356. ident: "teamGetFavor"
  5357. }, {
  5358. name: "clanGetInfo",
  5359. args: {},
  5360. ident: "clanGetInfo"
  5361. }, {
  5362. name: "titanGetAll",
  5363. args: {},
  5364. ident: "titanGetAll"
  5365. }, {
  5366. name: "inventoryGet",
  5367. args: {},
  5368. ident: "inventoryGet"
  5369. }]
  5370. }
  5371.  
  5372. this.start = function(titanit) {
  5373. maxDungeonActivity = titanit || getInput('countTitanit');
  5374. send(JSON.stringify(callsExecuteDungeon), startDungeon);
  5375. }
  5376.  
  5377. /**
  5378. * Getting data on the dungeon
  5379. *
  5380. * Получаем данные по подземелью
  5381. */
  5382. function startDungeon(e) {
  5383. res = e.results;
  5384. dungeonGetInfo = res[0].result.response;
  5385. if (!dungeonGetInfo) {
  5386. endDungeon('noDungeon', res);
  5387. return;
  5388. }
  5389. teamGetAll = res[1].result.response;
  5390. teamGetFavor = res[2].result.response;
  5391. dungeonActivity = res[3].result.response.stat.todayDungeonActivity;
  5392. titanGetAll = Object.values(res[4].result.response);
  5393. countPredictionCard = res[5].result.response.consumable[81];
  5394.  
  5395. teams.hero = {
  5396. favor: teamGetFavor.dungeon_hero,
  5397. heroes: teamGetAll.dungeon_hero.filter(id => id < 6000),
  5398. teamNum: 0,
  5399. }
  5400. heroPet = teamGetAll.dungeon_hero.filter(id => id >= 6000).pop();
  5401. if (heroPet) {
  5402. teams.hero.pet = heroPet;
  5403. }
  5404.  
  5405. teams.neutral = {
  5406. favor: {},
  5407. heroes: getTitanTeam(titanGetAll, 'neutral'),
  5408. teamNum: 0,
  5409. };
  5410. teams.water = {
  5411. favor: {},
  5412. heroes: getTitanTeam(titanGetAll, 'water'),
  5413. teamNum: 0,
  5414. };
  5415. teams.fire = {
  5416. favor: {},
  5417. heroes: getTitanTeam(titanGetAll, 'fire'),
  5418. teamNum: 0,
  5419. };
  5420. teams.earth = {
  5421. favor: {},
  5422. heroes: getTitanTeam(titanGetAll, 'earth'),
  5423. teamNum: 0,
  5424. };
  5425.  
  5426.  
  5427. checkFloor(dungeonGetInfo);
  5428. }
  5429.  
  5430. function getTitanTeam(titans, type) {
  5431. switch (type) {
  5432. case 'neutral':
  5433. return titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5434. case 'water':
  5435. return titans.filter(e => e.id.toString().slice(2, 3) == '0').map(e => e.id);
  5436. case 'fire':
  5437. return titans.filter(e => e.id.toString().slice(2, 3) == '1').map(e => e.id);
  5438. case 'earth':
  5439. return titans.filter(e => e.id.toString().slice(2, 3) == '2').map(e => e.id);
  5440. }
  5441. }
  5442.  
  5443. function getNeutralTeam() {
  5444. const titans = titanGetAll.filter(e => !titansStates[e.id]?.isDead)
  5445. return titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5446. }
  5447.  
  5448. function fixTitanTeam(titans) {
  5449. titans.heroes = titans.heroes.filter(e => !titansStates[e]?.isDead);
  5450. return titans;
  5451. }
  5452.  
  5453. /**
  5454. * Checking the floor
  5455. *
  5456. * Проверяем этаж
  5457. */
  5458. async function checkFloor(dungeonInfo) {
  5459. if (!('floor' in dungeonInfo) || dungeonInfo.floor?.state == 2) {
  5460. saveProgress();
  5461. return;
  5462. }
  5463. checkTalent(dungeonInfo);
  5464. // console.log(dungeonInfo, dungeonActivity);
  5465. setProgress(`${I18N('DUNGEON')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity} ${talentMsg}`);
  5466. if (dungeonActivity >= maxDungeonActivity) {
  5467. endDungeon('endDungeon', 'maxActive ' + dungeonActivity + '/' + maxDungeonActivity);
  5468. return;
  5469. }
  5470. titansStates = dungeonInfo.states.titans;
  5471. titanStats = titanObjToArray(titansStates);
  5472. const floorChoices = dungeonInfo.floor.userData;
  5473. const floorType = dungeonInfo.floorType;
  5474. //const primeElement = dungeonInfo.elements.prime;
  5475. if (floorType == "battle") {
  5476. const calls = [];
  5477. for (let teamNum in floorChoices) {
  5478. attackerType = floorChoices[teamNum].attackerType;
  5479. const args = fixTitanTeam(teams[attackerType]);
  5480. if (attackerType == 'neutral') {
  5481. args.heroes = getNeutralTeam();
  5482. }
  5483. if (!args.heroes.length) {
  5484. continue;
  5485. }
  5486. args.teamNum = teamNum;
  5487. calls.push({
  5488. name: "dungeonStartBattle",
  5489. args,
  5490. ident: "body_" + teamNum
  5491. })
  5492. }
  5493. if (!calls.length) {
  5494. endDungeon('endDungeon', 'All Dead');
  5495. return;
  5496. }
  5497. const battleDatas = await Send(JSON.stringify({ calls }))
  5498. .then(e => e.results.map(n => n.result.response))
  5499. const battleResults = [];
  5500. for (n in battleDatas) {
  5501. battleData = battleDatas[n]
  5502. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  5503. battleResults.push(await Calc(battleData).then(result => {
  5504. result.teamNum = n;
  5505. result.attackerType = floorChoices[n].attackerType;
  5506. return result;
  5507. }));
  5508. }
  5509. processingPromises(battleResults)
  5510. }
  5511. }
  5512.  
  5513. async function checkTalent(dungeonInfo) {
  5514. const talent = dungeonInfo.talent;
  5515. if (!talent) {
  5516. return;
  5517. }
  5518. const dungeonFloor = +dungeonInfo.floorNumber;
  5519. const talentFloor = +talent.floorRandValue;
  5520. let doorsAmount = 3 - talent.conditions.doorsAmount;
  5521.  
  5522. if (dungeonFloor === talentFloor && (!doorsAmount || !talent.conditions?.farmedDoors[dungeonFloor])) {
  5523. const reward = await Send({
  5524. calls: [
  5525. { name: 'heroTalent_getReward', args: { talentType: 'tmntDungeonTalent', reroll: false }, ident: 'group_0_body' },
  5526. { name: 'heroTalent_farmReward', args: { talentType: 'tmntDungeonTalent' }, ident: 'group_1_body' },
  5527. ],
  5528. }).then((e) => e.results[0].result.response);
  5529. const type = Object.keys(reward).pop();
  5530. const itemId = Object.keys(reward[type]).pop();
  5531. const count = reward[type][itemId];
  5532. const itemName = cheats.translate(`LIB_${type.toUpperCase()}_NAME_${itemId}`);
  5533. talentMsgReward += `<br> ${count} ${itemName}`;
  5534. doorsAmount++;
  5535. }
  5536. talentMsg = `<br>TMNT Talent: ${doorsAmount}/3 ${talentMsgReward}<br>`;
  5537. }
  5538.  
  5539. function processingPromises(results) {
  5540. let selectBattle = results[0];
  5541. if (results.length < 2) {
  5542. // console.log(selectBattle);
  5543. if (!selectBattle.result.win) {
  5544. endDungeon('dungeonEndBattle\n', selectBattle);
  5545. return;
  5546. }
  5547. endBattle(selectBattle);
  5548. return;
  5549. }
  5550.  
  5551. selectBattle = false;
  5552. let bestState = -1000;
  5553. for (const result of results) {
  5554. const recovery = getState(result);
  5555. if (recovery > bestState) {
  5556. bestState = recovery;
  5557. selectBattle = result
  5558. }
  5559. }
  5560. // console.log(selectBattle.teamNum, results);
  5561. if (!selectBattle || bestState <= -1000) {
  5562. endDungeon('dungeonEndBattle\n', results);
  5563. return;
  5564. }
  5565.  
  5566. startBattle(selectBattle.teamNum, selectBattle.attackerType)
  5567. .then(endBattle);
  5568. }
  5569.  
  5570. /**
  5571. * Let's start the fight
  5572. *
  5573. * Начинаем бой
  5574. */
  5575. function startBattle(teamNum, attackerType) {
  5576. return new Promise(function (resolve, reject) {
  5577. args = fixTitanTeam(teams[attackerType]);
  5578. args.teamNum = teamNum;
  5579. if (attackerType == 'neutral') {
  5580. const titans = titanGetAll.filter(e => !titansStates[e.id]?.isDead)
  5581. args.heroes = titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5582. }
  5583. startBattleCall = {
  5584. calls: [{
  5585. name: "dungeonStartBattle",
  5586. args,
  5587. ident: "body"
  5588. }]
  5589. }
  5590. send(JSON.stringify(startBattleCall), resultBattle, {
  5591. resolve,
  5592. teamNum,
  5593. attackerType
  5594. });
  5595. });
  5596. }
  5597. /**
  5598. * Returns the result of the battle in a promise
  5599. *
  5600. * Возращает резульат боя в промис
  5601. */
  5602. function resultBattle(resultBattles, args) {
  5603. battleData = resultBattles.results[0].result.response;
  5604. battleType = "get_tower";
  5605. if (battleData.type == "dungeon_titan") {
  5606. battleType = "get_titan";
  5607. }
  5608. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  5609. BattleCalc(battleData, battleType, function (result) {
  5610. result.teamNum = args.teamNum;
  5611. result.attackerType = args.attackerType;
  5612. args.resolve(result);
  5613. });
  5614. }
  5615. /**
  5616. * Finishing the fight
  5617. *
  5618. * Заканчиваем бой
  5619. */
  5620. async function endBattle(battleInfo) {
  5621. if (battleInfo.result.win) {
  5622. const args = {
  5623. result: battleInfo.result,
  5624. progress: battleInfo.progress,
  5625. }
  5626. if (countPredictionCard > 0) {
  5627. args.isRaid = true;
  5628. } else {
  5629. const timer = getTimer(battleInfo.battleTime);
  5630. console.log(timer);
  5631. await countdownTimer(timer, `${I18N('DUNGEON')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity} ${talentMsg}`);
  5632. }
  5633. const calls = [{
  5634. name: "dungeonEndBattle",
  5635. args,
  5636. ident: "body"
  5637. }];
  5638. lastDungeonBattleData = null;
  5639. send(JSON.stringify({ calls }), resultEndBattle);
  5640. } else {
  5641. endDungeon('dungeonEndBattle win: false\n', battleInfo);
  5642. }
  5643. }
  5644.  
  5645. /**
  5646. * Getting and processing battle results
  5647. *
  5648. * Получаем и обрабатываем результаты боя
  5649. */
  5650. function resultEndBattle(e) {
  5651. if ('error' in e) {
  5652. popup.confirm(I18N('ERROR_MSG', {
  5653. name: e.error.name,
  5654. description: e.error.description,
  5655. }));
  5656. endDungeon('errorRequest', e);
  5657. return;
  5658. }
  5659. battleResult = e.results[0].result.response;
  5660. if ('error' in battleResult) {
  5661. endDungeon('errorBattleResult', battleResult);
  5662. return;
  5663. }
  5664. dungeonGetInfo = battleResult.dungeon ?? battleResult;
  5665. dungeonActivity += battleResult.reward.dungeonActivity ?? 0;
  5666. checkFloor(dungeonGetInfo);
  5667. }
  5668.  
  5669. /**
  5670. * Returns the coefficient of condition of the
  5671. * difference in titanium before and after the battle
  5672. *
  5673. * Возвращает коэффициент состояния титанов после боя
  5674. */
  5675. function getState(result) {
  5676. if (!result.result.win) {
  5677. return -1000;
  5678. }
  5679.  
  5680. let beforeSumFactor = 0;
  5681. const beforeTitans = result.battleData.attackers;
  5682. for (let titanId in beforeTitans) {
  5683. const titan = beforeTitans[titanId];
  5684. const state = titan.state;
  5685. let factor = 1;
  5686. if (state) {
  5687. const hp = state.hp / titan.hp;
  5688. const energy = state.energy / 1e3;
  5689. factor = hp + energy / 20
  5690. }
  5691. beforeSumFactor += factor;
  5692. }
  5693.  
  5694. let afterSumFactor = 0;
  5695. const afterTitans = result.progress[0].attackers.heroes;
  5696. for (let titanId in afterTitans) {
  5697. const titan = afterTitans[titanId];
  5698. const hp = titan.hp / beforeTitans[titanId].hp;
  5699. const energy = titan.energy / 1e3;
  5700. const factor = hp + energy / 20;
  5701. afterSumFactor += factor;
  5702. }
  5703. return afterSumFactor - beforeSumFactor;
  5704. }
  5705.  
  5706. /**
  5707. * Converts an object with IDs to an array with IDs
  5708. *
  5709. * Преобразует объект с идетификаторами в массив с идетификаторами
  5710. */
  5711. function titanObjToArray(obj) {
  5712. let titans = [];
  5713. for (let id in obj) {
  5714. obj[id].id = id;
  5715. titans.push(obj[id]);
  5716. }
  5717. return titans;
  5718. }
  5719.  
  5720. function saveProgress() {
  5721. let saveProgressCall = {
  5722. calls: [{
  5723. name: "dungeonSaveProgress",
  5724. args: {},
  5725. ident: "body"
  5726. }]
  5727. }
  5728. send(JSON.stringify(saveProgressCall), resultEndBattle);
  5729. }
  5730.  
  5731. function endDungeon(reason, info) {
  5732. console.warn(reason, info);
  5733. setProgress(`${I18N('DUNGEON')} ${I18N('COMPLETED')}`, true);
  5734. resolve();
  5735. }
  5736. }
  5737.  
  5738. this.HWHClasses.executeDungeon = executeDungeon;
  5739.  
  5740. /**
  5741. * Passing the tower
  5742. *
  5743. * Прохождение башни
  5744. */
  5745. function testTower() {
  5746. const { executeTower } = HWHClasses;
  5747. return new Promise((resolve, reject) => {
  5748. tower = new executeTower(resolve, reject);
  5749. tower.start();
  5750. });
  5751. }
  5752.  
  5753. /**
  5754. * Passing the tower
  5755. *
  5756. * Прохождение башни
  5757. */
  5758. function executeTower(resolve, reject) {
  5759. lastTowerInfo = {};
  5760.  
  5761. scullCoin = 0;
  5762.  
  5763. heroGetAll = [];
  5764.  
  5765. heroesStates = {};
  5766.  
  5767. argsBattle = {
  5768. heroes: [],
  5769. favor: {},
  5770. };
  5771.  
  5772. callsExecuteTower = {
  5773. calls: [{
  5774. name: "towerGetInfo",
  5775. args: {},
  5776. ident: "towerGetInfo"
  5777. }, {
  5778. name: "teamGetAll",
  5779. args: {},
  5780. ident: "teamGetAll"
  5781. }, {
  5782. name: "teamGetFavor",
  5783. args: {},
  5784. ident: "teamGetFavor"
  5785. }, {
  5786. name: "inventoryGet",
  5787. args: {},
  5788. ident: "inventoryGet"
  5789. }, {
  5790. name: "heroGetAll",
  5791. args: {},
  5792. ident: "heroGetAll"
  5793. }]
  5794. }
  5795.  
  5796. buffIds = [
  5797. {id: 0, cost: 0, isBuy: false}, // plug // заглушка
  5798. {id: 1, cost: 1, isBuy: true}, // 3% attack // 3% атака
  5799. {id: 2, cost: 6, isBuy: true}, // 2% attack // 2% атака
  5800. {id: 3, cost: 16, isBuy: true}, // 4% attack // 4% атака
  5801. {id: 4, cost: 40, isBuy: true}, // 8% attack // 8% атака
  5802. {id: 5, cost: 1, isBuy: true}, // 10% armor // 10% броня
  5803. {id: 6, cost: 6, isBuy: true}, // 5% armor // 5% броня
  5804. {id: 7, cost: 16, isBuy: true}, // 10% armor // 10% броня
  5805. {id: 8, cost: 40, isBuy: true}, // 20% armor // 20% броня
  5806. { id: 9, cost: 1, isBuy: true }, // 10% protection from magic // 10% защита от магии
  5807. { id: 10, cost: 6, isBuy: true }, // 5% protection from magic // 5% защита от магии
  5808. { id: 11, cost: 16, isBuy: true }, // 10% protection from magic // 10% защита от магии
  5809. { id: 12, cost: 40, isBuy: true }, // 20% protection from magic // 20% защита от магии
  5810. { id: 13, cost: 1, isBuy: false }, // 40% health hero // 40% здоровья герою
  5811. { id: 14, cost: 6, isBuy: false }, // 40% health hero // 40% здоровья герою
  5812. { id: 15, cost: 16, isBuy: false }, // 80% health hero // 80% здоровья герою
  5813. { id: 16, cost: 40, isBuy: false }, // 40% health to all heroes // 40% здоровья всем героям
  5814. { id: 17, cost: 1, isBuy: false }, // 40% energy to the hero // 40% энергии герою
  5815. { id: 18, cost: 3, isBuy: false }, // 40% energy to the hero // 40% энергии герою
  5816. { id: 19, cost: 8, isBuy: false }, // 80% energy to the hero // 80% энергии герою
  5817. { id: 20, cost: 20, isBuy: false }, // 40% energy to all heroes // 40% энергии всем героям
  5818. { id: 21, cost: 40, isBuy: false }, // Hero Resurrection // Воскрешение героя
  5819. ]
  5820.  
  5821. this.start = function () {
  5822. send(JSON.stringify(callsExecuteTower), startTower);
  5823. }
  5824.  
  5825. /**
  5826. * Getting data on the Tower
  5827. *
  5828. * Получаем данные по башне
  5829. */
  5830. function startTower(e) {
  5831. res = e.results;
  5832. towerGetInfo = res[0].result.response;
  5833. if (!towerGetInfo) {
  5834. endTower('noTower', res);
  5835. return;
  5836. }
  5837. teamGetAll = res[1].result.response;
  5838. teamGetFavor = res[2].result.response;
  5839. inventoryGet = res[3].result.response;
  5840. heroGetAll = Object.values(res[4].result.response);
  5841.  
  5842. scullCoin = inventoryGet.coin[7] ?? 0;
  5843.  
  5844. argsBattle.favor = teamGetFavor.tower;
  5845. argsBattle.heroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5846. pet = teamGetAll.tower.filter(id => id >= 6000).pop();
  5847. if (pet) {
  5848. argsBattle.pet = pet;
  5849. }
  5850.  
  5851. checkFloor(towerGetInfo);
  5852. }
  5853.  
  5854. function fixHeroesTeam(argsBattle) {
  5855. let fixHeroes = argsBattle.heroes.filter(e => !heroesStates[e]?.isDead);
  5856. if (fixHeroes.length < 5) {
  5857. heroGetAll = heroGetAll.filter(e => !heroesStates[e.id]?.isDead);
  5858. fixHeroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5859. Object.keys(argsBattle.favor).forEach(e => {
  5860. if (!fixHeroes.includes(+e)) {
  5861. delete argsBattle.favor[e];
  5862. }
  5863. })
  5864. }
  5865. argsBattle.heroes = fixHeroes;
  5866. return argsBattle;
  5867. }
  5868.  
  5869. /**
  5870. * Check the floor
  5871. *
  5872. * Проверяем этаж
  5873. */
  5874. function checkFloor(towerInfo) {
  5875. lastTowerInfo = towerInfo;
  5876. maySkipFloor = +towerInfo.maySkipFloor;
  5877. floorNumber = +towerInfo.floorNumber;
  5878. heroesStates = towerInfo.states.heroes;
  5879. floorInfo = towerInfo.floor;
  5880.  
  5881. /**
  5882. * Is there at least one chest open on the floor
  5883. * Открыт ли на этаже хоть один сундук
  5884. */
  5885. isOpenChest = false;
  5886. if (towerInfo.floorType == "chest") {
  5887. isOpenChest = towerInfo.floor.chests.reduce((n, e) => n + e.opened, 0);
  5888. }
  5889.  
  5890. setProgress(`${I18N('TOWER')}: ${I18N('FLOOR')} ${floorNumber}`);
  5891. if (floorNumber > 49) {
  5892. if (isOpenChest) {
  5893. endTower('alreadyOpenChest 50 floor', floorNumber);
  5894. return;
  5895. }
  5896. }
  5897. /**
  5898. * If the chest is open and you can skip floors, then move on
  5899. * Если сундук открыт и можно скипать этажи, то переходим дальше
  5900. */
  5901. if (towerInfo.mayFullSkip && +towerInfo.teamLevel == 130) {
  5902. if (floorNumber == 1) {
  5903. fullSkipTower();
  5904. return;
  5905. }
  5906. if (isOpenChest) {
  5907. nextOpenChest(floorNumber);
  5908. } else {
  5909. nextChestOpen(floorNumber);
  5910. }
  5911. return;
  5912. }
  5913.  
  5914. // console.log(towerInfo, scullCoin);
  5915. switch (towerInfo.floorType) {
  5916. case "battle":
  5917. if (floorNumber <= maySkipFloor) {
  5918. skipFloor();
  5919. return;
  5920. }
  5921. if (floorInfo.state == 2) {
  5922. nextFloor();
  5923. return;
  5924. }
  5925. startBattle().then(endBattle);
  5926. return;
  5927. case "buff":
  5928. checkBuff(towerInfo);
  5929. return;
  5930. case "chest":
  5931. openChest(floorNumber);
  5932. return;
  5933. default:
  5934. console.log('!', towerInfo.floorType, towerInfo);
  5935. break;
  5936. }
  5937. }
  5938.  
  5939. /**
  5940. * Let's start the fight
  5941. *
  5942. * Начинаем бой
  5943. */
  5944. function startBattle() {
  5945. return new Promise(function (resolve, reject) {
  5946. towerStartBattle = {
  5947. calls: [{
  5948. name: "towerStartBattle",
  5949. args: fixHeroesTeam(argsBattle),
  5950. ident: "body"
  5951. }]
  5952. }
  5953. send(JSON.stringify(towerStartBattle), resultBattle, resolve);
  5954. });
  5955. }
  5956. /**
  5957. * Returns the result of the battle in a promise
  5958. *
  5959. * Возращает резульат боя в промис
  5960. */
  5961. function resultBattle(resultBattles, resolve) {
  5962. battleData = resultBattles.results[0].result.response;
  5963. battleType = "get_tower";
  5964. BattleCalc(battleData, battleType, function (result) {
  5965. resolve(result);
  5966. });
  5967. }
  5968. /**
  5969. * Finishing the fight
  5970. *
  5971. * Заканчиваем бой
  5972. */
  5973. function endBattle(battleInfo) {
  5974. if (battleInfo.result.stars >= 3) {
  5975. endBattleCall = {
  5976. calls: [{
  5977. name: "towerEndBattle",
  5978. args: {
  5979. result: battleInfo.result,
  5980. progress: battleInfo.progress,
  5981. },
  5982. ident: "body"
  5983. }]
  5984. }
  5985. send(JSON.stringify(endBattleCall), resultEndBattle);
  5986. } else {
  5987. endTower('towerEndBattle win: false\n', battleInfo);
  5988. }
  5989. }
  5990.  
  5991. /**
  5992. * Getting and processing battle results
  5993. *
  5994. * Получаем и обрабатываем результаты боя
  5995. */
  5996. function resultEndBattle(e) {
  5997. battleResult = e.results[0].result.response;
  5998. if ('error' in battleResult) {
  5999. endTower('errorBattleResult', battleResult);
  6000. return;
  6001. }
  6002. if ('reward' in battleResult) {
  6003. scullCoin += battleResult.reward?.coin[7] ?? 0;
  6004. }
  6005. nextFloor();
  6006. }
  6007.  
  6008. function nextFloor() {
  6009. nextFloorCall = {
  6010. calls: [{
  6011. name: "towerNextFloor",
  6012. args: {},
  6013. ident: "body"
  6014. }]
  6015. }
  6016. send(JSON.stringify(nextFloorCall), checkDataFloor);
  6017. }
  6018.  
  6019. function openChest(floorNumber) {
  6020. floorNumber = floorNumber || 0;
  6021. openChestCall = {
  6022. calls: [{
  6023. name: "towerOpenChest",
  6024. args: {
  6025. num: 2
  6026. },
  6027. ident: "body"
  6028. }]
  6029. }
  6030. send(JSON.stringify(openChestCall), floorNumber < 50 ? nextFloor : lastChest);
  6031. }
  6032.  
  6033. function lastChest() {
  6034. endTower('openChest 50 floor', floorNumber);
  6035. }
  6036.  
  6037. function skipFloor() {
  6038. skipFloorCall = {
  6039. calls: [{
  6040. name: "towerSkipFloor",
  6041. args: {},
  6042. ident: "body"
  6043. }]
  6044. }
  6045. send(JSON.stringify(skipFloorCall), checkDataFloor);
  6046. }
  6047.  
  6048. function checkBuff(towerInfo) {
  6049. buffArr = towerInfo.floor;
  6050. promises = [];
  6051. for (let buff of buffArr) {
  6052. buffInfo = buffIds[buff.id];
  6053. if (buffInfo.isBuy && buffInfo.cost <= scullCoin) {
  6054. scullCoin -= buffInfo.cost;
  6055. promises.push(buyBuff(buff.id));
  6056. }
  6057. }
  6058. Promise.all(promises).then(nextFloor);
  6059. }
  6060.  
  6061. function buyBuff(buffId) {
  6062. return new Promise(function (resolve, reject) {
  6063. buyBuffCall = {
  6064. calls: [{
  6065. name: "towerBuyBuff",
  6066. args: {
  6067. buffId
  6068. },
  6069. ident: "body"
  6070. }]
  6071. }
  6072. send(JSON.stringify(buyBuffCall), resolve);
  6073. });
  6074. }
  6075.  
  6076. function checkDataFloor(result) {
  6077. towerInfo = result.results[0].result.response;
  6078. if ('reward' in towerInfo && towerInfo.reward?.coin) {
  6079. scullCoin += towerInfo.reward?.coin[7] ?? 0;
  6080. }
  6081. if ('tower' in towerInfo) {
  6082. towerInfo = towerInfo.tower;
  6083. }
  6084. if ('skullReward' in towerInfo) {
  6085. scullCoin += towerInfo.skullReward?.coin[7] ?? 0;
  6086. }
  6087. checkFloor(towerInfo);
  6088. }
  6089. /**
  6090. * Getting tower rewards
  6091. *
  6092. * Получаем награды башни
  6093. */
  6094. function farmTowerRewards(reason) {
  6095. let { pointRewards, points } = lastTowerInfo;
  6096. let pointsAll = Object.getOwnPropertyNames(pointRewards);
  6097. let farmPoints = pointsAll.filter(e => +e <= +points && !pointRewards[e]);
  6098. if (!farmPoints.length) {
  6099. return;
  6100. }
  6101. let farmTowerRewardsCall = {
  6102. calls: [{
  6103. name: "tower_farmPointRewards",
  6104. args: {
  6105. points: farmPoints
  6106. },
  6107. ident: "tower_farmPointRewards"
  6108. }]
  6109. }
  6110.  
  6111. if (scullCoin > 0) {
  6112. farmTowerRewardsCall.calls.push({
  6113. name: "tower_farmSkullReward",
  6114. args: {},
  6115. ident: "tower_farmSkullReward"
  6116. });
  6117. }
  6118.  
  6119. send(JSON.stringify(farmTowerRewardsCall), () => { });
  6120. }
  6121.  
  6122. function fullSkipTower() {
  6123. /**
  6124. * Next chest
  6125. *
  6126. * Следующий сундук
  6127. */
  6128. function nextChest(n) {
  6129. return {
  6130. name: "towerNextChest",
  6131. args: {},
  6132. ident: "group_" + n + "_body"
  6133. }
  6134. }
  6135. /**
  6136. * Open chest
  6137. *
  6138. * Открыть сундук
  6139. */
  6140. function openChest(n) {
  6141. return {
  6142. name: "towerOpenChest",
  6143. args: {
  6144. "num": 2
  6145. },
  6146. ident: "group_" + n + "_body"
  6147. }
  6148. }
  6149.  
  6150. const fullSkipTowerCall = {
  6151. calls: []
  6152. }
  6153.  
  6154. let n = 0;
  6155. for (let i = 0; i < 15; i++) {
  6156. // 15 сундуков
  6157. fullSkipTowerCall.calls.push(nextChest(++n));
  6158. fullSkipTowerCall.calls.push(openChest(++n));
  6159. // +5 сундуков, 250 изюма // towerOpenChest
  6160. // if (i < 5) {
  6161. // fullSkipTowerCall.calls.push(openChest(++n, 2));
  6162. // }
  6163. }
  6164.  
  6165. fullSkipTowerCall.calls.push({
  6166. name: 'towerGetInfo',
  6167. args: {},
  6168. ident: 'group_' + ++n + '_body',
  6169. });
  6170.  
  6171. send(JSON.stringify(fullSkipTowerCall), data => {
  6172. for (const r of data.results) {
  6173. const towerInfo = r?.result?.response;
  6174. if (towerInfo && 'skullReward' in towerInfo) {
  6175. scullCoin += towerInfo.skullReward?.coin[7] ?? 0;
  6176. }
  6177. }
  6178. data.results[0] = data.results[data.results.length - 1];
  6179. checkDataFloor(data);
  6180. });
  6181. }
  6182.  
  6183. function nextChestOpen(floorNumber) {
  6184. const calls = [{
  6185. name: "towerOpenChest",
  6186. args: {
  6187. num: 2
  6188. },
  6189. ident: "towerOpenChest"
  6190. }];
  6191.  
  6192. Send(JSON.stringify({ calls })).then(e => {
  6193. nextOpenChest(floorNumber);
  6194. });
  6195. }
  6196.  
  6197. function nextOpenChest(floorNumber) {
  6198. if (floorNumber > 49) {
  6199. endTower('openChest 50 floor', floorNumber);
  6200. return;
  6201. }
  6202.  
  6203. let nextOpenChestCall = {
  6204. calls: [{
  6205. name: "towerNextChest",
  6206. args: {},
  6207. ident: "towerNextChest"
  6208. }, {
  6209. name: "towerOpenChest",
  6210. args: {
  6211. num: 2
  6212. },
  6213. ident: "towerOpenChest"
  6214. }]
  6215. }
  6216. send(JSON.stringify(nextOpenChestCall), checkDataFloor);
  6217. }
  6218.  
  6219. function endTower(reason, info) {
  6220. console.log(reason, info);
  6221. if (reason != 'noTower') {
  6222. farmTowerRewards(reason);
  6223. }
  6224. setProgress(`${I18N('TOWER')} ${I18N('COMPLETED')}!`, true);
  6225. resolve();
  6226. }
  6227. }
  6228.  
  6229. this.HWHClasses.executeTower = executeTower;
  6230.  
  6231. /**
  6232. * Passage of the arena of the titans
  6233. *
  6234. * Прохождение арены титанов
  6235. */
  6236. function testTitanArena() {
  6237. const { executeTitanArena } = HWHClasses;
  6238. return new Promise((resolve, reject) => {
  6239. titAren = new executeTitanArena(resolve, reject);
  6240. titAren.start();
  6241. });
  6242. }
  6243.  
  6244. /**
  6245. * Passage of the arena of the titans
  6246. *
  6247. * Прохождение арены титанов
  6248. */
  6249. function executeTitanArena(resolve, reject) {
  6250. let titan_arena = [];
  6251. let finishListBattle = [];
  6252. /**
  6253. * ID of the current batch
  6254. *
  6255. * Идетификатор текущей пачки
  6256. */
  6257. let currentRival = 0;
  6258. /**
  6259. * Number of attempts to finish off the pack
  6260. *
  6261. * Количество попыток добития пачки
  6262. */
  6263. let attempts = 0;
  6264. /**
  6265. * Was there an attempt to finish off the current shooting range
  6266. *
  6267. * Была ли попытка добития текущего тира
  6268. */
  6269. let isCheckCurrentTier = false;
  6270. /**
  6271. * Current shooting range
  6272. *
  6273. * Текущий тир
  6274. */
  6275. let currTier = 0;
  6276. /**
  6277. * Number of battles on the current dash
  6278. *
  6279. * Количество битв на текущем тире
  6280. */
  6281. let countRivalsTier = 0;
  6282.  
  6283. let callsStart = {
  6284. calls: [{
  6285. name: "titanArenaGetStatus",
  6286. args: {},
  6287. ident: "titanArenaGetStatus"
  6288. }, {
  6289. name: "teamGetAll",
  6290. args: {},
  6291. ident: "teamGetAll"
  6292. }]
  6293. }
  6294.  
  6295. this.start = function () {
  6296. send(JSON.stringify(callsStart), startTitanArena);
  6297. }
  6298.  
  6299. function startTitanArena(data) {
  6300. let titanArena = data.results[0].result.response;
  6301. if (titanArena.status == 'disabled') {
  6302. endTitanArena('disabled', titanArena);
  6303. return;
  6304. }
  6305.  
  6306. let teamGetAll = data.results[1].result.response;
  6307. titan_arena = teamGetAll.titan_arena;
  6308.  
  6309. checkTier(titanArena)
  6310. }
  6311.  
  6312. function checkTier(titanArena) {
  6313. if (titanArena.status == "peace_time") {
  6314. endTitanArena('Peace_time', titanArena);
  6315. return;
  6316. }
  6317. currTier = titanArena.tier;
  6318. if (currTier) {
  6319. setProgress(`${I18N('TITAN_ARENA')}: ${I18N('LEVEL')} ${currTier}`);
  6320. }
  6321.  
  6322. if (titanArena.status == "completed_tier") {
  6323. titanArenaCompleteTier();
  6324. return;
  6325. }
  6326. /**
  6327. * Checking for the possibility of a raid
  6328. * Проверка на возможность рейда
  6329. */
  6330. if (titanArena.canRaid) {
  6331. titanArenaStartRaid();
  6332. return;
  6333. }
  6334. /**
  6335. * Check was an attempt to achieve the current shooting range
  6336. * Проверка была ли попытка добития текущего тира
  6337. */
  6338. if (!isCheckCurrentTier) {
  6339. checkRivals(titanArena.rivals);
  6340. return;
  6341. }
  6342.  
  6343. endTitanArena('Done or not canRaid', titanArena);
  6344. }
  6345. /**
  6346. * Submit dash information for verification
  6347. *
  6348. * Отправка информации о тире на проверку
  6349. */
  6350. function checkResultInfo(data) {
  6351. let titanArena = data.results[0].result.response;
  6352. checkTier(titanArena);
  6353. }
  6354. /**
  6355. * Finish the current tier
  6356. *
  6357. * Завершить текущий тир
  6358. */
  6359. function titanArenaCompleteTier() {
  6360. isCheckCurrentTier = false;
  6361. let calls = [{
  6362. name: "titanArenaCompleteTier",
  6363. args: {},
  6364. ident: "body"
  6365. }];
  6366. send(JSON.stringify({calls}), checkResultInfo);
  6367. }
  6368. /**
  6369. * Gathering points to be completed
  6370. *
  6371. * Собираем точки которые нужно добить
  6372. */
  6373. function checkRivals(rivals) {
  6374. finishListBattle = [];
  6375. for (let n in rivals) {
  6376. if (rivals[n].attackScore < 250) {
  6377. finishListBattle.push(n);
  6378. }
  6379. }
  6380. console.log('checkRivals', finishListBattle);
  6381. countRivalsTier = finishListBattle.length;
  6382. roundRivals();
  6383. }
  6384. /**
  6385. * Selecting the next point to finish off
  6386. *
  6387. * Выбор следующей точки для добития
  6388. */
  6389. function roundRivals() {
  6390. let countRivals = finishListBattle.length;
  6391. if (!countRivals) {
  6392. /**
  6393. * Whole range checked
  6394. *
  6395. * Весь тир проверен
  6396. */
  6397. isCheckCurrentTier = true;
  6398. titanArenaGetStatus();
  6399. return;
  6400. }
  6401. // setProgress('TitanArena: Уровень ' + currTier + ' Бои: ' + (countRivalsTier - countRivals + 1) + '/' + countRivalsTier);
  6402. currentRival = finishListBattle.pop();
  6403. attempts = +currentRival;
  6404. // console.log('roundRivals', currentRival);
  6405. titanArenaStartBattle(currentRival);
  6406. }
  6407. /**
  6408. * The start of a solo battle
  6409. *
  6410. * Начало одиночной битвы
  6411. */
  6412. function titanArenaStartBattle(rivalId) {
  6413. let calls = [{
  6414. name: "titanArenaStartBattle",
  6415. args: {
  6416. rivalId: rivalId,
  6417. titans: titan_arena
  6418. },
  6419. ident: "body"
  6420. }];
  6421. send(JSON.stringify({calls}), calcResult);
  6422. }
  6423. /**
  6424. * Calculation of the results of the battle
  6425. *
  6426. * Расчет результатов боя
  6427. */
  6428. function calcResult(data) {
  6429. let battlesInfo = data.results[0].result.response.battle;
  6430. /**
  6431. * If attempts are equal to the current battle number we make
  6432. * Если попытки равны номеру текущего боя делаем прерасчет
  6433. */
  6434. if (attempts == currentRival) {
  6435. preCalcBattle(battlesInfo);
  6436. return;
  6437. }
  6438. /**
  6439. * If there are still attempts, we calculate a new battle
  6440. * Если попытки еще есть делаем расчет нового боя
  6441. */
  6442. if (attempts > 0) {
  6443. attempts--;
  6444. calcBattleResult(battlesInfo)
  6445. .then(resultCalcBattle);
  6446. return;
  6447. }
  6448. /**
  6449. * Otherwise, go to the next opponent
  6450. * Иначе переходим к следующему сопернику
  6451. */
  6452. roundRivals();
  6453. }
  6454. /**
  6455. * Processing the results of the battle calculation
  6456. *
  6457. * Обработка результатов расчета битвы
  6458. */
  6459. function resultCalcBattle(resultBattle) {
  6460. // console.log('resultCalcBattle', currentRival, attempts, resultBattle.result.win);
  6461. /**
  6462. * If the current calculation of victory is not a chance or the attempt ended with the finish the battle
  6463. * Если текущий расчет победа или шансов нет или попытки кончились завершаем бой
  6464. */
  6465. if (resultBattle.result.win || !attempts) {
  6466. titanArenaEndBattle({
  6467. progress: resultBattle.progress,
  6468. result: resultBattle.result,
  6469. rivalId: resultBattle.battleData.typeId
  6470. });
  6471. return;
  6472. }
  6473. /**
  6474. * If not victory and there are attempts we start a new battle
  6475. * Если не победа и есть попытки начинаем новый бой
  6476. */
  6477. titanArenaStartBattle(resultBattle.battleData.typeId);
  6478. }
  6479. /**
  6480. * Returns the promise of calculating the results of the battle
  6481. *
  6482. * Возращает промис расчета результатов битвы
  6483. */
  6484. function getBattleInfo(battle, isRandSeed) {
  6485. return new Promise(function (resolve) {
  6486. if (isRandSeed) {
  6487. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  6488. }
  6489. // console.log(battle.seed);
  6490. BattleCalc(battle, "get_titanClanPvp", e => resolve(e));
  6491. });
  6492. }
  6493. /**
  6494. * Recalculate battles
  6495. *
  6496. * Прерасчтет битвы
  6497. */
  6498. function preCalcBattle(battle) {
  6499. let actions = [getBattleInfo(battle, false)];
  6500. const countTestBattle = getInput('countTestBattle');
  6501. for (let i = 0; i < countTestBattle; i++) {
  6502. actions.push(getBattleInfo(battle, true));
  6503. }
  6504. Promise.all(actions)
  6505. .then(resultPreCalcBattle);
  6506. }
  6507. /**
  6508. * Processing the results of the battle recalculation
  6509. *
  6510. * Обработка результатов прерасчета битвы
  6511. */
  6512. function resultPreCalcBattle(e) {
  6513. let wins = e.map(n => n.result.win);
  6514. let firstBattle = e.shift();
  6515. let countWin = wins.reduce((w, s) => w + s);
  6516. const countTestBattle = getInput('countTestBattle');
  6517. console.log('resultPreCalcBattle', `${countWin}/${countTestBattle}`)
  6518. if (countWin > 0) {
  6519. attempts = getInput('countAutoBattle');
  6520. } else {
  6521. attempts = 0;
  6522. }
  6523. resultCalcBattle(firstBattle);
  6524. }
  6525.  
  6526. /**
  6527. * Complete an arena battle
  6528. *
  6529. * Завершить битву на арене
  6530. */
  6531. function titanArenaEndBattle(args) {
  6532. let calls = [{
  6533. name: "titanArenaEndBattle",
  6534. args,
  6535. ident: "body"
  6536. }];
  6537. send(JSON.stringify({calls}), resultTitanArenaEndBattle);
  6538. }
  6539.  
  6540. function resultTitanArenaEndBattle(e) {
  6541. let attackScore = e.results[0].result.response.attackScore;
  6542. let numReval = countRivalsTier - finishListBattle.length;
  6543. setProgress(`${I18N('TITAN_ARENA')}: ${I18N('LEVEL')} ${currTier} </br>${I18N('BATTLES')}: ${numReval}/${countRivalsTier} - ${attackScore}`);
  6544. /**
  6545. * TODO: Might need to improve the results.
  6546. * TODO: Возможно стоит сделать улучшение результатов
  6547. */
  6548. // console.log('resultTitanArenaEndBattle', e)
  6549. console.log('resultTitanArenaEndBattle', numReval + '/' + countRivalsTier, attempts)
  6550. roundRivals();
  6551. }
  6552. /**
  6553. * Arena State
  6554. *
  6555. * Состояние арены
  6556. */
  6557. function titanArenaGetStatus() {
  6558. let calls = [{
  6559. name: "titanArenaGetStatus",
  6560. args: {},
  6561. ident: "body"
  6562. }];
  6563. send(JSON.stringify({calls}), checkResultInfo);
  6564. }
  6565. /**
  6566. * Arena Raid Request
  6567. *
  6568. * Запрос рейда арены
  6569. */
  6570. function titanArenaStartRaid() {
  6571. let calls = [{
  6572. name: "titanArenaStartRaid",
  6573. args: {
  6574. titans: titan_arena
  6575. },
  6576. ident: "body"
  6577. }];
  6578. send(JSON.stringify({calls}), calcResults);
  6579. }
  6580.  
  6581. function calcResults(data) {
  6582. let battlesInfo = data.results[0].result.response;
  6583. let {attackers, rivals} = battlesInfo;
  6584.  
  6585. let promises = [];
  6586. for (let n in rivals) {
  6587. rival = rivals[n];
  6588. promises.push(calcBattleResult({
  6589. attackers: attackers,
  6590. defenders: [rival.team],
  6591. seed: rival.seed,
  6592. typeId: n,
  6593. }));
  6594. }
  6595.  
  6596. Promise.all(promises)
  6597. .then(results => {
  6598. const endResults = {};
  6599. for (let info of results) {
  6600. let id = info.battleData.typeId;
  6601. endResults[id] = {
  6602. progress: info.progress,
  6603. result: info.result,
  6604. }
  6605. }
  6606. titanArenaEndRaid(endResults);
  6607. });
  6608. }
  6609.  
  6610. function calcBattleResult(battleData) {
  6611. return new Promise(function (resolve, reject) {
  6612. BattleCalc(battleData, "get_titanClanPvp", resolve);
  6613. });
  6614. }
  6615.  
  6616. /**
  6617. * Sending Raid Results
  6618. *
  6619. * Отправка результатов рейда
  6620. */
  6621. function titanArenaEndRaid(results) {
  6622. titanArenaEndRaidCall = {
  6623. calls: [{
  6624. name: "titanArenaEndRaid",
  6625. args: {
  6626. results
  6627. },
  6628. ident: "body"
  6629. }]
  6630. }
  6631. send(JSON.stringify(titanArenaEndRaidCall), checkRaidResults);
  6632. }
  6633.  
  6634. function checkRaidResults(data) {
  6635. results = data.results[0].result.response.results;
  6636. isSucsesRaid = true;
  6637. for (let i in results) {
  6638. isSucsesRaid &&= (results[i].attackScore >= 250);
  6639. }
  6640.  
  6641. if (isSucsesRaid) {
  6642. titanArenaCompleteTier();
  6643. } else {
  6644. titanArenaGetStatus();
  6645. }
  6646. }
  6647.  
  6648. function titanArenaFarmDailyReward() {
  6649. titanArenaFarmDailyRewardCall = {
  6650. calls: [{
  6651. name: "titanArenaFarmDailyReward",
  6652. args: {},
  6653. ident: "body"
  6654. }]
  6655. }
  6656. send(JSON.stringify(titanArenaFarmDailyRewardCall), () => {console.log('Done farm daily reward')});
  6657. }
  6658.  
  6659. function endTitanArena(reason, info) {
  6660. if (!['Peace_time', 'disabled'].includes(reason)) {
  6661. titanArenaFarmDailyReward();
  6662. }
  6663. console.log(reason, info);
  6664. setProgress(`${I18N('TITAN_ARENA')} ${I18N('COMPLETED')}!`, true);
  6665. resolve();
  6666. }
  6667. }
  6668.  
  6669. this.HWHClasses.executeTitanArena = executeTitanArena;
  6670.  
  6671. function hackGame() {
  6672. const self = this;
  6673. selfGame = null;
  6674. bindId = 1e9;
  6675. this.libGame = null;
  6676. this.doneLibLoad = () => {}
  6677.  
  6678. /**
  6679. * List of correspondence of used classes to their names
  6680. *
  6681. * Список соответствия используемых классов их названиям
  6682. */
  6683. ObjectsList = [
  6684. { name: 'BattlePresets', prop: 'game.battle.controller.thread.BattlePresets' },
  6685. { name: 'DataStorage', prop: 'game.data.storage.DataStorage' },
  6686. { name: 'BattleConfigStorage', prop: 'game.data.storage.battle.BattleConfigStorage' },
  6687. { name: 'BattleInstantPlay', prop: 'game.battle.controller.instant.BattleInstantPlay' },
  6688. { name: 'MultiBattleInstantReplay', prop: 'game.battle.controller.instant.MultiBattleInstantReplay' },
  6689. { name: 'MultiBattleResult', prop: 'game.battle.controller.MultiBattleResult' },
  6690.  
  6691. { name: 'PlayerMissionData', prop: 'game.model.user.mission.PlayerMissionData' },
  6692. { name: 'PlayerMissionBattle', prop: 'game.model.user.mission.PlayerMissionBattle' },
  6693. { name: 'GameModel', prop: 'game.model.GameModel' },
  6694. { name: 'CommandManager', prop: 'game.command.CommandManager' },
  6695. { name: 'MissionCommandList', prop: 'game.command.rpc.mission.MissionCommandList' },
  6696. { name: 'RPCCommandBase', prop: 'game.command.rpc.RPCCommandBase' },
  6697. { name: 'PlayerTowerData', prop: 'game.model.user.tower.PlayerTowerData' },
  6698. { name: 'TowerCommandList', prop: 'game.command.tower.TowerCommandList' },
  6699. { name: 'PlayerHeroTeamResolver', prop: 'game.model.user.hero.PlayerHeroTeamResolver' },
  6700. { name: 'BattlePausePopup', prop: 'game.view.popup.battle.BattlePausePopup' },
  6701. { name: 'BattlePopup', prop: 'game.view.popup.battle.BattlePopup' },
  6702. { name: 'DisplayObjectContainer', prop: 'starling.display.DisplayObjectContainer' },
  6703. { name: 'GuiClipContainer', prop: 'engine.core.clipgui.GuiClipContainer' },
  6704. { name: 'BattlePausePopupClip', prop: 'game.view.popup.battle.BattlePausePopupClip' },
  6705. { name: 'ClipLabel', prop: 'game.view.gui.components.ClipLabel' },
  6706. { name: 'ClipLabelBase', prop: 'game.view.gui.components.ClipLabelBase' },
  6707. { name: 'Translate', prop: 'com.progrestar.common.lang.Translate' },
  6708. { name: 'ClipButtonLabeledCentered', prop: 'game.view.gui.components.ClipButtonLabeledCentered' },
  6709. { name: 'BattlePausePopupMediator', prop: 'game.mediator.gui.popup.battle.BattlePausePopupMediator' },
  6710. { name: 'SettingToggleButton', prop: 'game.mechanics.settings.popup.view.SettingToggleButton' },
  6711. { name: 'PlayerDungeonData', prop: 'game.mechanics.dungeon.model.PlayerDungeonData' },
  6712. { name: 'NextDayUpdatedManager', prop: 'game.model.user.NextDayUpdatedManager' },
  6713. { name: 'BattleController', prop: 'game.battle.controller.BattleController' },
  6714. { name: 'BattleSettingsModel', prop: 'game.battle.controller.BattleSettingsModel' },
  6715. { name: 'BooleanProperty', prop: 'engine.core.utils.property.BooleanProperty' },
  6716. { name: 'RuleStorage', prop: 'game.data.storage.rule.RuleStorage' },
  6717. { name: 'BattleConfig', prop: 'battle.BattleConfig' },
  6718. { name: 'BattleGuiMediator', prop: 'game.battle.gui.BattleGuiMediator' },
  6719. { name: 'BooleanPropertyWriteable', prop: 'engine.core.utils.property.BooleanPropertyWriteable' },
  6720. { name: 'BattleLogEncoder', prop: 'battle.log.BattleLogEncoder' },
  6721. { name: 'BattleLogReader', prop: 'battle.log.BattleLogReader' },
  6722. { name: 'PlayerSubscriptionInfoValueObject', prop: 'game.model.user.subscription.PlayerSubscriptionInfoValueObject' },
  6723. { name: 'AdventureMapCamera', prop: 'game.mechanics.adventure.popup.map.AdventureMapCamera' },
  6724. ];
  6725.  
  6726. /**
  6727. * Contains the game classes needed to write and override game methods
  6728. *
  6729. * Содержит классы игры необходимые для написания и подмены методов игры
  6730. */
  6731. Game = {
  6732. /**
  6733. * Function 'e'
  6734. * Функция 'e'
  6735. */
  6736. bindFunc: function (a, b) {
  6737. if (null == b)
  6738. return null;
  6739. null == b.__id__ && (b.__id__ = bindId++);
  6740. var c;
  6741. null == a.hx__closures__ ? a.hx__closures__ = {} :
  6742. c = a.hx__closures__[b.__id__];
  6743. null == c && (c = b.bind(a), a.hx__closures__[b.__id__] = c);
  6744. return c
  6745. },
  6746. };
  6747.  
  6748. /**
  6749. * Connects to game objects via the object creation event
  6750. *
  6751. * Подключается к объектам игры через событие создания объекта
  6752. */
  6753. function connectGame() {
  6754. for (let obj of ObjectsList) {
  6755. /**
  6756. * https: //stackoverflow.com/questions/42611719/how-to-intercept-and-modify-a-specific-property-for-any-object
  6757. */
  6758. Object.defineProperty(Object.prototype, obj.prop, {
  6759. set: function (value) {
  6760. if (!selfGame) {
  6761. selfGame = this;
  6762. }
  6763. if (!Game[obj.name]) {
  6764. Game[obj.name] = value;
  6765. }
  6766. // console.log('set ' + obj.prop, this, value);
  6767. this[obj.prop + '_'] = value;
  6768. },
  6769. get: function () {
  6770. // console.log('get ' + obj.prop, this);
  6771. return this[obj.prop + '_'];
  6772. }
  6773. });
  6774. }
  6775. }
  6776.  
  6777. /**
  6778. * Game.BattlePresets
  6779. * @param {bool} a isReplay
  6780. * @param {bool} b autoToggleable
  6781. * @param {bool} c auto On Start
  6782. * @param {object} d config
  6783. * @param {bool} f showBothTeams
  6784. */
  6785. /**
  6786. * Returns the results of the battle to the callback function
  6787. * Возвращает в функцию callback результаты боя
  6788. * @param {*} battleData battle data данные боя
  6789. * @param {*} battleConfig combat configuration type options:
  6790. *
  6791. * тип конфигурации боя варианты:
  6792. *
  6793. * "get_invasion", "get_titanPvpManual", "get_titanPvp",
  6794. * "get_titanClanPvp","get_clanPvp","get_titan","get_boss",
  6795. * "get_tower","get_pve","get_pvpManual","get_pvp","get_core"
  6796. *
  6797. * You can specify the xYc function in the game.assets.storage.BattleAssetStorage class
  6798. *
  6799. * Можно уточнить в классе game.assets.storage.BattleAssetStorage функция xYc
  6800. * @param {*} callback функция в которую вернуться результаты боя
  6801. */
  6802. this.BattleCalc = function (battleData, battleConfig, callback) {
  6803. // battleConfig = battleConfig || getBattleType(battleData.type)
  6804. if (!Game.BattlePresets) throw Error('Use connectGame');
  6805. battlePresets = new Game.BattlePresets(battleData.progress, !1, !0, Game.DataStorage[getFn(Game.DataStorage, 24)][getF(Game.BattleConfigStorage, battleConfig)](), !1);
  6806. let battleInstantPlay;
  6807. if (battleData.progress?.length > 1) {
  6808. battleInstantPlay = new Game.MultiBattleInstantReplay(battleData, battlePresets);
  6809. } else {
  6810. battleInstantPlay = new Game.BattleInstantPlay(battleData, battlePresets);
  6811. }
  6812. battleInstantPlay[getProtoFn(Game.BattleInstantPlay, 9)].add((battleInstant) => {
  6813. const MBR_2 = getProtoFn(Game.MultiBattleResult, 2);
  6814. const battleResults = battleInstant[getF(Game.BattleInstantPlay, 'get_result')]();
  6815. const battleData = battleInstant[getF(Game.BattleInstantPlay, 'get_rawBattleInfo')]();
  6816. const battleLogs = [];
  6817. const timeLimit = battlePresets[getF(Game.BattlePresets, 'get_timeLimit')]();
  6818. let battleTime = 0;
  6819. let battleTimer = 0;
  6820. for (const battleResult of battleResults[MBR_2]) {
  6821. const battleLog = Game.BattleLogEncoder.read(new Game.BattleLogReader(battleResult));
  6822. battleLogs.push(battleLog);
  6823. const maxTime = Math.max(...battleLog.map((e) => (e.time < timeLimit && e.time !== 168.8 ? e.time : 0)));
  6824. battleTimer += getTimer(maxTime)
  6825. battleTime += maxTime;
  6826. }
  6827. callback({
  6828. battleLogs,
  6829. battleTime,
  6830. battleTimer,
  6831. battleData,
  6832. progress: battleResults[getF(Game.MultiBattleResult, 'get_progress')](),
  6833. result: battleResults[getF(Game.MultiBattleResult, 'get_result')](),
  6834. });
  6835. });
  6836. battleInstantPlay.start();
  6837. }
  6838.  
  6839. /**
  6840. * Returns a function with the specified name from the class
  6841. *
  6842. * Возвращает из класса функцию с указанным именем
  6843. * @param {Object} classF Class // класс
  6844. * @param {String} nameF function name // имя функции
  6845. * @param {String} pos name and alias order // порядок имени и псевдонима
  6846. * @returns
  6847. */
  6848. function getF(classF, nameF, pos) {
  6849. pos = pos || false;
  6850. let prop = Object.entries(classF.prototype.__properties__)
  6851. if (!pos) {
  6852. return prop.filter((e) => e[1] == nameF).pop()[0];
  6853. } else {
  6854. return prop.filter((e) => e[0] == nameF).pop()[1];
  6855. }
  6856. }
  6857.  
  6858. /**
  6859. * Returns a function with the specified name from the class
  6860. *
  6861. * Возвращает из класса функцию с указанным именем
  6862. * @param {Object} classF Class // класс
  6863. * @param {String} nameF function name // имя функции
  6864. * @returns
  6865. */
  6866. function getFnP(classF, nameF) {
  6867. let prop = Object.entries(classF.__properties__)
  6868. return prop.filter((e) => e[1] == nameF).pop()[0];
  6869. }
  6870.  
  6871. /**
  6872. * Returns the function name with the specified ordinal from the class
  6873. *
  6874. * Возвращает имя функции с указаным порядковым номером из класса
  6875. * @param {Object} classF Class // класс
  6876. * @param {Number} nF Order number of function // порядковый номер функции
  6877. * @returns
  6878. */
  6879. function getFn(classF, nF) {
  6880. let prop = Object.keys(classF);
  6881. return prop[nF];
  6882. }
  6883.  
  6884. /**
  6885. * Returns the name of the function with the specified serial number from the prototype of the class
  6886. *
  6887. * Возвращает имя функции с указаным порядковым номером из прототипа класса
  6888. * @param {Object} classF Class // класс
  6889. * @param {Number} nF Order number of function // порядковый номер функции
  6890. * @returns
  6891. */
  6892. function getProtoFn(classF, nF) {
  6893. let prop = Object.keys(classF.prototype);
  6894. return prop[nF];
  6895. }
  6896. /**
  6897. * Description of replaced functions
  6898. *
  6899. * Описание подменяемых функций
  6900. */
  6901. replaceFunction = {
  6902. company: function () {
  6903. let PMD_12 = getProtoFn(Game.PlayerMissionData, 12);
  6904. let oldSkipMisson = Game.PlayerMissionData.prototype[PMD_12];
  6905. Game.PlayerMissionData.prototype[PMD_12] = function (a, b, c) {
  6906. if (!isChecked('passBattle')) {
  6907. oldSkipMisson.call(this, a, b, c);
  6908. return;
  6909. }
  6910.  
  6911. try {
  6912. this[getProtoFn(Game.PlayerMissionData, 9)] = new Game.PlayerMissionBattle(a, b, c);
  6913.  
  6914. var a = new Game.BattlePresets(
  6915. !1,
  6916. !1,
  6917. !0,
  6918. Game.DataStorage[getFn(Game.DataStorage, 24)][getProtoFn(Game.BattleConfigStorage, 20)](),
  6919. !1
  6920. );
  6921. a = new Game.BattleInstantPlay(c, a);
  6922. a[getProtoFn(Game.BattleInstantPlay, 9)].add(Game.bindFunc(this, this.P$h));
  6923. a.start();
  6924. } catch (error) {
  6925. console.error('company', error);
  6926. oldSkipMisson.call(this, a, b, c);
  6927. }
  6928. };
  6929.  
  6930. Game.PlayerMissionData.prototype.P$h = function (a) {
  6931. let GM_2 = getFn(Game.GameModel, 2);
  6932. let GM_P2 = getProtoFn(Game.GameModel, 2);
  6933. let CM_20 = getProtoFn(Game.CommandManager, 20);
  6934. let MCL_2 = getProtoFn(Game.MissionCommandList, 2);
  6935. let MBR_15 = getF(Game.MultiBattleResult, 'get_result');
  6936. let RPCCB_15 = getProtoFn(Game.RPCCommandBase, 16);
  6937. let PMD_32 = getProtoFn(Game.PlayerMissionData, 32);
  6938. Game.GameModel[GM_2]()[GM_P2][CM_20][MCL_2](a[MBR_15]())[RPCCB_15](Game.bindFunc(this, this[PMD_32]));
  6939. };
  6940. },
  6941. /*
  6942. tower: function () {
  6943. let PTD_67 = getProtoFn(Game.PlayerTowerData, 67);
  6944. let oldSkipTower = Game.PlayerTowerData.prototype[PTD_67];
  6945. Game.PlayerTowerData.prototype[PTD_67] = function (a) {
  6946. if (!isChecked('passBattle')) {
  6947. oldSkipTower.call(this, a);
  6948. return;
  6949. }
  6950. try {
  6951. var p = new Game.BattlePresets(
  6952. !1,
  6953. !1,
  6954. !0,
  6955. Game.DataStorage[getFn(Game.DataStorage, 24)][getProtoFn(Game.BattleConfigStorage, 20)](),
  6956. !1
  6957. );
  6958. a = new Game.BattleInstantPlay(a, p);
  6959. a[getProtoFn(Game.BattleInstantPlay, 9)].add(Game.bindFunc(this, this.P$h));
  6960. a.start();
  6961. } catch (error) {
  6962. console.error('tower', error);
  6963. oldSkipMisson.call(this, a, b, c);
  6964. }
  6965. };
  6966.  
  6967. Game.PlayerTowerData.prototype.P$h = function (a) {
  6968. const GM_2 = getFnP(Game.GameModel, 'get_instance');
  6969. const GM_P2 = getProtoFn(Game.GameModel, 2);
  6970. const CM_29 = getProtoFn(Game.CommandManager, 29);
  6971. const TCL_5 = getProtoFn(Game.TowerCommandList, 5);
  6972. const MBR_15 = getF(Game.MultiBattleResult, 'get_result');
  6973. const RPCCB_15 = getProtoFn(Game.RPCCommandBase, 17);
  6974. const PTD_78 = getProtoFn(Game.PlayerTowerData, 78);
  6975. Game.GameModel[GM_2]()[GM_P2][CM_29][TCL_5](a[MBR_15]())[RPCCB_15](Game.bindFunc(this, this[PTD_78]));
  6976. };
  6977. },
  6978. */
  6979. // skipSelectHero: function() {
  6980. // if (!HOST) throw Error('Use connectGame');
  6981. // Game.PlayerHeroTeamResolver.prototype[getProtoFn(Game.PlayerHeroTeamResolver, 3)] = () => false;
  6982. // },
  6983. passBattle: function () {
  6984. let BPP_4 = getProtoFn(Game.BattlePausePopup, 4);
  6985. let oldPassBattle = Game.BattlePausePopup.prototype[BPP_4];
  6986. Game.BattlePausePopup.prototype[BPP_4] = function (a) {
  6987. if (!isChecked('passBattle')) {
  6988. oldPassBattle.call(this, a);
  6989. return;
  6990. }
  6991. try {
  6992. Game.BattlePopup.prototype[getProtoFn(Game.BattlePausePopup, 4)].call(this, a);
  6993. this[getProtoFn(Game.BattlePausePopup, 3)]();
  6994. this[getProtoFn(Game.DisplayObjectContainer, 3)](this.clip[getProtoFn(Game.GuiClipContainer, 2)]());
  6995. this.clip[getProtoFn(Game.BattlePausePopupClip, 1)][getProtoFn(Game.ClipLabelBase, 9)](
  6996. Game.Translate.translate('UI_POPUP_BATTLE_PAUSE')
  6997. );
  6998.  
  6999. this.clip[getProtoFn(Game.BattlePausePopupClip, 2)][getProtoFn(Game.ClipButtonLabeledCentered, 2)](
  7000. Game.Translate.translate('UI_POPUP_BATTLE_RETREAT'),
  7001. ((q = this[getProtoFn(Game.BattlePausePopup, 1)]), Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 17)]))
  7002. );
  7003. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 2)](
  7004. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 14)](),
  7005. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 13)]()
  7006. ? ((q = this[getProtoFn(Game.BattlePausePopup, 1)]), Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 18)]))
  7007. : ((q = this[getProtoFn(Game.BattlePausePopup, 1)]), Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 18)]))
  7008. );
  7009.  
  7010. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 0)][
  7011. getProtoFn(Game.ClipLabelBase, 24)
  7012. ]();
  7013. this.clip[getProtoFn(Game.BattlePausePopupClip, 3)][getProtoFn(Game.SettingToggleButton, 3)](
  7014. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 9)]()
  7015. );
  7016. this.clip[getProtoFn(Game.BattlePausePopupClip, 4)][getProtoFn(Game.SettingToggleButton, 3)](
  7017. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 10)]()
  7018. );
  7019. this.clip[getProtoFn(Game.BattlePausePopupClip, 6)][getProtoFn(Game.SettingToggleButton, 3)](
  7020. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 11)]()
  7021. );
  7022. } catch (error) {
  7023. console.error('passBattle', error);
  7024. oldPassBattle.call(this, a);
  7025. }
  7026. };
  7027.  
  7028. let retreatButtonLabel = getF(Game.BattlePausePopupMediator, 'get_retreatButtonLabel');
  7029. let oldFunc = Game.BattlePausePopupMediator.prototype[retreatButtonLabel];
  7030. Game.BattlePausePopupMediator.prototype[retreatButtonLabel] = function () {
  7031. if (isChecked('passBattle')) {
  7032. return I18N('BTN_PASS');
  7033. } else {
  7034. return oldFunc.call(this);
  7035. }
  7036. };
  7037. },
  7038. endlessCards: function () {
  7039. let PDD_21 = getProtoFn(Game.PlayerDungeonData, 21);
  7040. let oldEndlessCards = Game.PlayerDungeonData.prototype[PDD_21];
  7041. Game.PlayerDungeonData.prototype[PDD_21] = function () {
  7042. if (countPredictionCard <= 0) {
  7043. return true;
  7044. } else {
  7045. return oldEndlessCards.call(this);
  7046. }
  7047. };
  7048. },
  7049. speedBattle: function () {
  7050. const get_timeScale = getF(Game.BattleController, 'get_timeScale');
  7051. const oldSpeedBattle = Game.BattleController.prototype[get_timeScale];
  7052. Game.BattleController.prototype[get_timeScale] = function () {
  7053. const speedBattle = Number.parseFloat(getInput('speedBattle'));
  7054. if (!speedBattle) {
  7055. return oldSpeedBattle.call(this);
  7056. }
  7057. try {
  7058. const BC_12 = getProtoFn(Game.BattleController, 12);
  7059. const BSM_12 = getProtoFn(Game.BattleSettingsModel, 12);
  7060. const BP_get_value = getF(Game.BooleanProperty, 'get_value');
  7061. if (this[BC_12][BSM_12][BP_get_value]()) {
  7062. return 0;
  7063. }
  7064. const BSM_2 = getProtoFn(Game.BattleSettingsModel, 2);
  7065. const BC_49 = getProtoFn(Game.BattleController, 49);
  7066. const BSM_1 = getProtoFn(Game.BattleSettingsModel, 1);
  7067. const BC_14 = getProtoFn(Game.BattleController, 14);
  7068. const BC_3 = getFn(Game.BattleController, 3);
  7069. if (this[BC_12][BSM_2][BP_get_value]()) {
  7070. var a = speedBattle * this[BC_49]();
  7071. } else {
  7072. a = this[BC_12][BSM_1][BP_get_value]();
  7073. const maxSpeed = Math.max(...this[BC_14]);
  7074. const multiple = a == this[BC_14].indexOf(maxSpeed) ? (maxSpeed >= 4 ? speedBattle : this[BC_14][a]) : this[BC_14][a];
  7075. a = multiple * Game.BattleController[BC_3][BP_get_value]() * this[BC_49]();
  7076. }
  7077. const BSM_24 = getProtoFn(Game.BattleSettingsModel, 24);
  7078. a > this[BC_12][BSM_24][BP_get_value]() && (a = this[BC_12][BSM_24][BP_get_value]());
  7079. const DS_23 = getFn(Game.DataStorage, 23);
  7080. const get_battleSpeedMultiplier = getF(Game.RuleStorage, 'get_battleSpeedMultiplier', true);
  7081. var b = Game.DataStorage[DS_23][get_battleSpeedMultiplier]();
  7082. const R_1 = getFn(selfGame.Reflect, 1);
  7083. const BC_1 = getFn(Game.BattleController, 1);
  7084. const get_config = getF(Game.BattlePresets, 'get_config');
  7085. null != b &&
  7086. (a = selfGame.Reflect[R_1](b, this[BC_1][get_config]().ident)
  7087. ? a * selfGame.Reflect[R_1](b, this[BC_1][get_config]().ident)
  7088. : a * selfGame.Reflect[R_1](b, 'default'));
  7089. return a;
  7090. } catch (error) {
  7091. console.error('passBatspeedBattletle', error);
  7092. return oldSpeedBattle.call(this);
  7093. }
  7094. };
  7095. },
  7096.  
  7097. /**
  7098. * Acceleration button without Valkyries favor
  7099. *
  7100. * Кнопка ускорения без Покровительства Валькирий
  7101. */
  7102. battleFastKey: function () {
  7103. const BGM_44 = getProtoFn(Game.BattleGuiMediator, 44);
  7104. const oldBattleFastKey = Game.BattleGuiMediator.prototype[BGM_44];
  7105. Game.BattleGuiMediator.prototype[BGM_44] = function () {
  7106. let flag = true;
  7107. //console.log(flag)
  7108. if (!flag) {
  7109. return oldBattleFastKey.call(this);
  7110. }
  7111. try {
  7112. const BGM_9 = getProtoFn(Game.BattleGuiMediator, 9);
  7113. const BGM_10 = getProtoFn(Game.BattleGuiMediator, 10);
  7114. const BPW_0 = getProtoFn(Game.BooleanPropertyWriteable, 0);
  7115. this[BGM_9][BPW_0](true);
  7116. this[BGM_10][BPW_0](true);
  7117. } catch (error) {
  7118. console.error(error);
  7119. return oldBattleFastKey.call(this);
  7120. }
  7121. };
  7122. },
  7123. fastSeason: function () {
  7124. const GameNavigator = selfGame['game.screen.navigator.GameNavigator'];
  7125. const oldFuncName = getProtoFn(GameNavigator, 18);
  7126. const newFuncName = getProtoFn(GameNavigator, 16);
  7127. const oldFastSeason = GameNavigator.prototype[oldFuncName];
  7128. const newFastSeason = GameNavigator.prototype[newFuncName];
  7129. GameNavigator.prototype[oldFuncName] = function (a, b) {
  7130. if (isChecked('fastSeason')) {
  7131. return newFastSeason.apply(this, [a]);
  7132. } else {
  7133. return oldFastSeason.apply(this, [a, b]);
  7134. }
  7135. };
  7136. },
  7137. ShowChestReward: function () {
  7138. const TitanArtifactChest = selfGame['game.mechanics.titan_arena.mediator.chest.TitanArtifactChestRewardPopupMediator'];
  7139. const getOpenAmountTitan = getF(TitanArtifactChest, 'get_openAmount');
  7140. const oldGetOpenAmountTitan = TitanArtifactChest.prototype[getOpenAmountTitan];
  7141. TitanArtifactChest.prototype[getOpenAmountTitan] = function () {
  7142. if (correctShowOpenArtifact) {
  7143. correctShowOpenArtifact--;
  7144. return 100;
  7145. }
  7146. return oldGetOpenAmountTitan.call(this);
  7147. };
  7148.  
  7149. const ArtifactChest = selfGame['game.view.popup.artifactchest.rewardpopup.ArtifactChestRewardPopupMediator'];
  7150. const getOpenAmount = getF(ArtifactChest, 'get_openAmount');
  7151. const oldGetOpenAmount = ArtifactChest.prototype[getOpenAmount];
  7152. ArtifactChest.prototype[getOpenAmount] = function () {
  7153. if (correctShowOpenArtifact) {
  7154. correctShowOpenArtifact--;
  7155. return 100;
  7156. }
  7157. return oldGetOpenAmount.call(this);
  7158. };
  7159. },
  7160. fixCompany: function () {
  7161. const GameBattleView = selfGame['game.mediator.gui.popup.battle.GameBattleView'];
  7162. const BattleThread = selfGame['game.battle.controller.thread.BattleThread'];
  7163. const getOnViewDisposed = getF(BattleThread, 'get_onViewDisposed');
  7164. const getThread = getF(GameBattleView, 'get_thread');
  7165. const oldFunc = GameBattleView.prototype[getThread];
  7166. GameBattleView.prototype[getThread] = function () {
  7167. return (
  7168. oldFunc.call(this) || {
  7169. [getOnViewDisposed]: async () => {},
  7170. }
  7171. );
  7172. };
  7173. },
  7174. BuyTitanArtifact: function () {
  7175. const BIP_4 = getProtoFn(selfGame['game.view.popup.shop.buy.BuyItemPopup'], 4);
  7176. const BuyItemPopup = selfGame['game.view.popup.shop.buy.BuyItemPopup'];
  7177. const oldFunc = BuyItemPopup.prototype[BIP_4];
  7178. BuyItemPopup.prototype[BIP_4] = function () {
  7179. if (isChecked('countControl')) {
  7180. const BuyTitanArtifactItemPopup = selfGame['game.view.popup.shop.buy.BuyTitanArtifactItemPopup'];
  7181. const BTAP_0 = getProtoFn(BuyTitanArtifactItemPopup, 0);
  7182. if (this[BTAP_0]) {
  7183. const BuyTitanArtifactPopupMediator = selfGame['game.mediator.gui.popup.shop.buy.BuyTitanArtifactItemPopupMediator'];
  7184. const BTAM_1 = getProtoFn(BuyTitanArtifactPopupMediator, 1);
  7185. const BuyItemPopupMediator = selfGame['game.mediator.gui.popup.shop.buy.BuyItemPopupMediator'];
  7186. const BIPM_5 = getProtoFn(BuyItemPopupMediator, 5);
  7187. const BIPM_7 = getProtoFn(BuyItemPopupMediator, 7);
  7188. const BIPM_9 = getProtoFn(BuyItemPopupMediator, 9);
  7189.  
  7190. let need = Math.min(this[BTAP_0][BTAM_1](), this[BTAP_0][BIPM_7]);
  7191. need = need ? need : 60;
  7192. this[BTAP_0][BIPM_9] = need;
  7193. this[BTAP_0][BIPM_5] = 10;
  7194. }
  7195. }
  7196. oldFunc.call(this);
  7197. };
  7198. },
  7199. ClanQuestsFastFarm: function () {
  7200. const VipRuleValueObject = selfGame['game.data.storage.rule.VipRuleValueObject'];
  7201. const getClanQuestsFastFarm = getF(VipRuleValueObject, 'get_clanQuestsFastFarm', 1);
  7202. VipRuleValueObject.prototype[getClanQuestsFastFarm] = function () {
  7203. return 0;
  7204. };
  7205. },
  7206. adventureCamera: function () {
  7207. const AMC_40 = getProtoFn(Game.AdventureMapCamera, 40);
  7208. const AMC_5 = getProtoFn(Game.AdventureMapCamera, 5);
  7209. const oldFunc = Game.AdventureMapCamera.prototype[AMC_40];
  7210. Game.AdventureMapCamera.prototype[AMC_40] = function (a) {
  7211. this[AMC_5] = 0.4;
  7212. oldFunc.bind(this)(a);
  7213. };
  7214. },
  7215. unlockMission: function () {
  7216. const WorldMapStoryDrommerHelper = selfGame['game.mediator.gui.worldmap.WorldMapStoryDrommerHelper'];
  7217. const WMSDH_4 = getFn(WorldMapStoryDrommerHelper, 4);
  7218. const WMSDH_7 = getFn(WorldMapStoryDrommerHelper, 7);
  7219. WorldMapStoryDrommerHelper[WMSDH_4] = function () {
  7220. return true;
  7221. };
  7222. WorldMapStoryDrommerHelper[WMSDH_7] = function () {
  7223. return true;
  7224. };
  7225. },
  7226. };
  7227.  
  7228. /**
  7229. * Starts replacing recorded functions
  7230. *
  7231. * Запускает замену записанных функций
  7232. */
  7233. this.activateHacks = function () {
  7234. if (!selfGame) throw Error('Use connectGame');
  7235. for (let func in replaceFunction) {
  7236. try {
  7237. replaceFunction[func]();
  7238. } catch (error) {
  7239. console.error(error);
  7240. }
  7241. }
  7242. }
  7243.  
  7244. /**
  7245. * Returns the game object
  7246. *
  7247. * Возвращает объект игры
  7248. */
  7249. this.getSelfGame = function () {
  7250. return selfGame;
  7251. }
  7252.  
  7253. /**
  7254. * Updates game data
  7255. *
  7256. * Обновляет данные игры
  7257. */
  7258. this.refreshGame = function () {
  7259. (new Game.NextDayUpdatedManager)[getProtoFn(Game.NextDayUpdatedManager, 5)]();
  7260. try {
  7261. cheats.refreshInventory();
  7262. } catch (e) { }
  7263. }
  7264.  
  7265. /**
  7266. * Update inventory
  7267. *
  7268. * Обновляет инвентарь
  7269. */
  7270. this.refreshInventory = async function () {
  7271. const GM_INST = getFnP(Game.GameModel, "get_instance");
  7272. const GM_0 = getProtoFn(Game.GameModel, 0);
  7273. const P_24 = getProtoFn(selfGame["game.model.user.Player"], 24);
  7274. const Player = Game.GameModel[GM_INST]()[GM_0];
  7275. Player[P_24] = new selfGame["game.model.user.inventory.PlayerInventory"]
  7276. Player[P_24].init(await Send({calls:[{name:"inventoryGet",args:{},ident:"body"}]}).then(e => e.results[0].result.response))
  7277. }
  7278. this.updateInventory = function (reward) {
  7279. const GM_INST = getFnP(Game.GameModel, 'get_instance');
  7280. const GM_0 = getProtoFn(Game.GameModel, 0);
  7281. const P_24 = getProtoFn(selfGame['game.model.user.Player'], 24);
  7282. const Player = Game.GameModel[GM_INST]()[GM_0];
  7283. Player[P_24].init(reward);
  7284. };
  7285.  
  7286. this.updateMap = function (data) {
  7287. const PCDD_21 = getProtoFn(selfGame['game.mechanics.clanDomination.model.PlayerClanDominationData'], 21);
  7288. const P_60 = getProtoFn(selfGame['game.model.user.Player'], 60);
  7289. const GM_0 = getProtoFn(Game.GameModel, 0);
  7290. const getInstance = getFnP(selfGame['Game'], 'get_instance');
  7291. const PlayerClanDominationData = Game.GameModel[getInstance]()[GM_0];
  7292. PlayerClanDominationData[P_60][PCDD_21].update(data);
  7293. };
  7294.  
  7295. /**
  7296. * Change the play screen on windowName
  7297. *
  7298. * Сменить экран игры на windowName
  7299. *
  7300. * Possible options:
  7301. *
  7302. * Возможные варианты:
  7303. *
  7304. * 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
  7305. */
  7306. this.goNavigtor = function (windowName) {
  7307. let mechanicStorage = selfGame["game.data.storage.mechanic.MechanicStorage"];
  7308. let window = mechanicStorage[windowName];
  7309. let event = new selfGame["game.mediator.gui.popup.PopupStashEventParams"];
  7310. let Game = selfGame['Game'];
  7311. let navigator = getF(Game, "get_navigator")
  7312. let navigate = getProtoFn(selfGame["game.screen.navigator.GameNavigator"], 20)
  7313. let instance = getFnP(Game, 'get_instance');
  7314. Game[instance]()[navigator]()[navigate](window, event);
  7315. }
  7316.  
  7317. /**
  7318. * Move to the sanctuary cheats.goSanctuary()
  7319. *
  7320. * Переместиться в святилище cheats.goSanctuary()
  7321. */
  7322. this.goSanctuary = () => {
  7323. this.goNavigtor("SANCTUARY");
  7324. }
  7325.  
  7326. /**
  7327. * Go to Guild War
  7328. *
  7329. * Перейти к Войне Гильдий
  7330. */
  7331. this.goClanWar = function() {
  7332. let instance = getFnP(Game.GameModel, 'get_instance')
  7333. let player = Game.GameModel[instance]().A;
  7334. let clanWarSelect = selfGame["game.mechanics.cross_clan_war.popup.selectMode.CrossClanWarSelectModeMediator"];
  7335. new clanWarSelect(player).open();
  7336. }
  7337.  
  7338. /**
  7339. * Go to BrawlShop
  7340. *
  7341. * Переместиться в BrawlShop
  7342. */
  7343. this.goBrawlShop = () => {
  7344. const instance = getFnP(Game.GameModel, 'get_instance')
  7345. const P_36 = getProtoFn(selfGame["game.model.user.Player"], 36);
  7346. const PSD_0 = getProtoFn(selfGame["game.model.user.shop.PlayerShopData"], 0);
  7347. const IM_0 = getProtoFn(selfGame["haxe.ds.IntMap"], 0);
  7348. const PSDE_4 = getProtoFn(selfGame["game.model.user.shop.PlayerShopDataEntry"], 4);
  7349.  
  7350. const player = Game.GameModel[instance]().A;
  7351. const shop = player[P_36][PSD_0][IM_0][1038][PSDE_4];
  7352. const shopPopup = new selfGame["game.mechanics.brawl.mediator.BrawlShopPopupMediator"](player, shop)
  7353. shopPopup.open(new selfGame["game.mediator.gui.popup.PopupStashEventParams"])
  7354. }
  7355.  
  7356. /**
  7357. * Returns all stores from game data
  7358. *
  7359. * Возвращает все магазины из данных игры
  7360. */
  7361. this.getShops = () => {
  7362. const instance = getFnP(Game.GameModel, 'get_instance')
  7363. const P_36 = getProtoFn(selfGame["game.model.user.Player"], 36);
  7364. const PSD_0 = getProtoFn(selfGame["game.model.user.shop.PlayerShopData"], 0);
  7365. const IM_0 = getProtoFn(selfGame["haxe.ds.IntMap"], 0);
  7366.  
  7367. const player = Game.GameModel[instance]().A;
  7368. return player[P_36][PSD_0][IM_0];
  7369. }
  7370.  
  7371. /**
  7372. * Returns the store from the game data by ID
  7373. *
  7374. * Возвращает магазин из данных игры по идетификатору
  7375. */
  7376. this.getShop = (id) => {
  7377. const PSDE_4 = getProtoFn(selfGame["game.model.user.shop.PlayerShopDataEntry"], 4);
  7378. const shops = this.getShops();
  7379. const shop = shops[id]?.[PSDE_4];
  7380. return shop;
  7381. }
  7382.  
  7383. /**
  7384. * Change island map
  7385. *
  7386. * Сменить карту острова
  7387. */
  7388. this.changeIslandMap = (mapId = 2) => {
  7389. const GameInst = getFnP(selfGame['Game'], 'get_instance');
  7390. const GM_0 = getProtoFn(Game.GameModel, 0);
  7391. const P_59 = getProtoFn(selfGame["game.model.user.Player"], 60);
  7392. const PSAD_31 = getProtoFn(selfGame['game.mechanics.season_adventure.model.PlayerSeasonAdventureData'], 31);
  7393. const Player = Game.GameModel[GameInst]()[GM_0];
  7394. Player[P_59][PSAD_31]({ id: mapId, seasonAdventure: { id: mapId, startDate: 1701914400, endDate: 1709690400, closed: false } });
  7395.  
  7396. const GN_15 = getProtoFn(selfGame["game.screen.navigator.GameNavigator"], 17)
  7397. const navigator = getF(selfGame['Game'], "get_navigator");
  7398. selfGame['Game'][GameInst]()[navigator]()[GN_15](new selfGame["game.mediator.gui.popup.PopupStashEventParams"]);
  7399. }
  7400.  
  7401. /**
  7402. * Game library availability tracker
  7403. *
  7404. * Отслеживание доступности игровой библиотеки
  7405. */
  7406. function checkLibLoad() {
  7407. timeout = setTimeout(() => {
  7408. if (Game.GameModel) {
  7409. changeLib();
  7410. } else {
  7411. checkLibLoad();
  7412. }
  7413. }, 100)
  7414. }
  7415.  
  7416. /**
  7417. * Game library data spoofing
  7418. *
  7419. * Подмена данных игровой библиотеки
  7420. */
  7421. function changeLib() {
  7422. console.log('lib connect');
  7423. const originalStartFunc = Game.GameModel.prototype.start;
  7424. Game.GameModel.prototype.start = function (a, b, c) {
  7425. self.libGame = b.raw;
  7426. self.doneLibLoad(self.libGame);
  7427. try {
  7428. const levels = b.raw.seasonAdventure.level;
  7429. for (const id in levels) {
  7430. const level = levels[id];
  7431. level.clientData.graphics.fogged = level.clientData.graphics.visible
  7432. }
  7433. const adv = b.raw.seasonAdventure.list[1];
  7434. adv.clientData.asset = 'dialog_season_adventure_tiles';
  7435. } catch (e) {
  7436. console.warn(e);
  7437. }
  7438. originalStartFunc.call(this, a, b, c);
  7439. }
  7440. }
  7441.  
  7442. this.LibLoad = function() {
  7443. return new Promise((e) => {
  7444. this.doneLibLoad = e;
  7445. });
  7446. }
  7447.  
  7448. /**
  7449. * Returns the value of a language constant
  7450. *
  7451. * Возвращает значение языковой константы
  7452. * @param {*} langConst language constant // языковая константа
  7453. * @returns
  7454. */
  7455. this.translate = function (langConst) {
  7456. return Game.Translate.translate(langConst);
  7457. }
  7458.  
  7459. connectGame();
  7460. checkLibLoad();
  7461. }
  7462.  
  7463. /**
  7464. * Auto collection of gifts
  7465. *
  7466. * Автосбор подарков
  7467. */
  7468. function getAutoGifts() {
  7469. // c3ltYm9scyB0aGF0IG1lYW4gbm90aGluZw==
  7470. let valName = 'giftSendIds_' + userInfo.id;
  7471.  
  7472. if (!localStorage['clearGift' + userInfo.id]) {
  7473. localStorage[valName] = '';
  7474. localStorage['clearGift' + userInfo.id] = '+';
  7475. }
  7476.  
  7477. if (!localStorage[valName]) {
  7478. localStorage[valName] = '';
  7479. }
  7480.  
  7481. const giftsAPI = new ZingerYWebsiteAPI('getGifts.php', arguments);
  7482. /**
  7483. * Submit a request to receive gift codes
  7484. *
  7485. * Отправка запроса для получения кодов подарков
  7486. */
  7487. giftsAPI.request().then((data) => {
  7488. let freebieCheckCalls = {
  7489. calls: [],
  7490. };
  7491. data.forEach((giftId, n) => {
  7492. if (localStorage[valName].includes(giftId)) return;
  7493. freebieCheckCalls.calls.push({
  7494. name: 'registration',
  7495. args: {
  7496. user: { referrer: {} },
  7497. giftId,
  7498. },
  7499. context: {
  7500. actionTs: Math.floor(performance.now()),
  7501. cookie: window?.NXAppInfo?.session_id || null,
  7502. },
  7503. ident: giftId,
  7504. });
  7505. });
  7506.  
  7507. if (!freebieCheckCalls.calls.length) {
  7508. return;
  7509. }
  7510.  
  7511. send(JSON.stringify(freebieCheckCalls), (e) => {
  7512. let countGetGifts = 0;
  7513. const gifts = [];
  7514. for (check of e.results) {
  7515. gifts.push(check.ident);
  7516. if (check.result.response != null) {
  7517. countGetGifts++;
  7518. }
  7519. }
  7520. const saveGifts = localStorage[valName].split(';');
  7521. localStorage[valName] = [...saveGifts, ...gifts].slice(-50).join(';');
  7522. console.log(`${I18N('GIFTS')}: ${countGetGifts}`);
  7523. });
  7524. });
  7525. }
  7526.  
  7527. /**
  7528. * To fill the kills in the Forge of Souls
  7529. *
  7530. * Набить килов в горниле душ
  7531. */
  7532. async function bossRatingEvent() {
  7533. const topGet = await Send(JSON.stringify({ calls: [{ name: "topGet", args: { type: "bossRatingTop", extraId: 0 }, ident: "body" }] }));
  7534. if (!topGet || !topGet.results[0].result.response[0]) {
  7535. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  7536. return;
  7537. }
  7538. const replayId = topGet.results[0].result.response[0].userData.replayId;
  7539. const result = await Send(JSON.stringify({
  7540. calls: [
  7541. { name: "battleGetReplay", args: { id: replayId }, ident: "battleGetReplay" },
  7542. { name: "heroGetAll", args: {}, ident: "heroGetAll" },
  7543. { name: "pet_getAll", args: {}, ident: "pet_getAll" },
  7544. { name: "offerGetAll", args: {}, ident: "offerGetAll" }
  7545. ]
  7546. }));
  7547. const bossEventInfo = result.results[3].result.response.find(e => e.offerType == "bossEvent");
  7548. if (!bossEventInfo) {
  7549. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  7550. return;
  7551. }
  7552. const usedHeroes = bossEventInfo.progress.usedHeroes;
  7553. const party = Object.values(result.results[0].result.response.replay.attackers);
  7554. const availableHeroes = Object.values(result.results[1].result.response).map(e => e.id);
  7555. const availablePets = Object.values(result.results[2].result.response).map(e => e.id);
  7556. const calls = [];
  7557. /**
  7558. * First pack
  7559. *
  7560. * Первая пачка
  7561. */
  7562. const args = {
  7563. heroes: [],
  7564. favor: {}
  7565. }
  7566. for (let hero of party) {
  7567. if (hero.id >= 6000 && availablePets.includes(hero.id)) {
  7568. args.pet = hero.id;
  7569. continue;
  7570. }
  7571. if (!availableHeroes.includes(hero.id) || usedHeroes.includes(hero.id)) {
  7572. continue;
  7573. }
  7574. args.heroes.push(hero.id);
  7575. if (hero.favorPetId) {
  7576. args.favor[hero.id] = hero.favorPetId;
  7577. }
  7578. }
  7579. if (args.heroes.length) {
  7580. calls.push({
  7581. name: "bossRatingEvent_startBattle",
  7582. args,
  7583. ident: "body_0"
  7584. });
  7585. }
  7586. /**
  7587. * Other packs
  7588. *
  7589. * Другие пачки
  7590. */
  7591. let heroes = [];
  7592. let count = 1;
  7593. while (heroId = availableHeroes.pop()) {
  7594. if (args.heroes.includes(heroId) || usedHeroes.includes(heroId)) {
  7595. continue;
  7596. }
  7597. heroes.push(heroId);
  7598. if (heroes.length == 5) {
  7599. calls.push({
  7600. name: "bossRatingEvent_startBattle",
  7601. args: {
  7602. heroes: [...heroes],
  7603. pet: availablePets[Math.floor(Math.random() * availablePets.length)]
  7604. },
  7605. ident: "body_" + count
  7606. });
  7607. heroes = [];
  7608. count++;
  7609. }
  7610. }
  7611.  
  7612. if (!calls.length) {
  7613. setProgress(`${I18N('NO_HEROES')}`, true);
  7614. return;
  7615. }
  7616.  
  7617. const resultBattles = await Send(JSON.stringify({ calls }));
  7618. console.log(resultBattles);
  7619. rewardBossRatingEvent();
  7620. }
  7621.  
  7622. /**
  7623. * Collecting Rewards from the Forge of Souls
  7624. *
  7625. * Сбор награды из Горнила Душ
  7626. */
  7627. function rewardBossRatingEvent() {
  7628. let rewardBossRatingCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  7629. send(rewardBossRatingCall, function (data) {
  7630. let bossEventInfo = data.results[0].result.response.find(e => e.offerType == "bossEvent");
  7631. if (!bossEventInfo) {
  7632. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  7633. return;
  7634. }
  7635.  
  7636. let farmedChests = bossEventInfo.progress.farmedChests;
  7637. let score = bossEventInfo.progress.score;
  7638. setProgress(`${I18N('DAMAGE_AMOUNT')}: ${score}`);
  7639. let revard = bossEventInfo.reward;
  7640.  
  7641. let getRewardCall = {
  7642. calls: []
  7643. }
  7644.  
  7645. let count = 0;
  7646. for (let i = 1; i < 10; i++) {
  7647. if (farmedChests.includes(i)) {
  7648. continue;
  7649. }
  7650. if (score < revard[i].score) {
  7651. break;
  7652. }
  7653. getRewardCall.calls.push({
  7654. name: "bossRatingEvent_getReward",
  7655. args: {
  7656. rewardId: i
  7657. },
  7658. ident: "body_" + i
  7659. });
  7660. count++;
  7661. }
  7662. if (!count) {
  7663. setProgress(`${I18N('NOTHING_TO_COLLECT')}`, true);
  7664. return;
  7665. }
  7666.  
  7667. send(JSON.stringify(getRewardCall), e => {
  7668. console.log(e);
  7669. setProgress(`${I18N('COLLECTED')} ${e?.results?.length} ${I18N('REWARD')}`, true);
  7670. });
  7671. });
  7672. }
  7673.  
  7674. /**
  7675. * Collect Easter eggs and event rewards
  7676. *
  7677. * Собрать пасхалки и награды событий
  7678. */
  7679. function offerFarmAllReward() {
  7680. const offerGetAllCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  7681. return Send(offerGetAllCall).then((data) => {
  7682. const offerGetAll = data.results[0].result.response.filter(e => e.type == "reward" && !e?.freeRewardObtained && e.reward);
  7683. if (!offerGetAll.length) {
  7684. setProgress(`${I18N('NOTHING_TO_COLLECT')}`, true);
  7685. return;
  7686. }
  7687.  
  7688. const calls = [];
  7689. for (let reward of offerGetAll) {
  7690. calls.push({
  7691. name: "offerFarmReward",
  7692. args: {
  7693. offerId: reward.id
  7694. },
  7695. ident: "offerFarmReward_" + reward.id
  7696. });
  7697. }
  7698.  
  7699. return Send(JSON.stringify({ calls })).then(e => {
  7700. console.log(e);
  7701. setProgress(`${I18N('COLLECTED')} ${e?.results?.length} ${I18N('REWARD')}`, true);
  7702. });
  7703. });
  7704. }
  7705.  
  7706. /**
  7707. * Assemble Outland
  7708. *
  7709. * Собрать запределье
  7710. */
  7711. function getOutland() {
  7712. return new Promise(function (resolve, reject) {
  7713. send('{"calls":[{"name":"bossGetAll","args":{},"ident":"bossGetAll"}]}', e => {
  7714. let bosses = e.results[0].result.response;
  7715.  
  7716. let bossRaidOpenChestCall = {
  7717. calls: []
  7718. };
  7719.  
  7720. for (let boss of bosses) {
  7721. if (boss.mayRaid) {
  7722. bossRaidOpenChestCall.calls.push({
  7723. name: "bossRaid",
  7724. args: {
  7725. bossId: boss.id
  7726. },
  7727. ident: "bossRaid_" + boss.id
  7728. });
  7729. bossRaidOpenChestCall.calls.push({
  7730. name: "bossOpenChest",
  7731. args: {
  7732. bossId: boss.id,
  7733. amount: 1,
  7734. starmoney: 0
  7735. },
  7736. ident: "bossOpenChest_" + boss.id
  7737. });
  7738. } else if (boss.chestId == 1) {
  7739. bossRaidOpenChestCall.calls.push({
  7740. name: "bossOpenChest",
  7741. args: {
  7742. bossId: boss.id,
  7743. amount: 1,
  7744. starmoney: 0
  7745. },
  7746. ident: "bossOpenChest_" + boss.id
  7747. });
  7748. }
  7749. }
  7750.  
  7751. if (!bossRaidOpenChestCall.calls.length) {
  7752. setProgress(`${I18N('OUTLAND')} ${I18N('NOTHING_TO_COLLECT')}`, true);
  7753. resolve();
  7754. return;
  7755. }
  7756.  
  7757. send(JSON.stringify(bossRaidOpenChestCall), e => {
  7758. setProgress(`${I18N('OUTLAND')} ${I18N('COLLECTED')}`, true);
  7759. resolve();
  7760. });
  7761. });
  7762. });
  7763. }
  7764.  
  7765. /**
  7766. * Collect all rewards
  7767. *
  7768. * Собрать все награды
  7769. */
  7770. function questAllFarm() {
  7771. return new Promise(function (resolve, reject) {
  7772. let questGetAllCall = {
  7773. calls: [{
  7774. name: "questGetAll",
  7775. args: {},
  7776. ident: "body"
  7777. }]
  7778. }
  7779. send(JSON.stringify(questGetAllCall), function (data) {
  7780. let questGetAll = data.results[0].result.response;
  7781. const questAllFarmCall = {
  7782. calls: []
  7783. }
  7784. let number = 0;
  7785. for (let quest of questGetAll) {
  7786. if (quest.id < 1e6 && quest.state == 2) {
  7787. questAllFarmCall.calls.push({
  7788. name: "questFarm",
  7789. args: {
  7790. questId: quest.id
  7791. },
  7792. ident: `group_${number}_body`
  7793. });
  7794. number++;
  7795. }
  7796. }
  7797.  
  7798. if (!questAllFarmCall.calls.length) {
  7799. setProgress(`${I18N('COLLECTED')} ${number} ${I18N('REWARD')}`, true);
  7800. resolve();
  7801. return;
  7802. }
  7803.  
  7804. send(JSON.stringify(questAllFarmCall), function (res) {
  7805. console.log(res);
  7806. setProgress(`${I18N('COLLECTED')} ${number} ${I18N('REWARD')}`, true);
  7807. resolve();
  7808. });
  7809. });
  7810. })
  7811. }
  7812.  
  7813. /**
  7814. * Mission auto repeat
  7815. *
  7816. * Автоповтор миссии
  7817. * isStopSendMission = false;
  7818. * isSendsMission = true;
  7819. **/
  7820. this.sendsMission = async function (param) {
  7821. if (isStopSendMission) {
  7822. isSendsMission = false;
  7823. console.log(I18N('STOPPED'));
  7824. setProgress('');
  7825. await popup.confirm(`${I18N('STOPPED')}<br>${I18N('REPETITIONS')}: ${param.count}`, [{
  7826. msg: 'Ok',
  7827. result: true
  7828. }, ])
  7829. return;
  7830. }
  7831. lastMissionBattleStart = Date.now();
  7832. let missionStartCall = {
  7833. "calls": [{
  7834. "name": "missionStart",
  7835. "args": lastMissionStart,
  7836. "ident": "body"
  7837. }]
  7838. }
  7839. /**
  7840. * Mission Request
  7841. *
  7842. * Запрос на выполнение мисии
  7843. */
  7844. SendRequest(JSON.stringify(missionStartCall), async e => {
  7845. if (e['error']) {
  7846. isSendsMission = false;
  7847. console.log(e['error']);
  7848. setProgress('');
  7849. let msg = e['error'].name + ' ' + e['error'].description + `<br>${I18N('REPETITIONS')}: ${param.count}`;
  7850. await popup.confirm(msg, [
  7851. {msg: 'Ok', result: true},
  7852. ])
  7853. return;
  7854. }
  7855. /**
  7856. * Mission data calculation
  7857. *
  7858. * Расчет данных мисии
  7859. */
  7860. BattleCalc(e.results[0].result.response, 'get_tower', async r => {
  7861. /** missionTimer */
  7862. let timer = getTimer(r.battleTime) + 5;
  7863. const period = Math.ceil((Date.now() - lastMissionBattleStart) / 1000);
  7864. if (period < timer) {
  7865. timer = timer - period;
  7866. await countdownTimer(timer, `${I18N('MISSIONS_PASSED')}: ${param.count}`);
  7867. }
  7868.  
  7869. let missionEndCall = {
  7870. "calls": [{
  7871. "name": "missionEnd",
  7872. "args": {
  7873. "id": param.id,
  7874. "result": r.result,
  7875. "progress": r.progress
  7876. },
  7877. "ident": "body"
  7878. }]
  7879. }
  7880. /**
  7881. * Mission Completion Request
  7882. *
  7883. * Запрос на завершение миссии
  7884. */
  7885. SendRequest(JSON.stringify(missionEndCall), async (e) => {
  7886. if (e['error']) {
  7887. isSendsMission = false;
  7888. console.log(e['error']);
  7889. setProgress('');
  7890. let msg = e['error'].name + ' ' + e['error'].description + `<br>${I18N('REPETITIONS')}: ${param.count}`;
  7891. await popup.confirm(msg, [
  7892. {msg: 'Ok', result: true},
  7893. ])
  7894. return;
  7895. }
  7896. r = e.results[0].result.response;
  7897. if (r['error']) {
  7898. isSendsMission = false;
  7899. console.log(r['error']);
  7900. setProgress('');
  7901. await popup.confirm(`<br>${I18N('REPETITIONS')}: ${param.count}` + ' 3 ' + r['error'], [
  7902. {msg: 'Ok', result: true},
  7903. ])
  7904. return;
  7905. }
  7906.  
  7907. param.count++;
  7908. setProgress(`${I18N('MISSIONS_PASSED')}: ${param.count} (${I18N('STOP')})`, false, () => {
  7909. isStopSendMission = true;
  7910. });
  7911. setTimeout(sendsMission, 1, param);
  7912. });
  7913. })
  7914. });
  7915. }
  7916.  
  7917. /**
  7918. * Opening of russian dolls
  7919. *
  7920. * Открытие матрешек
  7921. */
  7922. async function openRussianDolls(libId, amount) {
  7923. let sum = 0;
  7924. const sumResult = {};
  7925. let count = 0;
  7926.  
  7927. while (amount) {
  7928. sum += amount;
  7929. setProgress(`${I18N('TOTAL_OPEN')} ${sum}`);
  7930. const calls = [
  7931. {
  7932. name: 'consumableUseLootBox',
  7933. args: { libId, amount },
  7934. ident: 'body',
  7935. },
  7936. ];
  7937. const response = await Send(JSON.stringify({ calls })).then((e) => e.results[0].result.response);
  7938. let [countLootBox, result] = Object.entries(response).pop();
  7939. count += +countLootBox;
  7940. let newCount = 0;
  7941.  
  7942. if (result?.consumable && result.consumable[libId]) {
  7943. newCount = result.consumable[libId];
  7944. delete result.consumable[libId];
  7945. }
  7946.  
  7947. mergeItemsObj(sumResult, result);
  7948. amount = newCount;
  7949. }
  7950.  
  7951. setProgress(`${I18N('TOTAL_OPEN')} ${sum}`, 5000);
  7952. return [count, sumResult];
  7953. }
  7954.  
  7955. function mergeItemsObj(obj1, obj2) {
  7956. for (const key in obj2) {
  7957. if (obj1[key]) {
  7958. if (typeof obj1[key] == 'object') {
  7959. for (const innerKey in obj2[key]) {
  7960. obj1[key][innerKey] = (obj1[key][innerKey] || 0) + obj2[key][innerKey];
  7961. }
  7962. } else {
  7963. obj1[key] += obj2[key] || 0;
  7964. }
  7965. } else {
  7966. obj1[key] = obj2[key];
  7967. }
  7968. }
  7969.  
  7970. return obj1;
  7971. }
  7972.  
  7973. /**
  7974. * Collect all mail, except letters with energy and charges of the portal
  7975. *
  7976. * Собрать всю почту, кроме писем с энергией и зарядами портала
  7977. */
  7978. function mailGetAll() {
  7979. const getMailInfo = '{"calls":[{"name":"mailGetAll","args":{},"ident":"body"}]}';
  7980.  
  7981. return Send(getMailInfo).then(dataMail => {
  7982. const letters = dataMail.results[0].result.response.letters;
  7983. const letterIds = lettersFilter(letters);
  7984. if (!letterIds.length) {
  7985. setProgress(I18N('NOTHING_TO_COLLECT'), true);
  7986. return;
  7987. }
  7988.  
  7989. const calls = [
  7990. { name: "mailFarm", args: { letterIds }, ident: "body" }
  7991. ];
  7992.  
  7993. return Send(JSON.stringify({ calls })).then(res => {
  7994. const lettersIds = res.results[0].result.response;
  7995. if (lettersIds) {
  7996. const countLetters = Object.keys(lettersIds).length;
  7997. setProgress(`${I18N('RECEIVED')} ${countLetters} ${I18N('LETTERS')}`, true);
  7998. }
  7999. });
  8000. });
  8001. }
  8002.  
  8003. /**
  8004. * Filters received emails
  8005. *
  8006. * Фильтрует получаемые письма
  8007. */
  8008. function lettersFilter(letters) {
  8009. const lettersIds = [];
  8010. for (let l in letters) {
  8011. letter = letters[l];
  8012. const reward = letter?.reward;
  8013. if (!reward || !Object.keys(reward).length) {
  8014. continue;
  8015. }
  8016. /**
  8017. * Mail Collection Exceptions
  8018. *
  8019. * Исключения на сбор писем
  8020. */
  8021. const isFarmLetter = !(
  8022. /** Portals // сферы портала */
  8023. (reward?.refillable ? reward.refillable[45] : false) ||
  8024. /** Energy // энергия */
  8025. (reward?.stamina ? reward.stamina : false) ||
  8026. /** accelerating energy gain // ускорение набора энергии */
  8027. (reward?.buff ? true : false) ||
  8028. /** VIP Points // вип очки */
  8029. (reward?.vipPoints ? reward.vipPoints : false) ||
  8030. /** souls of heroes // душы героев */
  8031. (reward?.fragmentHero ? true : false) ||
  8032. /** heroes // герои */
  8033. (reward?.bundleHeroReward ? true : false)
  8034. );
  8035. if (isFarmLetter) {
  8036. lettersIds.push(~~letter.id);
  8037. continue;
  8038. }
  8039. /**
  8040. * Если до окончания годности письма менее 24 часов,
  8041. * то оно собирается не смотря на исключения
  8042. */
  8043. const availableUntil = +letter?.availableUntil;
  8044. if (availableUntil) {
  8045. const maxTimeLeft = 24 * 60 * 60 * 1000;
  8046. const timeLeft = (new Date(availableUntil * 1000) - new Date())
  8047. console.log('Time left:', timeLeft)
  8048. if (timeLeft < maxTimeLeft) {
  8049. lettersIds.push(~~letter.id);
  8050. continue;
  8051. }
  8052. }
  8053. }
  8054. return lettersIds;
  8055. }
  8056.  
  8057. /**
  8058. * Displaying information about the areas of the portal and attempts on the VG
  8059. *
  8060. * Отображение информации о сферах портала и попытках на ВГ
  8061. */
  8062. async function justInfo() {
  8063. return new Promise(async (resolve, reject) => {
  8064. const calls = [{
  8065. name: "userGetInfo",
  8066. args: {},
  8067. ident: "userGetInfo"
  8068. },
  8069. {
  8070. name: "clanWarGetInfo",
  8071. args: {},
  8072. ident: "clanWarGetInfo"
  8073. },
  8074. {
  8075. name: "titanArenaGetStatus",
  8076. args: {},
  8077. ident: "titanArenaGetStatus"
  8078. }];
  8079. const result = await Send(JSON.stringify({ calls }));
  8080. const infos = result.results;
  8081. const portalSphere = infos[0].result.response.refillable.find(n => n.id == 45);
  8082. const clanWarMyTries = infos[1].result.response?.myTries ?? 0;
  8083. const arePointsMax = infos[1].result.response?.arePointsMax;
  8084. const titansLevel = +(infos[2].result.response?.tier ?? 0);
  8085. const titansStatus = infos[2].result.response?.status; //peace_time || battle
  8086.  
  8087. const sanctuaryButton = buttons['goToSanctuary'].button;
  8088. const clanWarButton = buttons['goToClanWar'].button;
  8089. const titansArenaButton = buttons['testTitanArena'].button;
  8090.  
  8091. if (portalSphere.amount) {
  8092. sanctuaryButton.style.color = portalSphere.amount >= 3 ? 'red' : 'brown';
  8093. sanctuaryButton.title = `${I18N('SANCTUARY_TITLE')}\n${portalSphere.amount} ${I18N('PORTALS')}`;
  8094. } else {
  8095. sanctuaryButton.style.color = '';
  8096. sanctuaryButton.title = I18N('SANCTUARY_TITLE');
  8097. }
  8098. if (clanWarMyTries && !arePointsMax) {
  8099. clanWarButton.style.color = 'red';
  8100. clanWarButton.title = `${I18N('GUILD_WAR_TITLE')}\n${clanWarMyTries}${I18N('ATTEMPTS')}`;
  8101. } else {
  8102. clanWarButton.style.color = '';
  8103. clanWarButton.title = I18N('GUILD_WAR_TITLE');
  8104. }
  8105.  
  8106. if (titansLevel < 7 && titansStatus == 'battle') {
  8107. const partColor = Math.floor(125 * titansLevel / 7);
  8108. titansArenaButton.style.color = `rgb(255,${partColor},${partColor})`;
  8109. titansArenaButton.title = `${I18N('TITAN_ARENA_TITLE')}\n${titansLevel} ${I18N('LEVEL')}`;
  8110. } else {
  8111. titansArenaButton.style.color = '';
  8112. titansArenaButton.title = I18N('TITAN_ARENA_TITLE');
  8113. }
  8114.  
  8115. const imgPortal =
  8116. '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';
  8117.  
  8118. setProgress('<img src="' + imgPortal + '" style="height: 25px;position: relative;top: 5px;"> ' + `${portalSphere.amount} </br> ${I18N('GUILD_WAR')}: ${clanWarMyTries}`, true);
  8119. resolve();
  8120. });
  8121. }
  8122.  
  8123. async function getDailyBonus() {
  8124. const dailyBonusInfo = await Send(JSON.stringify({
  8125. calls: [{
  8126. name: "dailyBonusGetInfo",
  8127. args: {},
  8128. ident: "body"
  8129. }]
  8130. })).then(e => e.results[0].result.response);
  8131. const { availableToday, availableVip, currentDay } = dailyBonusInfo;
  8132.  
  8133. if (!availableToday) {
  8134. console.log('Уже собрано');
  8135. return;
  8136. }
  8137.  
  8138. const currentVipPoints = +userInfo.vipPoints;
  8139. const dailyBonusStat = lib.getData('dailyBonusStatic');
  8140. const vipInfo = lib.getData('level').vip;
  8141. let currentVipLevel = 0;
  8142. for (let i in vipInfo) {
  8143. vipLvl = vipInfo[i];
  8144. if (currentVipPoints >= vipLvl.vipPoints) {
  8145. currentVipLevel = vipLvl.level;
  8146. }
  8147. }
  8148. const vipLevelDouble = dailyBonusStat[`${currentDay}_0_0`].vipLevelDouble;
  8149.  
  8150. const calls = [{
  8151. name: "dailyBonusFarm",
  8152. args: {
  8153. vip: availableVip && currentVipLevel >= vipLevelDouble ? 1 : 0
  8154. },
  8155. ident: "body"
  8156. }];
  8157.  
  8158. const result = await Send(JSON.stringify({ calls }));
  8159. if (result.error) {
  8160. console.error(result.error);
  8161. return;
  8162. }
  8163.  
  8164. const reward = result.results[0].result.response;
  8165. const type = Object.keys(reward).pop();
  8166. const itemId = Object.keys(reward[type]).pop();
  8167. const count = reward[type][itemId];
  8168. const itemName = cheats.translate(`LIB_${type.toUpperCase()}_NAME_${itemId}`);
  8169.  
  8170. console.log(`Ежедневная награда: Получено ${count} ${itemName}`, reward);
  8171. }
  8172.  
  8173. async function farmStamina(lootBoxId = 148) {
  8174. const lootBox = await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"}]}')
  8175. .then(e => e.results[0].result.response.consumable[148]);
  8176.  
  8177. /** Добавить другие ящики */
  8178. /**
  8179. * 144 - медная шкатулка
  8180. * 145 - бронзовая шкатулка
  8181. * 148 - платиновая шкатулка
  8182. */
  8183. if (!lootBox) {
  8184. setProgress(I18N('NO_BOXES'), true);
  8185. return;
  8186. }
  8187.  
  8188. let maxFarmEnergy = getSaveVal('maxFarmEnergy', 100);
  8189. const result = await popup.confirm(I18N('OPEN_LOOTBOX', { lootBox }), [
  8190. { result: false, isClose: true },
  8191. { msg: I18N('BTN_YES'), result: true },
  8192. { msg: I18N('STAMINA'), isInput: true, default: maxFarmEnergy },
  8193. ]);
  8194. if (!+result) {
  8195. return;
  8196. }
  8197.  
  8198. if ((typeof result) !== 'boolean' && Number.parseInt(result)) {
  8199. maxFarmEnergy = +result;
  8200. setSaveVal('maxFarmEnergy', maxFarmEnergy);
  8201. } else {
  8202. maxFarmEnergy = 0;
  8203. }
  8204.  
  8205. let collectEnergy = 0;
  8206. for (let count = lootBox; count > 0; count--) {
  8207. const response = await Send('{"calls":[{"name":"consumableUseLootBox","args":{"libId":148,"amount":1},"ident":"body"}]}').then(
  8208. (e) => e.results[0].result.response
  8209. );
  8210. const result = Object.values(response).pop();
  8211. if ('stamina' in result) {
  8212. setProgress(`${I18N('OPEN')}: ${lootBox - count}/${lootBox} ${I18N('STAMINA')} +${result.stamina}<br>${I18N('STAMINA')}: ${collectEnergy}`, false);
  8213. console.log(`${ I18N('STAMINA') } + ${ result.stamina }`);
  8214. if (!maxFarmEnergy) {
  8215. return;
  8216. }
  8217. collectEnergy += +result.stamina;
  8218. if (collectEnergy >= maxFarmEnergy) {
  8219. console.log(`${I18N('STAMINA')} + ${ collectEnergy }`);
  8220. setProgress(`${I18N('STAMINA')} + ${ collectEnergy }`, false);
  8221. return;
  8222. }
  8223. } else {
  8224. setProgress(`${I18N('OPEN')}: ${lootBox - count}/${lootBox}<br>${I18N('STAMINA')}: ${collectEnergy}`, false);
  8225. console.log(result);
  8226. }
  8227. }
  8228.  
  8229. setProgress(I18N('BOXES_OVER'), true);
  8230. }
  8231.  
  8232. async function fillActive() {
  8233. const data = await Send(JSON.stringify({
  8234. calls: [{
  8235. name: "questGetAll",
  8236. args: {},
  8237. ident: "questGetAll"
  8238. }, {
  8239. name: "inventoryGet",
  8240. args: {},
  8241. ident: "inventoryGet"
  8242. }, {
  8243. name: "clanGetInfo",
  8244. args: {},
  8245. ident: "clanGetInfo"
  8246. }
  8247. ]
  8248. })).then(e => e.results.map(n => n.result.response));
  8249.  
  8250. const quests = data[0];
  8251. const inv = data[1];
  8252. const stat = data[2].stat;
  8253. const maxActive = 2000 - stat.todayItemsActivity;
  8254. if (maxActive <= 0) {
  8255. setProgress(I18N('NO_MORE_ACTIVITY'), true);
  8256. return;
  8257. }
  8258. let countGetActive = 0;
  8259. const quest = quests.find(e => e.id > 10046 && e.id < 10051);
  8260. if (quest) {
  8261. countGetActive = 1750 - quest.progress;
  8262. }
  8263. if (countGetActive <= 0) {
  8264. countGetActive = maxActive;
  8265. }
  8266. console.log(countGetActive);
  8267.  
  8268. countGetActive = +(await popup.confirm(I18N('EXCHANGE_ITEMS', { maxActive }), [
  8269. { result: false, isClose: true },
  8270. { msg: I18N('GET_ACTIVITY'), isInput: true, default: countGetActive.toString() },
  8271. ]));
  8272.  
  8273. if (!countGetActive) {
  8274. return;
  8275. }
  8276.  
  8277. if (countGetActive > maxActive) {
  8278. countGetActive = maxActive;
  8279. }
  8280.  
  8281. const items = lib.getData('inventoryItem');
  8282.  
  8283. let itemsInfo = [];
  8284. for (let type of ['gear', 'scroll']) {
  8285. for (let i in inv[type]) {
  8286. const v = items[type][i]?.enchantValue || 0;
  8287. itemsInfo.push({
  8288. id: i,
  8289. count: inv[type][i],
  8290. v,
  8291. type
  8292. })
  8293. }
  8294. const invType = 'fragment' + type.toLowerCase().charAt(0).toUpperCase() + type.slice(1);
  8295. for (let i in inv[invType]) {
  8296. const v = items[type][i]?.fragmentEnchantValue || 0;
  8297. itemsInfo.push({
  8298. id: i,
  8299. count: inv[invType][i],
  8300. v,
  8301. type: invType
  8302. })
  8303. }
  8304. }
  8305. itemsInfo = itemsInfo.filter(e => e.v < 4 && e.count > 200);
  8306. itemsInfo = itemsInfo.sort((a, b) => b.count - a.count);
  8307. console.log(itemsInfo);
  8308. const activeItem = itemsInfo.shift();
  8309. console.log(activeItem);
  8310. const countItem = Math.ceil(countGetActive / activeItem.v);
  8311. if (countItem > activeItem.count) {
  8312. setProgress(I18N('NOT_ENOUGH_ITEMS'), true);
  8313. console.log(activeItem);
  8314. return;
  8315. }
  8316.  
  8317. await Send(JSON.stringify({
  8318. calls: [{
  8319. name: "clanItemsForActivity",
  8320. args: {
  8321. items: {
  8322. [activeItem.type]: {
  8323. [activeItem.id]: countItem
  8324. }
  8325. }
  8326. },
  8327. ident: "body"
  8328. }]
  8329. })).then(e => {
  8330. /** TODO: Вывести потраченые предметы */
  8331. console.log(e);
  8332. setProgress(`${I18N('ACTIVITY_RECEIVED')}: ` + e.results[0].result.response, true);
  8333. });
  8334. }
  8335.  
  8336. async function buyHeroFragments() {
  8337. const result = await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"},{"name":"shopGetAll","args":{},"ident":"shopGetAll"}]}')
  8338. .then(e => e.results.map(n => n.result.response));
  8339. const inv = result[0];
  8340. const shops = Object.values(result[1]).filter(shop => [4, 5, 6, 8, 9, 10, 17].includes(shop.id));
  8341. const calls = [];
  8342.  
  8343. for (let shop of shops) {
  8344. const slots = Object.values(shop.slots);
  8345. for (const slot of slots) {
  8346. /* Уже куплено */
  8347. if (slot.bought) {
  8348. continue;
  8349. }
  8350. /* Не душа героя */
  8351. if (!('fragmentHero' in slot.reward)) {
  8352. continue;
  8353. }
  8354. const coin = Object.keys(slot.cost).pop();
  8355. const coinId = Object.keys(slot.cost[coin]).pop();
  8356. const stock = inv[coin][coinId] || 0;
  8357. /* Не хватает на покупку */
  8358. if (slot.cost[coin][coinId] > stock) {
  8359. continue;
  8360. }
  8361. inv[coin][coinId] -= slot.cost[coin][coinId];
  8362. calls.push({
  8363. name: "shopBuy",
  8364. args: {
  8365. shopId: shop.id,
  8366. slot: slot.id,
  8367. cost: slot.cost,
  8368. reward: slot.reward,
  8369. },
  8370. ident: `shopBuy_${shop.id}_${slot.id}`,
  8371. })
  8372. }
  8373. }
  8374.  
  8375. if (!calls.length) {
  8376. setProgress(I18N('NO_PURCHASABLE_HERO_SOULS'), true);
  8377. return;
  8378. }
  8379.  
  8380. const bought = await Send(JSON.stringify({ calls })).then(e => e.results.map(n => n.result.response));
  8381. if (!bought) {
  8382. console.log('что-то пошло не так')
  8383. return;
  8384. }
  8385.  
  8386. let countHeroSouls = 0;
  8387. for (const buy of bought) {
  8388. countHeroSouls += +Object.values(Object.values(buy).pop()).pop();
  8389. }
  8390. console.log(countHeroSouls, bought, calls);
  8391. setProgress(I18N('PURCHASED_HERO_SOULS', { countHeroSouls }), true);
  8392. }
  8393.  
  8394. /** Открыть платные сундуки в Запределье за 90 */
  8395. async function bossOpenChestPay() {
  8396. const callsNames = ['userGetInfo', 'bossGetAll', 'specialOffer_getAll', 'getTime'];
  8397. const info = await Send({ calls: callsNames.map((name) => ({ name, args: {}, ident: name })) }).then((e) =>
  8398. e.results.map((n) => n.result.response)
  8399. );
  8400.  
  8401. const user = info[0];
  8402. const boses = info[1];
  8403. const offers = info[2];
  8404. const time = info[3];
  8405.  
  8406. const discountOffer = offers.find((e) => e.offerType == 'costReplaceOutlandChest');
  8407.  
  8408. let discount = 1;
  8409. if (discountOffer && discountOffer.endTime > time) {
  8410. discount = 1 - discountOffer.offerData.outlandChest.discountPercent / 100;
  8411. }
  8412.  
  8413. cost9chests = 540 * discount;
  8414. cost18chests = 1740 * discount;
  8415. costFirstChest = 90 * discount;
  8416. costSecondChest = 200 * discount;
  8417.  
  8418. const currentStarMoney = user.starMoney;
  8419. if (currentStarMoney < cost9chests) {
  8420. setProgress('Недостаточно изюма, нужно ' + cost9chests + ' у Вас ' + currentStarMoney, true);
  8421. return;
  8422. }
  8423.  
  8424. const imgEmerald =
  8425. "<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='>";
  8426.  
  8427. if (currentStarMoney < cost9chests) {
  8428. setProgress(I18N('NOT_ENOUGH_EMERALDS_540', { currentStarMoney, imgEmerald }), true);
  8429. return;
  8430. }
  8431.  
  8432. const buttons = [{ result: false, isClose: true }];
  8433.  
  8434. if (currentStarMoney >= cost9chests) {
  8435. buttons.push({
  8436. msg: I18N('BUY_OUTLAND_BTN', { count: 9, countEmerald: cost9chests, imgEmerald }),
  8437. result: [costFirstChest, costFirstChest, 0],
  8438. });
  8439. }
  8440.  
  8441. if (currentStarMoney >= cost18chests) {
  8442. buttons.push({
  8443. msg: I18N('BUY_OUTLAND_BTN', { count: 18, countEmerald: cost18chests, imgEmerald }),
  8444. result: [costFirstChest, costFirstChest, 0, costSecondChest, costSecondChest, 0],
  8445. });
  8446. }
  8447.  
  8448. const answer = await popup.confirm(`<div style="margin-bottom: 15px;">${I18N('BUY_OUTLAND')}</div>`, buttons);
  8449.  
  8450. if (!answer) {
  8451. return;
  8452. }
  8453.  
  8454. const callBoss = [];
  8455. let n = 0;
  8456. for (let boss of boses) {
  8457. const bossId = boss.id;
  8458. if (boss.chestNum != 2) {
  8459. continue;
  8460. }
  8461. const calls = [];
  8462. for (const starmoney of answer) {
  8463. calls.push({
  8464. name: 'bossOpenChest',
  8465. args: {
  8466. amount: 1,
  8467. bossId,
  8468. starmoney,
  8469. },
  8470. ident: 'bossOpenChest_' + ++n,
  8471. });
  8472. }
  8473. callBoss.push(calls);
  8474. }
  8475.  
  8476. if (!callBoss.length) {
  8477. setProgress(I18N('CHESTS_NOT_AVAILABLE'), true);
  8478. return;
  8479. }
  8480.  
  8481. let count = 0;
  8482. let errors = 0;
  8483. for (const calls of callBoss) {
  8484. const result = await Send({ calls });
  8485. console.log(result);
  8486. if (result?.results) {
  8487. count += result.results.length;
  8488. } else {
  8489. errors++;
  8490. }
  8491. }
  8492.  
  8493. setProgress(`${I18N('OUTLAND_CHESTS_RECEIVED')}: ${count}`, true);
  8494. }
  8495.  
  8496. async function autoRaidAdventure() {
  8497. const calls = [
  8498. {
  8499. name: "userGetInfo",
  8500. args: {},
  8501. ident: "userGetInfo"
  8502. },
  8503. {
  8504. name: "adventure_raidGetInfo",
  8505. args: {},
  8506. ident: "adventure_raidGetInfo"
  8507. }
  8508. ];
  8509. const result = await Send(JSON.stringify({ calls }))
  8510. .then(e => e.results.map(n => n.result.response));
  8511.  
  8512. const portalSphere = result[0].refillable.find(n => n.id == 45);
  8513. const adventureRaid = Object.entries(result[1].raid).filter(e => e[1]).pop()
  8514. const adventureId = adventureRaid ? adventureRaid[0] : 0;
  8515.  
  8516. if (!portalSphere.amount || !adventureId) {
  8517. setProgress(I18N('RAID_NOT_AVAILABLE'), true);
  8518. return;
  8519. }
  8520.  
  8521. const countRaid = +(await popup.confirm(I18N('RAID_ADVENTURE', { adventureId }), [
  8522. { result: false, isClose: true },
  8523. { msg: I18N('RAID'), isInput: true, default: portalSphere.amount },
  8524. ]));
  8525.  
  8526. if (!countRaid) {
  8527. return;
  8528. }
  8529.  
  8530. if (countRaid > portalSphere.amount) {
  8531. countRaid = portalSphere.amount;
  8532. }
  8533.  
  8534. const resultRaid = await Send(JSON.stringify({
  8535. calls: [...Array(countRaid)].map((e, i) => ({
  8536. name: "adventure_raid",
  8537. args: {
  8538. adventureId
  8539. },
  8540. ident: `body_${i}`
  8541. }))
  8542. })).then(e => e.results.map(n => n.result.response));
  8543.  
  8544. if (!resultRaid.length) {
  8545. console.log(resultRaid);
  8546. setProgress(I18N('SOMETHING_WENT_WRONG'), true);
  8547. return;
  8548. }
  8549.  
  8550. console.log(resultRaid, adventureId, portalSphere.amount);
  8551. setProgress(I18N('ADVENTURE_COMPLETED', { adventureId, times: resultRaid.length }), true);
  8552. }
  8553.  
  8554. /** Вывести всю клановую статистику в консоль браузера */
  8555. async function clanStatistic() {
  8556. const copy = function (text) {
  8557. const copyTextarea = document.createElement("textarea");
  8558. copyTextarea.style.opacity = "0";
  8559. copyTextarea.textContent = text;
  8560. document.body.appendChild(copyTextarea);
  8561. copyTextarea.select();
  8562. document.execCommand("copy");
  8563. document.body.removeChild(copyTextarea);
  8564. delete copyTextarea;
  8565. }
  8566. const calls = [
  8567. { name: "clanGetInfo", args: {}, ident: "clanGetInfo" },
  8568. { name: "clanGetWeeklyStat", args: {}, ident: "clanGetWeeklyStat" },
  8569. { name: "clanGetLog", args: {}, ident: "clanGetLog" },
  8570. ];
  8571.  
  8572. const result = await Send(JSON.stringify({ calls }));
  8573.  
  8574. const dataClanInfo = result.results[0].result.response;
  8575. const dataClanStat = result.results[1].result.response;
  8576. const dataClanLog = result.results[2].result.response;
  8577.  
  8578. const membersStat = {};
  8579. for (let i = 0; i < dataClanStat.stat.length; i++) {
  8580. membersStat[dataClanStat.stat[i].id] = dataClanStat.stat[i];
  8581. }
  8582.  
  8583. const joinStat = {};
  8584. historyLog = dataClanLog.history;
  8585. for (let j in historyLog) {
  8586. his = historyLog[j];
  8587. if (his.event == 'join') {
  8588. joinStat[his.userId] = his.ctime;
  8589. }
  8590. }
  8591.  
  8592. const infoArr = [];
  8593. const members = dataClanInfo.clan.members;
  8594. for (let n in members) {
  8595. var member = [
  8596. n,
  8597. members[n].name,
  8598. members[n].level,
  8599. dataClanInfo.clan.warriors.includes(+n) ? 1 : 0,
  8600. (new Date(members[n].lastLoginTime * 1000)).toLocaleString().replace(',', ''),
  8601. joinStat[n] ? (new Date(joinStat[n] * 1000)).toLocaleString().replace(',', '') : '',
  8602. membersStat[n].activity.reverse().join('\t'),
  8603. membersStat[n].adventureStat.reverse().join('\t'),
  8604. membersStat[n].clanGifts.reverse().join('\t'),
  8605. membersStat[n].clanWarStat.reverse().join('\t'),
  8606. membersStat[n].dungeonActivity.reverse().join('\t'),
  8607. ];
  8608. infoArr.push(member);
  8609. }
  8610. const info = infoArr.sort((a, b) => (b[2] - a[2])).map((e) => e.join('\t')).join('\n');
  8611. console.log(info);
  8612. copy(info);
  8613. setProgress(I18N('CLAN_STAT_COPY'), true);
  8614. }
  8615.  
  8616. async function buyInStoreForGold() {
  8617. const result = await Send('{"calls":[{"name":"shopGetAll","args":{},"ident":"body"},{"name":"userGetInfo","args":{},"ident":"userGetInfo"}]}').then(e => e.results.map(n => n.result.response));
  8618. const shops = result[0];
  8619. const user = result[1];
  8620. let gold = user.gold;
  8621. const calls = [];
  8622. if (shops[17]) {
  8623. const slots = shops[17].slots;
  8624. for (let i = 1; i <= 2; i++) {
  8625. if (!slots[i].bought) {
  8626. const costGold = slots[i].cost.gold;
  8627. if ((gold - costGold) < 0) {
  8628. continue;
  8629. }
  8630. gold -= costGold;
  8631. calls.push({
  8632. name: "shopBuy",
  8633. args: {
  8634. shopId: 17,
  8635. slot: i,
  8636. cost: slots[i].cost,
  8637. reward: slots[i].reward,
  8638. },
  8639. ident: 'body_' + i,
  8640. })
  8641. }
  8642. }
  8643. }
  8644. const slots = shops[1].slots;
  8645. for (let i = 4; i <= 6; i++) {
  8646. if (!slots[i].bought && slots[i]?.cost?.gold) {
  8647. const costGold = slots[i].cost.gold;
  8648. if ((gold - costGold) < 0) {
  8649. continue;
  8650. }
  8651. gold -= costGold;
  8652. calls.push({
  8653. name: "shopBuy",
  8654. args: {
  8655. shopId: 1,
  8656. slot: i,
  8657. cost: slots[i].cost,
  8658. reward: slots[i].reward,
  8659. },
  8660. ident: 'body_' + i,
  8661. })
  8662. }
  8663. }
  8664.  
  8665. if (!calls.length) {
  8666. setProgress(I18N('NOTHING_BUY'), true);
  8667. return;
  8668. }
  8669.  
  8670. const resultBuy = await Send(JSON.stringify({ calls })).then(e => e.results.map(n => n.result.response));
  8671. console.log(resultBuy);
  8672. const countBuy = resultBuy.length;
  8673. setProgress(I18N('LOTS_BOUGHT', { countBuy }), true);
  8674. }
  8675.  
  8676. function rewardsAndMailFarm() {
  8677. return new Promise(function (resolve, reject) {
  8678. let questGetAllCall = {
  8679. calls: [{
  8680. name: "questGetAll",
  8681. args: {},
  8682. ident: "questGetAll"
  8683. }, {
  8684. name: "mailGetAll",
  8685. args: {},
  8686. ident: "mailGetAll"
  8687. }]
  8688. }
  8689. send(JSON.stringify(questGetAllCall), function (data) {
  8690. if (!data) return;
  8691. const questGetAll = data.results[0].result.response.filter((e) => e.state == 2);
  8692. const questBattlePass = lib.getData('quest').battlePass;
  8693. const questChainBPass = lib.getData('battlePass').questChain;
  8694. const listBattlePass = lib.getData('battlePass').list;
  8695.  
  8696. const questAllFarmCall = {
  8697. calls: [],
  8698. };
  8699. const questIds = [];
  8700. for (let quest of questGetAll) {
  8701. if (quest.id >= 2001e4) {
  8702. continue;
  8703. }
  8704. if (quest.id > 1e6 && quest.id < 2e7) {
  8705. const questInfo = questBattlePass[quest.id];
  8706. const chain = questChainBPass[questInfo.chain];
  8707. if (chain.requirement?.battlePassTicket) {
  8708. continue;
  8709. }
  8710. const battlePass = listBattlePass[chain.battlePass];
  8711. const startTime = battlePass.startCondition.time.value * 1e3
  8712. const endTime = new Date(startTime + battlePass.duration * 1e3);
  8713. if (startTime > Date.now() || endTime < Date.now()) {
  8714. continue;
  8715. }
  8716. }
  8717. if (quest.id >= 2e7) {
  8718. questIds.push(quest.id);
  8719. continue;
  8720. }
  8721. questAllFarmCall.calls.push({
  8722. name: 'questFarm',
  8723. args: {
  8724. questId: quest.id,
  8725. },
  8726. ident: `questFarm_${quest.id}`,
  8727. });
  8728. }
  8729.  
  8730. if (questIds.length) {
  8731. questAllFarmCall.calls.push({
  8732. name: 'quest_questsFarm',
  8733. args: { questIds },
  8734. ident: 'quest_questsFarm',
  8735. });
  8736. }
  8737.  
  8738. let letters = data?.results[1]?.result?.response?.letters;
  8739. letterIds = lettersFilter(letters);
  8740.  
  8741. if (letterIds.length) {
  8742. questAllFarmCall.calls.push({
  8743. name: 'mailFarm',
  8744. args: { letterIds },
  8745. ident: 'mailFarm',
  8746. });
  8747. }
  8748.  
  8749. if (!questAllFarmCall.calls.length) {
  8750. setProgress(I18N('NOTHING_TO_COLLECT'), true);
  8751. resolve();
  8752. return;
  8753. }
  8754.  
  8755. send(JSON.stringify(questAllFarmCall), async function (res) {
  8756. let countQuests = 0;
  8757. let countMail = 0;
  8758. let questsIds = [];
  8759. for (let call of res.results) {
  8760. if (call.ident.includes('questFarm')) {
  8761. countQuests++;
  8762. } else if (call.ident.includes('questsFarm')) {
  8763. countQuests += Object.keys(call.result.response).length;
  8764. } else if (call.ident.includes('mailFarm')) {
  8765. countMail = Object.keys(call.result.response).length;
  8766. }
  8767.  
  8768. const newQuests = call.result.newQuests;
  8769. if (newQuests) {
  8770. for (let quest of newQuests) {
  8771. if ((quest.id < 1e6 || (quest.id >= 2e7 && quest.id < 2001e4)) && quest.state == 2) {
  8772. questsIds.push(quest.id);
  8773. }
  8774. }
  8775. }
  8776. }
  8777.  
  8778. while (questsIds.length) {
  8779. const questIds = [];
  8780. const calls = [];
  8781. for (let questId of questsIds) {
  8782. if (questId < 1e6) {
  8783. calls.push({
  8784. name: 'questFarm',
  8785. args: {
  8786. questId,
  8787. },
  8788. ident: `questFarm_${questId}`,
  8789. });
  8790. countQuests++;
  8791. } else if (questId >= 2e7 && questId < 2001e4) {
  8792. questIds.push(questId);
  8793. countQuests++;
  8794. }
  8795. }
  8796. calls.push({
  8797. name: 'quest_questsFarm',
  8798. args: { questIds },
  8799. ident: 'body',
  8800. });
  8801. const results = await Send({ calls }).then((e) => e.results.map((e) => e.result));
  8802. questsIds = [];
  8803. for (const result of results) {
  8804. const newQuests = result.newQuests;
  8805. if (newQuests) {
  8806. for (let quest of newQuests) {
  8807. if (quest.state == 2) {
  8808. questsIds.push(quest.id);
  8809. }
  8810. }
  8811. }
  8812. }
  8813. }
  8814.  
  8815. setProgress(I18N('COLLECT_REWARDS_AND_MAIL', { countQuests, countMail }), true);
  8816. resolve();
  8817. });
  8818. });
  8819. })
  8820. }
  8821.  
  8822. class epicBrawl {
  8823. timeout = null;
  8824. time = null;
  8825.  
  8826. constructor() {
  8827. if (epicBrawl.inst) {
  8828. return epicBrawl.inst;
  8829. }
  8830. epicBrawl.inst = this;
  8831. return this;
  8832. }
  8833.  
  8834. runTimeout(func, timeDiff) {
  8835. const worker = new Worker(URL.createObjectURL(new Blob([`
  8836. self.onmessage = function(e) {
  8837. const timeDiff = e.data;
  8838.  
  8839. if (timeDiff > 0) {
  8840. setTimeout(() => {
  8841. self.postMessage(1);
  8842. self.close();
  8843. }, timeDiff);
  8844. }
  8845. };
  8846. `])));
  8847. worker.postMessage(timeDiff);
  8848. worker.onmessage = () => {
  8849. func();
  8850. };
  8851. return true;
  8852. }
  8853.  
  8854. timeDiff(date1, date2) {
  8855. const date1Obj = new Date(date1);
  8856. const date2Obj = new Date(date2);
  8857.  
  8858. const timeDiff = Math.abs(date2Obj - date1Obj);
  8859.  
  8860. const totalSeconds = timeDiff / 1000;
  8861. const minutes = Math.floor(totalSeconds / 60);
  8862. const seconds = Math.floor(totalSeconds % 60);
  8863.  
  8864. const formattedMinutes = String(minutes).padStart(2, '0');
  8865. const formattedSeconds = String(seconds).padStart(2, '0');
  8866.  
  8867. return `${formattedMinutes}:${formattedSeconds}`;
  8868. }
  8869.  
  8870. check() {
  8871. console.log(new Date(this.time))
  8872. if (Date.now() > this.time) {
  8873. this.timeout = null;
  8874. this.start()
  8875. return;
  8876. }
  8877. this.timeout = this.runTimeout(() => this.check(), 6e4);
  8878. return this.timeDiff(this.time, Date.now())
  8879. }
  8880.  
  8881. async start() {
  8882. if (this.timeout) {
  8883. const time = this.timeDiff(this.time, Date.now());
  8884. console.log(new Date(this.time))
  8885. setProgress(I18N('TIMER_ALREADY', { time }), false, hideProgress);
  8886. return;
  8887. }
  8888. setProgress(I18N('EPIC_BRAWL'), false, hideProgress);
  8889. 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));
  8890. const refill = teamInfo[2].refillable.find(n => n.id == 52)
  8891. this.time = (refill.lastRefill + 3600) * 1000
  8892. const attempts = refill.amount;
  8893. if (!attempts) {
  8894. console.log(new Date(this.time));
  8895. const time = this.check();
  8896. setProgress(I18N('NO_ATTEMPTS_TIMER_START', { time }), false, hideProgress);
  8897. return;
  8898. }
  8899.  
  8900. if (!teamInfo[0].epic_brawl) {
  8901. setProgress(I18N('NO_HEROES_PACK'), false, hideProgress);
  8902. return;
  8903. }
  8904.  
  8905. const args = {
  8906. heroes: teamInfo[0].epic_brawl.filter(e => e < 1000),
  8907. pet: teamInfo[0].epic_brawl.filter(e => e > 6000).pop(),
  8908. favor: teamInfo[1].epic_brawl,
  8909. }
  8910.  
  8911. let wins = 0;
  8912. let coins = 0;
  8913. let streak = { progress: 0, nextStage: 0 };
  8914. for (let i = attempts; i > 0; i--) {
  8915. const info = await Send(JSON.stringify({
  8916. calls: [
  8917. { name: "epicBrawl_getEnemy", args: {}, ident: "epicBrawl_getEnemy" }, { name: "epicBrawl_startBattle", args, ident: "epicBrawl_startBattle" }
  8918. ]
  8919. })).then(e => e.results.map(n => n.result.response));
  8920.  
  8921. const { progress, result } = await Calc(info[1].battle);
  8922. 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));
  8923.  
  8924. const resultInfo = endResult[0].result;
  8925. streak = endResult[1];
  8926.  
  8927. wins += resultInfo.win;
  8928. coins += resultInfo.reward ? resultInfo.reward.coin[39] : 0;
  8929.  
  8930. console.log(endResult[0].result)
  8931. if (endResult[1].progress == endResult[1].nextStage) {
  8932. const farm = await Send('{"calls":[{"name":"epicBrawl_farmWinStreak","args":{},"ident":"body"}]}').then(e => e.results[0].result.response);
  8933. coins += farm.coin[39];
  8934. }
  8935.  
  8936. setProgress(I18N('EPIC_BRAWL_RESULT', {
  8937. i, wins, attempts, coins,
  8938. progress: streak.progress,
  8939. nextStage: streak.nextStage,
  8940. end: '',
  8941. }), false, hideProgress);
  8942. }
  8943.  
  8944. console.log(new Date(this.time));
  8945. const time = this.check();
  8946. setProgress(I18N('EPIC_BRAWL_RESULT', {
  8947. wins, attempts, coins,
  8948. i: '',
  8949. progress: streak.progress,
  8950. nextStage: streak.nextStage,
  8951. end: I18N('ATTEMPT_ENDED', { time }),
  8952. }), false, hideProgress);
  8953. }
  8954. }
  8955.  
  8956. function countdownTimer(seconds, message) {
  8957. message = message || I18N('TIMER');
  8958. const stopTimer = Date.now() + seconds * 1e3
  8959. return new Promise(resolve => {
  8960. const interval = setInterval(async () => {
  8961. const now = Date.now();
  8962. setProgress(`${message} ${((stopTimer - now) / 1000).toFixed(2)}`, false);
  8963. if (now > stopTimer) {
  8964. clearInterval(interval);
  8965. setProgress('', 1);
  8966. resolve();
  8967. }
  8968. }, 100);
  8969. });
  8970. }
  8971.  
  8972. this.HWHFuncs.countdownTimer = countdownTimer;
  8973.  
  8974. /** Набить килов в горниле душк */
  8975. async function bossRatingEventSouls() {
  8976. const data = await Send({
  8977. calls: [
  8978. { name: "heroGetAll", args: {}, ident: "teamGetAll" },
  8979. { name: "offerGetAll", args: {}, ident: "offerGetAll" },
  8980. { name: "pet_getAll", args: {}, ident: "pet_getAll" },
  8981. ]
  8982. });
  8983. const bossEventInfo = data.results[1].result.response.find(e => e.offerType == "bossEvent");
  8984. if (!bossEventInfo) {
  8985. setProgress('Эвент завершен', true);
  8986. return;
  8987. }
  8988.  
  8989. if (bossEventInfo.progress.score > 250) {
  8990. setProgress('Уже убито больше 250 врагов');
  8991. rewardBossRatingEventSouls();
  8992. return;
  8993. }
  8994. const availablePets = Object.values(data.results[2].result.response).map(e => e.id);
  8995. const heroGetAllList = data.results[0].result.response;
  8996. const usedHeroes = bossEventInfo.progress.usedHeroes;
  8997. const heroList = [];
  8998.  
  8999. for (let heroId in heroGetAllList) {
  9000. let hero = heroGetAllList[heroId];
  9001. if (usedHeroes.includes(hero.id)) {
  9002. continue;
  9003. }
  9004. heroList.push(hero.id);
  9005. }
  9006.  
  9007. if (!heroList.length) {
  9008. setProgress('Нет героев', true);
  9009. return;
  9010. }
  9011.  
  9012. const pet = availablePets.includes(6005) ? 6005 : availablePets[Math.floor(Math.random() * availablePets.length)];
  9013. const petLib = lib.getData('pet');
  9014. let count = 1;
  9015.  
  9016. for (const heroId of heroList) {
  9017. const args = {
  9018. heroes: [heroId],
  9019. pet
  9020. }
  9021. /** Поиск питомца для героя */
  9022. for (const petId of availablePets) {
  9023. if (petLib[petId].favorHeroes.includes(heroId)) {
  9024. args.favor = {
  9025. [heroId]: petId
  9026. }
  9027. break;
  9028. }
  9029. }
  9030.  
  9031. const calls = [{
  9032. name: "bossRatingEvent_startBattle",
  9033. args,
  9034. ident: "body"
  9035. }, {
  9036. name: "offerGetAll",
  9037. args: {},
  9038. ident: "offerGetAll"
  9039. }];
  9040.  
  9041. const res = await Send({ calls });
  9042. count++;
  9043.  
  9044. if ('error' in res) {
  9045. console.error(res.error);
  9046. setProgress('Перезагрузите игру и попробуйте позже', true);
  9047. return;
  9048. }
  9049.  
  9050. const eventInfo = res.results[1].result.response.find(e => e.offerType == "bossEvent");
  9051. if (eventInfo.progress.score > 250) {
  9052. break;
  9053. }
  9054. setProgress('Количество убитых врагов: ' + eventInfo.progress.score + '<br>Использовано ' + count + ' героев');
  9055. }
  9056.  
  9057. rewardBossRatingEventSouls();
  9058. }
  9059. /** Сбор награды из Горнила Душ */
  9060. async function rewardBossRatingEventSouls() {
  9061. const data = await Send({
  9062. calls: [
  9063. { name: "offerGetAll", args: {}, ident: "offerGetAll" }
  9064. ]
  9065. });
  9066.  
  9067. const bossEventInfo = data.results[0].result.response.find(e => e.offerType == "bossEvent");
  9068. if (!bossEventInfo) {
  9069. setProgress('Эвент завершен', true);
  9070. return;
  9071. }
  9072.  
  9073. const farmedChests = bossEventInfo.progress.farmedChests;
  9074. const score = bossEventInfo.progress.score;
  9075. // setProgress('Количество убитых врагов: ' + score);
  9076. const revard = bossEventInfo.reward;
  9077. const calls = [];
  9078.  
  9079. let count = 0;
  9080. for (let i = 1; i < 10; i++) {
  9081. if (farmedChests.includes(i)) {
  9082. continue;
  9083. }
  9084. if (score < revard[i].score) {
  9085. break;
  9086. }
  9087. calls.push({
  9088. name: "bossRatingEvent_getReward",
  9089. args: {
  9090. rewardId: i
  9091. },
  9092. ident: "body_" + i
  9093. });
  9094. count++;
  9095. }
  9096. if (!count) {
  9097. setProgress('Нечего собирать', true);
  9098. return;
  9099. }
  9100.  
  9101. Send({ calls }).then(e => {
  9102. console.log(e);
  9103. setProgress('Собрано ' + e?.results?.length + ' наград', true);
  9104. })
  9105. }
  9106. /**
  9107. * Spin the Seer
  9108. *
  9109. * Покрутить провидца
  9110. */
  9111. async function rollAscension() {
  9112. const refillable = await Send({calls:[
  9113. {
  9114. name:"userGetInfo",
  9115. args:{},
  9116. ident:"userGetInfo"
  9117. }
  9118. ]}).then(e => e.results[0].result.response.refillable);
  9119. const i47 = refillable.find(i => i.id == 47);
  9120. if (i47?.amount) {
  9121. await Send({ calls: [{ name: "ascensionChest_open", args: { paid: false, amount: 1 }, ident: "body" }] });
  9122. setProgress(I18N('DONE'), true);
  9123. } else {
  9124. setProgress(I18N('NOT_ENOUGH_AP'), true);
  9125. }
  9126. }
  9127.  
  9128. /**
  9129. * Collect gifts for the New Year
  9130. *
  9131. * Собрать подарки на новый год
  9132. */
  9133. function getGiftNewYear() {
  9134. Send({ calls: [{ name: "newYearGiftGet", args: { type: 0 }, ident: "body" }] }).then(e => {
  9135. const gifts = e.results[0].result.response.gifts;
  9136. const calls = gifts.filter(e => e.opened == 0).map(e => ({
  9137. name: "newYearGiftOpen",
  9138. args: {
  9139. giftId: e.id
  9140. },
  9141. ident: `body_${e.id}`
  9142. }));
  9143. if (!calls.length) {
  9144. setProgress(I18N('NY_NO_GIFTS'), 5000);
  9145. return;
  9146. }
  9147. Send({ calls }).then(e => {
  9148. console.log(e.results)
  9149. const msg = I18N('NY_GIFTS_COLLECTED', { count: e.results.length });
  9150. console.log(msg);
  9151. setProgress(msg, 5000);
  9152. });
  9153. })
  9154. }
  9155.  
  9156. async function updateArtifacts() {
  9157. const count = +await popup.confirm(I18N('SET_NUMBER_LEVELS'), [
  9158. { msg: I18N('BTN_GO'), isInput: true, default: 10 },
  9159. { result: false, isClose: true }
  9160. ]);
  9161. if (!count) {
  9162. return;
  9163. }
  9164. const quest = new questRun;
  9165. await quest.autoInit();
  9166. const heroes = Object.values(quest.questInfo['heroGetAll']);
  9167. const inventory = quest.questInfo['inventoryGet'];
  9168. const calls = [];
  9169. for (let i = count; i > 0; i--) {
  9170. const upArtifact = quest.getUpgradeArtifact();
  9171. if (!upArtifact.heroId) {
  9172. if (await popup.confirm(I18N('POSSIBLE_IMPROVE_LEVELS', { count: calls.length }), [
  9173. { msg: I18N('YES'), result: true },
  9174. { result: false, isClose: true }
  9175. ])) {
  9176. break;
  9177. } else {
  9178. return;
  9179. }
  9180. }
  9181. const hero = heroes.find(e => e.id == upArtifact.heroId);
  9182. hero.artifacts[upArtifact.slotId].level++;
  9183. inventory[upArtifact.costCurrency][upArtifact.costId] -= upArtifact.costValue;
  9184. calls.push({
  9185. name: "heroArtifactLevelUp",
  9186. args: {
  9187. heroId: upArtifact.heroId,
  9188. slotId: upArtifact.slotId
  9189. },
  9190. ident: `heroArtifactLevelUp_${i}`
  9191. });
  9192. }
  9193.  
  9194. if (!calls.length) {
  9195. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  9196. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  9197. return;
  9198. }
  9199.  
  9200. await Send(JSON.stringify({ calls })).then(e => {
  9201. if ('error' in e) {
  9202. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  9203. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  9204. } else {
  9205. console.log(I18N('IMPROVED_LEVELS', { count: e.results.length }));
  9206. setProgress(I18N('IMPROVED_LEVELS', { count: e.results.length }), false);
  9207. }
  9208. });
  9209. }
  9210.  
  9211. window.sign = a => {
  9212. const i = this['\x78\x79\x7a'];
  9213. 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'))
  9214. }
  9215.  
  9216. async function updateSkins() {
  9217. const count = +await popup.confirm(I18N('SET_NUMBER_LEVELS'), [
  9218. { msg: I18N('BTN_GO'), isInput: true, default: 10 },
  9219. { result: false, isClose: true }
  9220. ]);
  9221. if (!count) {
  9222. return;
  9223. }
  9224.  
  9225. const quest = new questRun;
  9226. await quest.autoInit();
  9227. const heroes = Object.values(quest.questInfo['heroGetAll']);
  9228. const inventory = quest.questInfo['inventoryGet'];
  9229. const calls = [];
  9230. for (let i = count; i > 0; i--) {
  9231. const upSkin = quest.getUpgradeSkin();
  9232. if (!upSkin.heroId) {
  9233. if (await popup.confirm(I18N('POSSIBLE_IMPROVE_LEVELS', { count: calls.length }), [
  9234. { msg: I18N('YES'), result: true },
  9235. { result: false, isClose: true }
  9236. ])) {
  9237. break;
  9238. } else {
  9239. return;
  9240. }
  9241. }
  9242. const hero = heroes.find(e => e.id == upSkin.heroId);
  9243. hero.skins[upSkin.skinId]++;
  9244. inventory[upSkin.costCurrency][upSkin.costCurrencyId] -= upSkin.cost;
  9245. calls.push({
  9246. name: "heroSkinUpgrade",
  9247. args: {
  9248. heroId: upSkin.heroId,
  9249. skinId: upSkin.skinId
  9250. },
  9251. ident: `heroSkinUpgrade_${i}`
  9252. })
  9253. }
  9254.  
  9255. if (!calls.length) {
  9256. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  9257. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  9258. return;
  9259. }
  9260.  
  9261. await Send(JSON.stringify({ calls })).then(e => {
  9262. if ('error' in e) {
  9263. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  9264. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  9265. } else {
  9266. console.log(I18N('IMPROVED_LEVELS', { count: e.results.length }));
  9267. setProgress(I18N('IMPROVED_LEVELS', { count: e.results.length }), false);
  9268. }
  9269. });
  9270. }
  9271.  
  9272. function getQuestionInfo(img, nameOnly = false) {
  9273. const libHeroes = Object.values(lib.data.hero);
  9274. const parts = img.split(':');
  9275. const id = parts[1];
  9276. switch (parts[0]) {
  9277. case 'titanArtifact_id':
  9278. return cheats.translate("LIB_TITAN_ARTIFACT_NAME_" + id);
  9279. case 'titan':
  9280. return cheats.translate("LIB_HERO_NAME_" + id);
  9281. case 'skill':
  9282. return cheats.translate("LIB_SKILL_" + id);
  9283. case 'inventoryItem_gear':
  9284. return cheats.translate("LIB_GEAR_NAME_" + id);
  9285. case 'inventoryItem_coin':
  9286. return cheats.translate("LIB_COIN_NAME_" + id);
  9287. case 'artifact':
  9288. if (nameOnly) {
  9289. return cheats.translate("LIB_ARTIFACT_NAME_" + id);
  9290. }
  9291. heroes = libHeroes.filter(h => h.id < 100 && h.artifacts.includes(+id));
  9292. return {
  9293. /** Как называется этот артефакт? */
  9294. name: cheats.translate("LIB_ARTIFACT_NAME_" + id),
  9295. /** Какому герою принадлежит этот артефакт? */
  9296. heroes: heroes.map(h => cheats.translate("LIB_HERO_NAME_" + h.id))
  9297. };
  9298. case 'hero':
  9299. if (nameOnly) {
  9300. return cheats.translate("LIB_HERO_NAME_" + id);
  9301. }
  9302. artifacts = lib.data.hero[id].artifacts;
  9303. return {
  9304. /** Как зовут этого героя? */
  9305. name: cheats.translate("LIB_HERO_NAME_" + id),
  9306. /** Какой артефакт принадлежит этому герою? */
  9307. artifact: artifacts.map(a => cheats.translate("LIB_ARTIFACT_NAME_" + a))
  9308. };
  9309. }
  9310. }
  9311.  
  9312. function hintQuest(quest) {
  9313. const result = {};
  9314. if (quest?.questionIcon) {
  9315. const info = getQuestionInfo(quest.questionIcon);
  9316. if (info?.heroes) {
  9317. /** Какому герою принадлежит этот артефакт? */
  9318. result.answer = quest.answers.filter(e => info.heroes.includes(e.answerText.slice(1)));
  9319. }
  9320. if (info?.artifact) {
  9321. /** Какой артефакт принадлежит этому герою? */
  9322. result.answer = quest.answers.filter(e => info.artifact.includes(e.answerText.slice(1)));
  9323. }
  9324. if (typeof info == 'string') {
  9325. result.info = { name: info };
  9326. } else {
  9327. result.info = info;
  9328. }
  9329. }
  9330.  
  9331. if (quest.answers[0]?.answerIcon) {
  9332. result.answer = quest.answers.filter(e => quest.question.includes(getQuestionInfo(e.answerIcon, true)))
  9333. }
  9334.  
  9335. if ((!result?.answer || !result.answer.length) && !result.info?.name) {
  9336. return false;
  9337. }
  9338.  
  9339. let resultText = '';
  9340. if (result?.info) {
  9341. resultText += I18N('PICTURE') + result.info.name;
  9342. }
  9343. console.log(result);
  9344. if (result?.answer && result.answer.length) {
  9345. resultText += I18N('ANSWER') + result.answer[0].id + (!result.answer[0].answerIcon ? ' - ' + result.answer[0].answerText : '');
  9346. }
  9347.  
  9348. return resultText;
  9349. }
  9350.  
  9351. async function farmBattlePass() {
  9352. const isFarmReward = (reward) => {
  9353. return !(reward?.buff || reward?.fragmentHero || reward?.bundleHeroReward);
  9354. };
  9355.  
  9356. const battlePassProcess = (pass) => {
  9357. if (!pass.id) {return []}
  9358. const levels = Object.values(lib.data.battlePass.level).filter(x => x.battlePass == pass.id)
  9359. const last_level = levels[levels.length - 1];
  9360. let actual = Math.max(...levels.filter(p => pass.exp >= p.experience).map(p => p.level))
  9361.  
  9362. if (pass.exp > last_level.experience) {
  9363. actual = last_level.level + (pass.exp - last_level.experience) / last_level.experienceByLevel;
  9364. }
  9365. const calls = [];
  9366. for(let i = 1; i <= actual; i++) {
  9367. const level = i >= last_level.level ? last_level : levels.find(l => l.level === i);
  9368. const reward = {free: level?.freeReward, paid:level?.paidReward};
  9369.  
  9370. if (!pass.rewards[i]?.free && isFarmReward(reward.free)) {
  9371. const args = {level: i, free:true};
  9372. if (!pass.gold) { args.id = pass.id }
  9373. calls.push({ name: 'battlePass_farmReward', args, ident: `${pass.gold ? 'body' : 'spesial'}_free_${args.id}_${i}` });
  9374. }
  9375. if (pass.ticket && !pass.rewards[i]?.paid && isFarmReward(reward.paid)) {
  9376. const args = {level: i, free:false};
  9377. if (!pass.gold) { args.id = pass.id}
  9378. calls.push({ name: 'battlePass_farmReward', args, ident: `${pass.gold ? 'body' : 'spesial'}_paid_${args.id}_${i}` });
  9379. }
  9380. }
  9381. return calls;
  9382. }
  9383.  
  9384. const passes = await Send({
  9385. calls: [
  9386. { name: 'battlePass_getInfo', args: {}, ident: 'getInfo' },
  9387. { name: 'battlePass_getSpecial', args: {}, ident: 'getSpecial' },
  9388. ],
  9389. }).then((e) => [{...e.results[0].result.response?.battlePass, gold: true}, ...Object.values(e.results[1].result.response)]);
  9390.  
  9391. const calls = passes.map(p => battlePassProcess(p)).flat()
  9392.  
  9393. if (!calls.length) {
  9394. setProgress(I18N('NOTHING_TO_COLLECT'));
  9395. return;
  9396. }
  9397.  
  9398. let results = await Send({calls});
  9399. if (results.error) {
  9400. console.log(results.error);
  9401. setProgress(I18N('SOMETHING_WENT_WRONG'));
  9402. } else {
  9403. setProgress(I18N('SEASON_REWARD_COLLECTED', {count: results.results.length}), true);
  9404. }
  9405. }
  9406.  
  9407. async function sellHeroSoulsForGold() {
  9408. let { fragmentHero, heroes } = await Send({
  9409. calls: [
  9410. { name: 'inventoryGet', args: {}, ident: 'inventoryGet' },
  9411. { name: 'heroGetAll', args: {}, ident: 'heroGetAll' },
  9412. ],
  9413. })
  9414. .then((e) => e.results.map((r) => r.result.response))
  9415. .then((e) => ({ fragmentHero: e[0].fragmentHero, heroes: e[1] }));
  9416.  
  9417. const calls = [];
  9418. for (let i in fragmentHero) {
  9419. if (heroes[i] && heroes[i].star == 6) {
  9420. calls.push({
  9421. name: 'inventorySell',
  9422. args: {
  9423. type: 'hero',
  9424. libId: i,
  9425. amount: fragmentHero[i],
  9426. fragment: true,
  9427. },
  9428. ident: 'inventorySell_' + i,
  9429. });
  9430. }
  9431. }
  9432. if (!calls.length) {
  9433. console.log(0);
  9434. return 0;
  9435. }
  9436. const rewards = await Send({ calls }).then((e) => e.results.map((r) => r.result?.response?.gold || 0));
  9437. const gold = rewards.reduce((e, a) => e + a, 0);
  9438. setProgress(I18N('GOLD_RECEIVED', { gold }), true);
  9439. }
  9440.  
  9441. /**
  9442. * Attack of the minions of Asgard
  9443. *
  9444. * Атака прислужников Асгарда
  9445. */
  9446. function testRaidNodes() {
  9447. const { executeRaidNodes } = HWHClasses;
  9448. return new Promise((resolve, reject) => {
  9449. const tower = new executeRaidNodes(resolve, reject);
  9450. tower.start();
  9451. });
  9452. }
  9453.  
  9454. /**
  9455. * Attack of the minions of Asgard
  9456. *
  9457. * Атака прислужников Асгарда
  9458. */
  9459. function executeRaidNodes(resolve, reject) {
  9460. let raidData = {
  9461. teams: [],
  9462. favor: {},
  9463. nodes: [],
  9464. attempts: 0,
  9465. countExecuteBattles: 0,
  9466. cancelBattle: 0,
  9467. }
  9468.  
  9469. callsExecuteRaidNodes = {
  9470. calls: [{
  9471. name: "clanRaid_getInfo",
  9472. args: {},
  9473. ident: "clanRaid_getInfo"
  9474. }, {
  9475. name: "teamGetAll",
  9476. args: {},
  9477. ident: "teamGetAll"
  9478. }, {
  9479. name: "teamGetFavor",
  9480. args: {},
  9481. ident: "teamGetFavor"
  9482. }]
  9483. }
  9484.  
  9485. this.start = function () {
  9486. send(JSON.stringify(callsExecuteRaidNodes), startRaidNodes);
  9487. }
  9488.  
  9489. async function startRaidNodes(data) {
  9490. res = data.results;
  9491. clanRaidInfo = res[0].result.response;
  9492. teamGetAll = res[1].result.response;
  9493. teamGetFavor = res[2].result.response;
  9494.  
  9495. let index = 0;
  9496. let isNotFullPack = false;
  9497. for (let team of teamGetAll.clanRaid_nodes) {
  9498. if (team.length < 6) {
  9499. isNotFullPack = true;
  9500. }
  9501. raidData.teams.push({
  9502. data: {},
  9503. heroes: team.filter(id => id < 6000),
  9504. pet: team.filter(id => id >= 6000).pop(),
  9505. battleIndex: index++
  9506. });
  9507. }
  9508. raidData.favor = teamGetFavor.clanRaid_nodes;
  9509.  
  9510. if (isNotFullPack) {
  9511. if (await popup.confirm(I18N('MINIONS_WARNING'), [
  9512. { msg: I18N('BTN_NO'), result: true },
  9513. { msg: I18N('BTN_YES'), result: false },
  9514. ])) {
  9515. endRaidNodes('isNotFullPack');
  9516. return;
  9517. }
  9518. }
  9519.  
  9520. raidData.nodes = clanRaidInfo.nodes;
  9521. raidData.attempts = clanRaidInfo.attempts;
  9522. setIsCancalBattle(false);
  9523.  
  9524. checkNodes();
  9525. }
  9526.  
  9527. function getAttackNode() {
  9528. for (let nodeId in raidData.nodes) {
  9529. let node = raidData.nodes[nodeId];
  9530. let points = 0
  9531. for (team of node.teams) {
  9532. points += team.points;
  9533. }
  9534. let now = Date.now() / 1000;
  9535. if (!points && now > node.timestamps.start && now < node.timestamps.end) {
  9536. let countTeam = node.teams.length;
  9537. delete raidData.nodes[nodeId];
  9538. return {
  9539. nodeId,
  9540. countTeam
  9541. };
  9542. }
  9543. }
  9544. return null;
  9545. }
  9546.  
  9547. function checkNodes() {
  9548. setProgress(`${I18N('REMAINING_ATTEMPTS')}: ${raidData.attempts}`);
  9549. let nodeInfo = getAttackNode();
  9550. if (nodeInfo && raidData.attempts) {
  9551. startNodeBattles(nodeInfo);
  9552. return;
  9553. }
  9554.  
  9555. endRaidNodes('EndRaidNodes');
  9556. }
  9557.  
  9558. function startNodeBattles(nodeInfo) {
  9559. let {nodeId, countTeam} = nodeInfo;
  9560. let teams = raidData.teams.slice(0, countTeam);
  9561. let heroes = raidData.teams.map(e => e.heroes).flat();
  9562. let favor = {...raidData.favor};
  9563. for (let heroId in favor) {
  9564. if (!heroes.includes(+heroId)) {
  9565. delete favor[heroId];
  9566. }
  9567. }
  9568.  
  9569. let calls = [{
  9570. name: "clanRaid_startNodeBattles",
  9571. args: {
  9572. nodeId,
  9573. teams,
  9574. favor
  9575. },
  9576. ident: "body"
  9577. }];
  9578.  
  9579. send(JSON.stringify({calls}), resultNodeBattles);
  9580. }
  9581.  
  9582. function resultNodeBattles(e) {
  9583. if (e['error']) {
  9584. endRaidNodes('nodeBattlesError', e['error']);
  9585. return;
  9586. }
  9587.  
  9588. console.log(e);
  9589. let battles = e.results[0].result.response.battles;
  9590. let promises = [];
  9591. let battleIndex = 0;
  9592. for (let battle of battles) {
  9593. battle.battleIndex = battleIndex++;
  9594. promises.push(calcBattleResult(battle));
  9595. }
  9596.  
  9597. Promise.all(promises)
  9598. .then(results => {
  9599. const endResults = {};
  9600. let isAllWin = true;
  9601. for (let r of results) {
  9602. isAllWin &&= r.result.win;
  9603. }
  9604. if (!isAllWin) {
  9605. cancelEndNodeBattle(results[0]);
  9606. return;
  9607. }
  9608. raidData.countExecuteBattles = results.length;
  9609. let timeout = 500;
  9610. for (let r of results) {
  9611. setTimeout(endNodeBattle, timeout, r);
  9612. timeout += 500;
  9613. }
  9614. });
  9615. }
  9616. /**
  9617. * Returns the battle calculation promise
  9618. *
  9619. * Возвращает промис расчета боя
  9620. */
  9621. function calcBattleResult(battleData) {
  9622. return new Promise(function (resolve, reject) {
  9623. BattleCalc(battleData, "get_clanPvp", resolve);
  9624. });
  9625. }
  9626. /**
  9627. * Cancels the fight
  9628. *
  9629. * Отменяет бой
  9630. */
  9631. function cancelEndNodeBattle(r) {
  9632. const fixBattle = function (heroes) {
  9633. for (const ids in heroes) {
  9634. hero = heroes[ids];
  9635. hero.energy = random(1, 999);
  9636. if (hero.hp > 0) {
  9637. hero.hp = random(1, hero.hp);
  9638. }
  9639. }
  9640. }
  9641. fixBattle(r.progress[0].attackers.heroes);
  9642. fixBattle(r.progress[0].defenders.heroes);
  9643. endNodeBattle(r);
  9644. }
  9645. /**
  9646. * Ends the fight
  9647. *
  9648. * Завершает бой
  9649. */
  9650. function endNodeBattle(r) {
  9651. let nodeId = r.battleData.result.nodeId;
  9652. let battleIndex = r.battleData.battleIndex;
  9653. let calls = [{
  9654. name: "clanRaid_endNodeBattle",
  9655. args: {
  9656. nodeId,
  9657. battleIndex,
  9658. result: r.result,
  9659. progress: r.progress
  9660. },
  9661. ident: "body"
  9662. }]
  9663.  
  9664. SendRequest(JSON.stringify({calls}), battleResult);
  9665. }
  9666. /**
  9667. * Processing the results of the battle
  9668. *
  9669. * Обработка результатов боя
  9670. */
  9671. function battleResult(e) {
  9672. if (e['error']) {
  9673. endRaidNodes('missionEndError', e['error']);
  9674. return;
  9675. }
  9676. r = e.results[0].result.response;
  9677. if (r['error']) {
  9678. if (r.reason == "invalidBattle") {
  9679. raidData.cancelBattle++;
  9680. checkNodes();
  9681. } else {
  9682. endRaidNodes('missionEndError', e['error']);
  9683. }
  9684. return;
  9685. }
  9686.  
  9687. if (!(--raidData.countExecuteBattles)) {
  9688. raidData.attempts--;
  9689. checkNodes();
  9690. }
  9691. }
  9692. /**
  9693. * Completing a task
  9694. *
  9695. * Завершение задачи
  9696. */
  9697. function endRaidNodes(reason, info) {
  9698. setIsCancalBattle(true);
  9699. let textCancel = raidData.cancelBattle ? ` ${I18N('BATTLES_CANCELED')}: ${raidData.cancelBattle}` : '';
  9700. setProgress(`${I18N('MINION_RAID')} ${I18N('COMPLETED')}! ${textCancel}`, true);
  9701. console.log(reason, info);
  9702. resolve();
  9703. }
  9704. }
  9705.  
  9706. this.HWHClasses.executeRaidNodes = executeRaidNodes;
  9707.  
  9708. /**
  9709. * Asgard Boss Attack Replay
  9710. *
  9711. * Повтор атаки босса Асгарда
  9712. */
  9713. function testBossBattle() {
  9714. const { executeBossBattle } = HWHClasses;
  9715. return new Promise((resolve, reject) => {
  9716. const bossBattle = new executeBossBattle(resolve, reject);
  9717. bossBattle.start(lastBossBattle);
  9718. });
  9719. }
  9720.  
  9721. /**
  9722. * Asgard Boss Attack Replay
  9723. *
  9724. * Повтор атаки босса Асгарда
  9725. */
  9726. function executeBossBattle(resolve, reject) {
  9727.  
  9728. this.start = function (battleInfo) {
  9729. preCalcBattle(battleInfo);
  9730. }
  9731.  
  9732. function getBattleInfo(battle) {
  9733. return new Promise(function (resolve) {
  9734. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  9735. BattleCalc(battle, getBattleType(battle.type), e => {
  9736. let extra = e.progress[0].defenders.heroes[1].extra;
  9737. resolve(extra.damageTaken + extra.damageTakenNextLevel);
  9738. });
  9739. });
  9740. }
  9741.  
  9742. function preCalcBattle(battle) {
  9743. let actions = [];
  9744. const countTestBattle = getInput('countTestBattle');
  9745. for (let i = 0; i < countTestBattle; i++) {
  9746. actions.push(getBattleInfo(battle, true));
  9747. }
  9748. Promise.all(actions)
  9749. .then(resultPreCalcBattle);
  9750. }
  9751.  
  9752. async function resultPreCalcBattle(damages) {
  9753. let maxDamage = 0;
  9754. let minDamage = 1e10;
  9755. let avgDamage = 0;
  9756. for (let damage of damages) {
  9757. avgDamage += damage
  9758. if (damage > maxDamage) {
  9759. maxDamage = damage;
  9760. }
  9761. if (damage < minDamage) {
  9762. minDamage = damage;
  9763. }
  9764. }
  9765. avgDamage /= damages.length;
  9766. console.log(damages.map(e => e.toLocaleString()).join('\n'), avgDamage, maxDamage);
  9767.  
  9768. await popup.confirm(
  9769. `${I18N('ROUND_STAT')} ${damages.length} ${I18N('BATTLE')}:` +
  9770. `<br>${I18N('MINIMUM')}: ` + minDamage.toLocaleString() +
  9771. `<br>${I18N('MAXIMUM')}: ` + maxDamage.toLocaleString() +
  9772. `<br>${I18N('AVERAGE')}: ` + avgDamage.toLocaleString()
  9773. , [
  9774. { msg: I18N('BTN_OK'), result: 0},
  9775. ])
  9776. endBossBattle(I18N('BTN_CANCEL'));
  9777. }
  9778.  
  9779. /**
  9780. * Completing a task
  9781. *
  9782. * Завершение задачи
  9783. */
  9784. function endBossBattle(reason, info) {
  9785. console.log(reason, info);
  9786. resolve();
  9787. }
  9788. }
  9789.  
  9790. this.HWHClasses.executeBossBattle = executeBossBattle;
  9791.  
  9792. class FixBattle {
  9793. minTimer = 1.3;
  9794. maxTimer = 15.3;
  9795.  
  9796. constructor(battle, isTimeout = true) {
  9797. this.battle = structuredClone(battle);
  9798. this.isTimeout = isTimeout;
  9799. }
  9800.  
  9801. timeout(callback, timeout) {
  9802. if (this.isTimeout) {
  9803. this.worker.postMessage(timeout);
  9804. this.worker.onmessage = callback;
  9805. } else {
  9806. callback();
  9807. }
  9808. }
  9809.  
  9810. randTimer() {
  9811. return Math.random() * (this.maxTimer - this.minTimer + 1) + this.minTimer;
  9812. }
  9813.  
  9814. setAvgTime(startTime) {
  9815. this.fixTime += Date.now() - startTime;
  9816. this.avgTime = this.fixTime / this.count;
  9817. }
  9818.  
  9819. init() {
  9820. this.fixTime = 0;
  9821. this.lastTimer = 0;
  9822. this.index = 0;
  9823. this.lastBossDamage = 0;
  9824. this.bestResult = {
  9825. count: 0,
  9826. timer: 0,
  9827. value: 0,
  9828. result: null,
  9829. progress: null,
  9830. };
  9831. this.lastBattleResult = {
  9832. win: false,
  9833. };
  9834. this.worker = new Worker(
  9835. URL.createObjectURL(
  9836. new Blob([
  9837. `self.onmessage = function(e) {
  9838. const timeout = e.data;
  9839. setTimeout(() => {
  9840. self.postMessage(1);
  9841. }, timeout);
  9842. };`,
  9843. ])
  9844. )
  9845. );
  9846. }
  9847.  
  9848. async start(endTime = Date.now() + 6e4, maxCount = 100) {
  9849. this.endTime = endTime;
  9850. this.maxCount = maxCount;
  9851. this.init();
  9852. return await new Promise((resolve) => {
  9853. this.resolve = resolve;
  9854. this.count = 0;
  9855. this.loop();
  9856. });
  9857. }
  9858.  
  9859. endFix() {
  9860. this.bestResult.maxCount = this.count;
  9861. this.worker.terminate();
  9862. this.resolve(this.bestResult);
  9863. }
  9864.  
  9865. async loop() {
  9866. const start = Date.now();
  9867. if (this.isEndLoop()) {
  9868. this.endFix();
  9869. return;
  9870. }
  9871. this.count++;
  9872. try {
  9873. this.lastResult = await Calc(this.battle);
  9874. } catch (e) {
  9875. this.updateProgressTimer(this.index++);
  9876. this.timeout(this.loop.bind(this), 0);
  9877. return;
  9878. }
  9879. const { progress, result } = this.lastResult;
  9880. this.lastBattleResult = result;
  9881. this.lastBattleProgress = progress;
  9882. this.setAvgTime(start);
  9883. this.checkResult();
  9884. this.showResult();
  9885. this.updateProgressTimer();
  9886. this.timeout(this.loop.bind(this), 0);
  9887. }
  9888.  
  9889. isEndLoop() {
  9890. return this.count >= this.maxCount || this.endTime < Date.now();
  9891. }
  9892.  
  9893. updateProgressTimer(index = 0) {
  9894. this.lastTimer = this.randTimer();
  9895. this.battle.progress = [{ attackers: { input: ['auto', 0, 0, 'auto', index, this.lastTimer] } }];
  9896. }
  9897.  
  9898. showResult() {
  9899. console.log(
  9900. this.count,
  9901. this.avgTime.toFixed(2),
  9902. (this.endTime - Date.now()) / 1000,
  9903. this.lastTimer.toFixed(2),
  9904. this.lastBossDamage.toLocaleString(),
  9905. this.bestResult.value.toLocaleString()
  9906. );
  9907. }
  9908.  
  9909. checkResult() {
  9910. const { damageTaken, damageTakenNextLevel } = this.lastBattleProgress[0].defenders.heroes[1].extra;
  9911. this.lastBossDamage = damageTaken + damageTakenNextLevel;
  9912. if (this.lastBossDamage > this.bestResult.value) {
  9913. this.bestResult = {
  9914. count: this.count,
  9915. timer: this.lastTimer,
  9916. value: this.lastBossDamage,
  9917. result: structuredClone(this.lastBattleResult),
  9918. progress: structuredClone(this.lastBattleProgress),
  9919. };
  9920. }
  9921. }
  9922.  
  9923. stopFix() {
  9924. this.endTime = 0;
  9925. }
  9926. }
  9927.  
  9928. this.HWHClasses.FixBattle = FixBattle;
  9929.  
  9930. class WinFixBattle extends FixBattle {
  9931. checkResult() {
  9932. if (this.lastBattleResult.win) {
  9933. this.bestResult = {
  9934. count: this.count,
  9935. timer: this.lastTimer,
  9936. value: this.lastBattleResult.stars,
  9937. result: structuredClone(this.lastBattleResult),
  9938. progress: structuredClone(this.lastBattleProgress),
  9939. battleTimer: this.lastResult.battleTimer,
  9940. };
  9941. }
  9942. }
  9943.  
  9944. setWinTimer(value) {
  9945. this.winTimer = value;
  9946. }
  9947.  
  9948. setMaxTimer(value) {
  9949. this.maxTimer = value;
  9950. }
  9951.  
  9952. randTimer() {
  9953. if (this.winTimer) {
  9954. return this.winTimer;
  9955. }
  9956. return super.randTimer();
  9957. }
  9958.  
  9959. isEndLoop() {
  9960. return super.isEndLoop() || this.bestResult.result?.win;
  9961. }
  9962.  
  9963. showResult() {
  9964. console.log(
  9965. this.count,
  9966. this.avgTime.toFixed(2),
  9967. (this.endTime - Date.now()) / 1000,
  9968. this.lastResult.battleTime,
  9969. this.lastTimer,
  9970. this.bestResult.value
  9971. );
  9972. const endTime = ((this.endTime - Date.now()) / 1000).toFixed(2);
  9973. const avgTime = this.avgTime.toFixed(2);
  9974. const msg = `${I18N('LETS_FIX')} ${this.count}/${this.maxCount}<br/>${endTime}s<br/>${avgTime}ms`;
  9975. setProgress(msg, false, this.stopFix.bind(this));
  9976. }
  9977. }
  9978.  
  9979. this.HWHClasses.WinFixBattle = WinFixBattle;
  9980.  
  9981. class BestOrWinFixBattle extends WinFixBattle {
  9982. isNoMakeWin = false;
  9983.  
  9984. getState(result) {
  9985. let beforeSumFactor = 0;
  9986. const beforeHeroes = result.battleData.defenders[0];
  9987. for (let heroId in beforeHeroes) {
  9988. const hero = beforeHeroes[heroId];
  9989. const state = hero.state;
  9990. let factor = 1;
  9991. if (state) {
  9992. const hp = state.hp / (hero?.hp || 1);
  9993. const energy = state.energy / 1e3;
  9994. factor = hp + energy / 20;
  9995. }
  9996. beforeSumFactor += factor;
  9997. }
  9998.  
  9999. let afterSumFactor = 0;
  10000. const afterHeroes = result.progress[0].defenders.heroes;
  10001. for (let heroId in afterHeroes) {
  10002. const hero = afterHeroes[heroId];
  10003. const hp = hero.hp / (beforeHeroes[heroId]?.hp || 1);
  10004. const energy = hero.energy / 1e3;
  10005. const factor = hp + energy / 20;
  10006. afterSumFactor += factor;
  10007. }
  10008. return 100 - Math.floor((afterSumFactor / beforeSumFactor) * 1e4) / 100;
  10009. }
  10010.  
  10011. setNoMakeWin(value) {
  10012. this.isNoMakeWin = value;
  10013. }
  10014.  
  10015. checkResult() {
  10016. const state = this.getState(this.lastResult);
  10017. console.log(state);
  10018.  
  10019. if (state > this.bestResult.value) {
  10020. if (!(this.isNoMakeWin && this.lastBattleResult.win)) {
  10021. this.bestResult = {
  10022. count: this.count,
  10023. timer: this.lastTimer,
  10024. value: state,
  10025. result: structuredClone(this.lastBattleResult),
  10026. progress: structuredClone(this.lastBattleProgress),
  10027. battleTimer: this.lastResult.battleTimer,
  10028. };
  10029. }
  10030. }
  10031. }
  10032. }
  10033.  
  10034. this.HWHClasses.BestOrWinFixBattle = BestOrWinFixBattle;
  10035.  
  10036. class BossFixBattle extends FixBattle {
  10037. showResult() {
  10038. super.showResult();
  10039. //setTimeout(() => {
  10040. const best = this.bestResult;
  10041. const maxDmg = best.value.toLocaleString();
  10042. const avgTime = this.avgTime.toLocaleString();
  10043. const msg = `${I18N('LETS_FIX')} ${this.count}/${this.maxCount}<br/>${maxDmg}<br/>${avgTime}ms`;
  10044. setProgress(msg, false, this.stopFix.bind(this));
  10045. //}, 0);
  10046. }
  10047. }
  10048.  
  10049. this.HWHClasses.BossFixBattle = BossFixBattle;
  10050.  
  10051. class DungeonFixBattle extends FixBattle {
  10052. init() {
  10053. super.init();
  10054. this.isTimeout = false;
  10055. }
  10056.  
  10057. setState() {
  10058. const result = this.lastResult;
  10059. let beforeSumFactor = 0;
  10060. const beforeHeroes = result.battleData.attackers;
  10061. for (let heroId in beforeHeroes) {
  10062. const hero = beforeHeroes[heroId];
  10063. const state = hero.state;
  10064. let factor = 1;
  10065. if (state) {
  10066. const hp = state.hp / (hero?.hp || 1);
  10067. const energy = state.energy / 1e3;
  10068. factor = hp + energy / 20;
  10069. }
  10070. beforeSumFactor += factor;
  10071. }
  10072.  
  10073. let afterSumFactor = 0;
  10074. const afterHeroes = result.progress[0].attackers.heroes;
  10075. for (let heroId in afterHeroes) {
  10076. const hero = afterHeroes[heroId];
  10077. const hp = hero.hp / (beforeHeroes[heroId]?.hp || 1);
  10078. const energy = hero.energy / 1e3;
  10079. const factor = hp + energy / 20;
  10080. afterSumFactor += factor;
  10081. }
  10082. this.lastState = Math.floor((afterSumFactor / beforeSumFactor) * 1e4) / 100;
  10083. }
  10084.  
  10085. checkResult() {
  10086. this.setState();
  10087. if (this.lastResult.result.win && this.lastState > this.bestResult.value) {
  10088. this.bestResult = {
  10089. count: this.count,
  10090. timer: this.lastTimer,
  10091. value: this.lastState,
  10092. result: this.lastResult.result,
  10093. progress: this.lastResult.progress,
  10094. };
  10095. }
  10096. }
  10097.  
  10098. showResult() {
  10099. console.log(
  10100. this.count,
  10101. this.avgTime.toFixed(2),
  10102. (this.endTime - Date.now()) / 1000,
  10103. this.lastTimer.toFixed(2),
  10104. this.lastState.toLocaleString(),
  10105. this.bestResult.value.toLocaleString()
  10106. );
  10107. }
  10108. }
  10109.  
  10110. this.HWHClasses.DungeonFixBattle = DungeonFixBattle;
  10111.  
  10112. const masterWsMixin = {
  10113. wsStart() {
  10114. const socket = new WebSocket(this.url);
  10115.  
  10116. socket.onopen = () => {
  10117. console.log('Connected to server');
  10118.  
  10119. // Пример создания новой задачи
  10120. const newTask = {
  10121. type: 'newTask',
  10122. battle: this.battle,
  10123. endTime: this.endTime - 1e4,
  10124. maxCount: this.maxCount,
  10125. };
  10126. socket.send(JSON.stringify(newTask));
  10127. };
  10128.  
  10129. socket.onmessage = this.onmessage.bind(this);
  10130.  
  10131. socket.onclose = () => {
  10132. console.log('Disconnected from server');
  10133. };
  10134.  
  10135. this.ws = socket;
  10136. },
  10137.  
  10138. onmessage(event) {
  10139. const data = JSON.parse(event.data);
  10140. switch (data.type) {
  10141. case 'newTask': {
  10142. console.log('newTask:', data);
  10143. this.id = data.id;
  10144. this.countExecutor = data.count;
  10145. break;
  10146. }
  10147. case 'getSolTask': {
  10148. console.log('getSolTask:', data);
  10149. this.endFix(data.solutions);
  10150. break;
  10151. }
  10152. case 'resolveTask': {
  10153. console.log('resolveTask:', data);
  10154. if (data.id === this.id && data.solutions.length === this.countExecutor) {
  10155. this.worker.terminate();
  10156. this.endFix(data.solutions);
  10157. }
  10158. break;
  10159. }
  10160. default:
  10161. console.log('Unknown message type:', data.type);
  10162. }
  10163. },
  10164.  
  10165. getTask() {
  10166. this.ws.send(
  10167. JSON.stringify({
  10168. type: 'getSolTask',
  10169. id: this.id,
  10170. })
  10171. );
  10172. },
  10173. };
  10174.  
  10175. /*
  10176. mFix = new action.masterFixBattle(battle)
  10177. await mFix.start(Date.now() + 6e4, 1);
  10178. */
  10179. class masterFixBattle extends FixBattle {
  10180. constructor(battle, url = 'wss://localho.st:3000') {
  10181. super(battle, true);
  10182. this.url = url;
  10183. }
  10184.  
  10185. async start(endTime, maxCount) {
  10186. this.endTime = endTime;
  10187. this.maxCount = maxCount;
  10188. this.init();
  10189. this.wsStart();
  10190. return await new Promise((resolve) => {
  10191. this.resolve = resolve;
  10192. const timeout = this.endTime - Date.now();
  10193. this.timeout(this.getTask.bind(this), timeout);
  10194. });
  10195. }
  10196.  
  10197. async endFix(solutions) {
  10198. this.ws.close();
  10199. let maxCount = 0;
  10200. for (const solution of solutions) {
  10201. maxCount += solution.maxCount;
  10202. if (solution.value > this.bestResult.value) {
  10203. this.bestResult = solution;
  10204. }
  10205. }
  10206. this.count = maxCount;
  10207. super.endFix();
  10208. }
  10209. }
  10210.  
  10211. Object.assign(masterFixBattle.prototype, masterWsMixin);
  10212.  
  10213. this.HWHClasses.masterFixBattle = masterFixBattle;
  10214.  
  10215. class masterWinFixBattle extends WinFixBattle {
  10216. constructor(battle, url = 'wss://localho.st:3000') {
  10217. super(battle, true);
  10218. this.url = url;
  10219. }
  10220.  
  10221. async start(endTime, maxCount) {
  10222. this.endTime = endTime;
  10223. this.maxCount = maxCount;
  10224. this.init();
  10225. this.wsStart();
  10226. return await new Promise((resolve) => {
  10227. this.resolve = resolve;
  10228. const timeout = this.endTime - Date.now();
  10229. this.timeout(this.getTask.bind(this), timeout);
  10230. });
  10231. }
  10232.  
  10233. async endFix(solutions) {
  10234. this.ws.close();
  10235. let maxCount = 0;
  10236. for (const solution of solutions) {
  10237. maxCount += solution.maxCount;
  10238. if (solution.value > this.bestResult.value) {
  10239. this.bestResult = solution;
  10240. }
  10241. }
  10242. this.count = maxCount;
  10243. super.endFix();
  10244. }
  10245. }
  10246.  
  10247. Object.assign(masterWinFixBattle.prototype, masterWsMixin);
  10248.  
  10249. this.HWHClasses.masterWinFixBattle = masterWinFixBattle;
  10250.  
  10251. const slaveWsMixin = {
  10252. wsStop() {
  10253. this.ws.close();
  10254. },
  10255.  
  10256. wsStart() {
  10257. const socket = new WebSocket(this.url);
  10258.  
  10259. socket.onopen = () => {
  10260. console.log('Connected to server');
  10261. };
  10262. socket.onmessage = this.onmessage.bind(this);
  10263. socket.onclose = () => {
  10264. console.log('Disconnected from server');
  10265. };
  10266.  
  10267. this.ws = socket;
  10268. },
  10269.  
  10270. async onmessage(event) {
  10271. const data = JSON.parse(event.data);
  10272. switch (data.type) {
  10273. case 'newTask': {
  10274. console.log('newTask:', data.task);
  10275. const { battle, endTime, maxCount } = data.task;
  10276. this.battle = battle;
  10277. const id = data.task.id;
  10278. const solution = await this.start(endTime, maxCount);
  10279. this.ws.send(
  10280. JSON.stringify({
  10281. type: 'resolveTask',
  10282. id,
  10283. solution,
  10284. })
  10285. );
  10286. break;
  10287. }
  10288. default:
  10289. console.log('Unknown message type:', data.type);
  10290. }
  10291. },
  10292. };
  10293. /*
  10294. sFix = new action.slaveFixBattle();
  10295. sFix.wsStart()
  10296. */
  10297. class slaveFixBattle extends FixBattle {
  10298. constructor(url = 'wss://localho.st:3000') {
  10299. super(null, false);
  10300. this.isTimeout = false;
  10301. this.url = url;
  10302. }
  10303. }
  10304.  
  10305. Object.assign(slaveFixBattle.prototype, slaveWsMixin);
  10306.  
  10307. this.HWHClasses.slaveFixBattle = slaveFixBattle;
  10308.  
  10309. class slaveWinFixBattle extends WinFixBattle {
  10310. constructor(url = 'wss://localho.st:3000') {
  10311. super(null, false);
  10312. this.isTimeout = false;
  10313. this.url = url;
  10314. }
  10315. }
  10316.  
  10317. Object.assign(slaveWinFixBattle.prototype, slaveWsMixin);
  10318.  
  10319. this.HWHClasses.slaveWinFixBattle = slaveWinFixBattle;
  10320. /**
  10321. * Auto-repeat attack
  10322. *
  10323. * Автоповтор атаки
  10324. */
  10325. function testAutoBattle() {
  10326. const { executeAutoBattle } = HWHClasses;
  10327. return new Promise((resolve, reject) => {
  10328. const bossBattle = new executeAutoBattle(resolve, reject);
  10329. bossBattle.start(lastBattleArg, lastBattleInfo);
  10330. });
  10331. }
  10332.  
  10333. /**
  10334. * Auto-repeat attack
  10335. *
  10336. * Автоповтор атаки
  10337. */
  10338. function executeAutoBattle(resolve, reject) {
  10339. let battleArg = {};
  10340. let countBattle = 0;
  10341. let countError = 0;
  10342. let findCoeff = 0;
  10343. let dataNotEeceived = 0;
  10344. let stopAutoBattle = false;
  10345.  
  10346. let isSetWinTimer = false;
  10347. 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>';
  10348. 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>';
  10349. 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>';
  10350.  
  10351. this.start = function (battleArgs, battleInfo) {
  10352. battleArg = battleArgs;
  10353. if (nameFuncStartBattle == 'invasion_bossStart') {
  10354. startBattle();
  10355. return;
  10356. }
  10357. preCalcBattle(battleInfo);
  10358. }
  10359. /**
  10360. * Returns a promise for combat recalculation
  10361. *
  10362. * Возвращает промис для прерасчета боя
  10363. */
  10364. function getBattleInfo(battle) {
  10365. return new Promise(function (resolve) {
  10366. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  10367. Calc(battle).then(e => {
  10368. e.coeff = calcCoeff(e, 'defenders');
  10369. resolve(e);
  10370. });
  10371. });
  10372. }
  10373. /**
  10374. * Battle recalculation
  10375. *
  10376. * Прерасчет боя
  10377. */
  10378. function preCalcBattle(battle) {
  10379. let actions = [];
  10380. const countTestBattle = getInput('countTestBattle');
  10381. for (let i = 0; i < countTestBattle; i++) {
  10382. actions.push(getBattleInfo(battle));
  10383. }
  10384. Promise.all(actions)
  10385. .then(resultPreCalcBattle);
  10386. }
  10387. /**
  10388. * Processing the results of the battle recalculation
  10389. *
  10390. * Обработка результатов прерасчета боя
  10391. */
  10392. async function resultPreCalcBattle(results) {
  10393. let countWin = results.reduce((s, w) => w.result.win + s, 0);
  10394. setProgress(`${I18N('CHANCE_TO_WIN')} ${Math.floor(countWin / results.length * 100)}% (${results.length})`, false, hideProgress);
  10395. if (countWin > 0) {
  10396. setIsCancalBattle(false);
  10397. startBattle();
  10398. return;
  10399. }
  10400.  
  10401. let minCoeff = 100;
  10402. let maxCoeff = -100;
  10403. let avgCoeff = 0;
  10404. results.forEach(e => {
  10405. if (e.coeff < minCoeff) minCoeff = e.coeff;
  10406. if (e.coeff > maxCoeff) maxCoeff = e.coeff;
  10407. avgCoeff += e.coeff;
  10408. });
  10409. avgCoeff /= results.length;
  10410.  
  10411. if (nameFuncStartBattle == 'invasion_bossStart' ||
  10412. nameFuncStartBattle == 'bossAttack') {
  10413. const result = await popup.confirm(
  10414. I18N('BOSS_VICTORY_IMPOSSIBLE', { battles: results.length }), [
  10415. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  10416. { msg: I18N('BTN_DO_IT'), result: true },
  10417. ])
  10418. if (result) {
  10419. setIsCancalBattle(false);
  10420. startBattle();
  10421. return;
  10422. }
  10423. setProgress(I18N('NOT_THIS_TIME'), true);
  10424. endAutoBattle('invasion_bossStart');
  10425. return;
  10426. }
  10427.  
  10428. const result = await popup.confirm(
  10429. I18N('VICTORY_IMPOSSIBLE') +
  10430. `<br>${I18N('ROUND_STAT')} ${results.length} ${I18N('BATTLE')}:` +
  10431. `<br>${I18N('MINIMUM')}: ` + minCoeff.toLocaleString() +
  10432. `<br>${I18N('MAXIMUM')}: ` + maxCoeff.toLocaleString() +
  10433. `<br>${I18N('AVERAGE')}: ` + avgCoeff.toLocaleString() +
  10434. `<br>${I18N('FIND_COEFF')} ` + avgCoeff.toLocaleString(), [
  10435. { msg: I18N('BTN_CANCEL'), result: 0, isCancel: true },
  10436. { msg: I18N('BTN_GO'), isInput: true, default: Math.round(avgCoeff * 1000) / 1000 },
  10437. ])
  10438. if (result) {
  10439. findCoeff = result;
  10440. setIsCancalBattle(false);
  10441. startBattle();
  10442. return;
  10443. }
  10444. setProgress(I18N('NOT_THIS_TIME'), true);
  10445. endAutoBattle(I18N('NOT_THIS_TIME'));
  10446. }
  10447.  
  10448. /**
  10449. * Calculation of the combat result coefficient
  10450. *
  10451. * Расчет коэфициента результата боя
  10452. */
  10453. function calcCoeff(result, packType) {
  10454. let beforeSumFactor = 0;
  10455. const beforePack = result.battleData[packType][0];
  10456. for (let heroId in beforePack) {
  10457. const hero = beforePack[heroId];
  10458. const state = hero.state;
  10459. let factor = 1;
  10460. if (state) {
  10461. const hp = state.hp / state.maxHp;
  10462. const energy = state.energy / 1e3;
  10463. factor = hp + energy / 20;
  10464. }
  10465. beforeSumFactor += factor;
  10466. }
  10467.  
  10468. let afterSumFactor = 0;
  10469. const afterPack = result.progress[0][packType].heroes;
  10470. for (let heroId in afterPack) {
  10471. const hero = afterPack[heroId];
  10472. const stateHp = beforePack[heroId]?.state?.hp || beforePack[heroId]?.stats?.hp;
  10473. const hp = hero.hp / stateHp;
  10474. const energy = hero.energy / 1e3;
  10475. const factor = hp + energy / 20;
  10476. afterSumFactor += factor;
  10477. }
  10478. const resultCoeff = -(afterSumFactor - beforeSumFactor);
  10479. return Math.round(resultCoeff * 1000) / 1000;
  10480. }
  10481. /**
  10482. * Start battle
  10483. *
  10484. * Начало боя
  10485. */
  10486. function startBattle() {
  10487. countBattle++;
  10488. const countMaxBattle = getInput('countAutoBattle');
  10489. // setProgress(countBattle + '/' + countMaxBattle);
  10490. if (countBattle > countMaxBattle) {
  10491. setProgress(`${I18N('RETRY_LIMIT_EXCEEDED')}: ${countMaxBattle}`, true);
  10492. endAutoBattle(`${I18N('RETRY_LIMIT_EXCEEDED')}: ${countMaxBattle}`)
  10493. return;
  10494. }
  10495. if (stopAutoBattle) {
  10496. setProgress(I18N('STOPPED'), true);
  10497. endAutoBattle('STOPPED');
  10498. return;
  10499. }
  10500. send({calls: [{
  10501. name: nameFuncStartBattle,
  10502. args: battleArg,
  10503. ident: "body"
  10504. }]}, calcResultBattle);
  10505. }
  10506. /**
  10507. * Battle calculation
  10508. *
  10509. * Расчет боя
  10510. */
  10511. async function calcResultBattle(e) {
  10512. if (!e) {
  10513. console.log('данные не были получены');
  10514. if (dataNotEeceived < 10) {
  10515. dataNotEeceived++;
  10516. startBattle();
  10517. return;
  10518. }
  10519. endAutoBattle('Error', 'данные не были получены ' + dataNotEeceived + ' раз');
  10520. return;
  10521. }
  10522. if ('error' in e) {
  10523. if (e.error.description === 'too many tries') {
  10524. invasionTimer += 100;
  10525. countBattle--;
  10526. countError++;
  10527. console.log(`Errors: ${countError}`, e.error);
  10528. startBattle();
  10529. return;
  10530. }
  10531. const result = await popup.confirm(I18N('ERROR_DURING_THE_BATTLE') + '<br>' + e.error.description, [
  10532. { msg: I18N('BTN_OK'), result: false },
  10533. { msg: I18N('RELOAD_GAME'), result: true },
  10534. ]);
  10535. endAutoBattle('Error', e.error);
  10536. if (result) {
  10537. location.reload();
  10538. }
  10539. return;
  10540. }
  10541. let battle = e.results[0].result.response.battle
  10542. if (nameFuncStartBattle == 'towerStartBattle' ||
  10543. nameFuncStartBattle == 'bossAttack' ||
  10544. nameFuncStartBattle == 'invasion_bossStart') {
  10545. battle = e.results[0].result.response;
  10546. }
  10547. lastBattleInfo = battle;
  10548. BattleCalc(battle, getBattleType(battle.type), resultBattle);
  10549. }
  10550. /**
  10551. * Processing the results of the battle
  10552. *
  10553. * Обработка результатов боя
  10554. */
  10555. async function resultBattle(e) {
  10556. const isWin = e.result.win;
  10557. if (isWin) {
  10558. endBattle(e, false);
  10559. return;
  10560. } else if (isChecked('tryFixIt_v2')) {
  10561. const { WinFixBattle } = HWHClasses;
  10562. const cloneBattle = structuredClone(e.battleData);
  10563. const bFix = new WinFixBattle(cloneBattle);
  10564. let attempts = Infinity;
  10565. if (nameFuncStartBattle == 'invasion_bossStart' && !isSetWinTimer) {
  10566. let winTimer = await popup.confirm(`Secret number:`, [
  10567. { result: false, isClose: true },
  10568. { msg: 'Go', isInput: true, default: '0' },
  10569. ]);
  10570. winTimer = Number.parseFloat(winTimer);
  10571. if (winTimer) {
  10572. attempts = 5;
  10573. bFix.setWinTimer(winTimer);
  10574. }
  10575. isSetWinTimer = true;
  10576. }
  10577. let endTime = Date.now() + 6e4;
  10578. if (nameFuncStartBattle == 'invasion_bossStart') {
  10579. endTime = Date.now() + 6e4 * 4;
  10580. bFix.setMaxTimer(120.3);
  10581. }
  10582. const result = await bFix.start(endTime, attempts);
  10583. console.log(result);
  10584. if (result.value) {
  10585. endBattle(result, false);
  10586. return;
  10587. }
  10588. }
  10589. const countMaxBattle = getInput('countAutoBattle');
  10590. if (findCoeff) {
  10591. const coeff = calcCoeff(e, 'defenders');
  10592. setProgress(`${countBattle}/${countMaxBattle}, ${coeff}`);
  10593. if (coeff > findCoeff) {
  10594. endBattle(e, false);
  10595. return;
  10596. }
  10597. } else {
  10598. if (nameFuncStartBattle == 'invasion_bossStart') {
  10599. const bossLvl = lastBattleInfo.typeId >= 130 ? lastBattleInfo.typeId : '';
  10600. const justice = lastBattleInfo?.effects?.attackers?.percentInOutDamageModAndEnergyIncrease_any_99_100_300_99_1000_300 || 0;
  10601. setProgress(`${svgBoss} ${bossLvl} ${svgJustice} ${justice} <br>${svgAttempt} ${countBattle}/${countMaxBattle}`, false, () => {
  10602. stopAutoBattle = true;
  10603. });
  10604. await new Promise((resolve) => setTimeout(resolve, 5000));
  10605. } else {
  10606. setProgress(`${countBattle}/${countMaxBattle}`);
  10607. }
  10608. }
  10609. if (nameFuncStartBattle == 'towerStartBattle' ||
  10610. nameFuncStartBattle == 'bossAttack' ||
  10611. nameFuncStartBattle == 'invasion_bossStart') {
  10612. startBattle();
  10613. return;
  10614. }
  10615. cancelEndBattle(e);
  10616. }
  10617. /**
  10618. * Cancel fight
  10619. *
  10620. * Отмена боя
  10621. */
  10622. function cancelEndBattle(r) {
  10623. const fixBattle = function (heroes) {
  10624. for (const ids in heroes) {
  10625. hero = heroes[ids];
  10626. hero.energy = random(1, 999);
  10627. if (hero.hp > 0) {
  10628. hero.hp = random(1, hero.hp);
  10629. }
  10630. }
  10631. }
  10632. fixBattle(r.progress[0].attackers.heroes);
  10633. fixBattle(r.progress[0].defenders.heroes);
  10634. endBattle(r, true);
  10635. }
  10636. /**
  10637. * End of the fight
  10638. *
  10639. * Завершение боя */
  10640. function endBattle(battleResult, isCancal) {
  10641. let calls = [{
  10642. name: nameFuncEndBattle,
  10643. args: {
  10644. result: battleResult.result,
  10645. progress: battleResult.progress
  10646. },
  10647. ident: "body"
  10648. }];
  10649.  
  10650. if (nameFuncStartBattle == 'invasion_bossStart') {
  10651. calls[0].args.id = lastBattleArg.id;
  10652. }
  10653.  
  10654. send(JSON.stringify({
  10655. calls
  10656. }), async e => {
  10657. console.log(e);
  10658. if (isCancal) {
  10659. startBattle();
  10660. return;
  10661. }
  10662.  
  10663. setProgress(`${I18N('SUCCESS')}!`, 5000)
  10664. if (nameFuncStartBattle == 'invasion_bossStart' ||
  10665. nameFuncStartBattle == 'bossAttack') {
  10666. const countMaxBattle = getInput('countAutoBattle');
  10667. const bossLvl = lastBattleInfo.typeId >= 130 ? lastBattleInfo.typeId : '';
  10668. const justice = lastBattleInfo?.effects?.attackers?.percentInOutDamageModAndEnergyIncrease_any_99_100_300_99_1000_300 || 0;
  10669. let winTimer = '';
  10670. if (nameFuncStartBattle == 'invasion_bossStart') {
  10671. winTimer = '<br>Secret number: ' + battleResult.progress[0].attackers.input[5];
  10672. }
  10673. const result = await popup.confirm(
  10674. I18N('BOSS_HAS_BEEN_DEF_TEXT', {
  10675. bossLvl: `${svgBoss} ${bossLvl} ${svgJustice} ${justice}`,
  10676. countBattle: svgAttempt + ' ' + countBattle,
  10677. countMaxBattle,
  10678. winTimer,
  10679. }),
  10680. [
  10681. { msg: I18N('BTN_OK'), result: 0 },
  10682. { msg: I18N('MAKE_A_SYNC'), result: 1 },
  10683. { msg: I18N('RELOAD_GAME'), result: 2 },
  10684. ]
  10685. );
  10686. if (result) {
  10687. if (result == 1) {
  10688. cheats.refreshGame();
  10689. }
  10690. if (result == 2) {
  10691. location.reload();
  10692. }
  10693. }
  10694.  
  10695. }
  10696. endAutoBattle(`${I18N('SUCCESS')}!`)
  10697. });
  10698. }
  10699. /**
  10700. * Completing a task
  10701. *
  10702. * Завершение задачи
  10703. */
  10704. function endAutoBattle(reason, info) {
  10705. setIsCancalBattle(true);
  10706. console.log(reason, info);
  10707. resolve();
  10708. }
  10709. }
  10710.  
  10711. this.HWHClasses.executeAutoBattle = executeAutoBattle;
  10712.  
  10713. function testDailyQuests() {
  10714. const { dailyQuests } = HWHClasses;
  10715. return new Promise((resolve, reject) => {
  10716. const quests = new dailyQuests(resolve, reject);
  10717. quests.init(questsInfo);
  10718. quests.start();
  10719. });
  10720. }
  10721.  
  10722. /**
  10723. * Automatic completion of daily quests
  10724. *
  10725. * Автоматическое выполнение ежедневных квестов
  10726. */
  10727. class dailyQuests {
  10728. /**
  10729. * Send(' {"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}').then(e => console.log(e))
  10730. * Send(' {"calls":[{"name":"heroGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  10731. * Send(' {"calls":[{"name":"titanGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  10732. * Send(' {"calls":[{"name":"inventoryGet","args":{},"ident":"body"}]}').then(e => console.log(e))
  10733. * Send(' {"calls":[{"name":"questGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  10734. * Send(' {"calls":[{"name":"bossGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  10735. */
  10736. callsList = ['userGetInfo', 'heroGetAll', 'titanGetAll', 'inventoryGet', 'questGetAll', 'bossGetAll', 'missionGetAll'];
  10737.  
  10738. dataQuests = {
  10739. 10001: {
  10740. description: 'Улучши умения героев 3 раза', // ++++++++++++++++
  10741. doItCall: () => {
  10742. const upgradeSkills = this.getUpgradeSkills();
  10743. return upgradeSkills.map(({ heroId, skill }, index) => ({
  10744. name: 'heroUpgradeSkill',
  10745. args: { heroId, skill },
  10746. ident: `heroUpgradeSkill_${index}`,
  10747. }));
  10748. },
  10749. isWeCanDo: () => {
  10750. const upgradeSkills = this.getUpgradeSkills();
  10751. let sumGold = 0;
  10752. for (const skill of upgradeSkills) {
  10753. sumGold += this.skillCost(skill.value);
  10754. if (!skill.heroId) {
  10755. return false;
  10756. }
  10757. }
  10758. return this.questInfo['userGetInfo'].gold > sumGold;
  10759. },
  10760. },
  10761. 10002: {
  10762. description: 'Пройди 10 миссий', // --------------
  10763. isWeCanDo: () => false,
  10764. },
  10765. 10003: {
  10766. description: 'Пройди 3 героические миссии', // ++++++++++++++++
  10767. isWeCanDo: () => {
  10768. const vipPoints = +this.questInfo.userGetInfo.vipPoints;
  10769. const goldTicket = !!this.questInfo.inventoryGet.consumable[151];
  10770. return (vipPoints > 100 || goldTicket) && this.getHeroicMissionId();
  10771. },
  10772. doItCall: () => {
  10773. const selectedMissionId = this.getHeroicMissionId();
  10774. const goldTicket = !!this.questInfo.inventoryGet.consumable[151];
  10775. const vipLevel = Math.max(...lib.data.level.vip.filter(l => l.vipPoints <= +this.questInfo.userGetInfo.vipPoints).map(l => l.level));
  10776. // Возвращаем массив команд для рейда
  10777. if (vipLevel >= 5 || goldTicket) {
  10778. return [{ name: 'missionRaid', args: { id: selectedMissionId, times: 3 }, ident: 'missionRaid_1' }];
  10779. } else {
  10780. return [
  10781. { name: 'missionRaid', args: { id: selectedMissionId, times: 1 }, ident: 'missionRaid_1' },
  10782. { name: 'missionRaid', args: { id: selectedMissionId, times: 1 }, ident: 'missionRaid_2' },
  10783. { name: 'missionRaid', args: { id: selectedMissionId, times: 1 }, ident: 'missionRaid_3' },
  10784. ];
  10785. }
  10786. },
  10787. },
  10788. 10004: {
  10789. description: 'Сразись 3 раза на Арене или Гранд Арене', // --------------
  10790. isWeCanDo: () => false,
  10791. },
  10792. 10006: {
  10793. description: 'Используй обмен изумрудов 1 раз', // ++++++++++++++++
  10794. doItCall: () => [
  10795. {
  10796. name: 'refillableAlchemyUse',
  10797. args: { multi: false },
  10798. ident: 'refillableAlchemyUse',
  10799. },
  10800. ],
  10801. isWeCanDo: () => {
  10802. const starMoney = this.questInfo['userGetInfo'].starMoney;
  10803. return starMoney >= 20;
  10804. },
  10805. },
  10806. 10007: {
  10807. description: 'Соверши 1 призыв в Атриуме Душ', // ++++++++++++++++
  10808. doItCall: () => [{ name: 'gacha_open', args: { ident: 'heroGacha', free: true, pack: false }, ident: 'gacha_open' }],
  10809. isWeCanDo: () => {
  10810. const soulCrystal = this.questInfo['inventoryGet'].coin[38];
  10811. return soulCrystal > 0;
  10812. },
  10813. },
  10814. 10016: {
  10815. description: 'Отправь подарки согильдийцам', // ++++++++++++++++
  10816. doItCall: () => [{ name: 'clanSendDailyGifts', args: {}, ident: 'clanSendDailyGifts' }],
  10817. isWeCanDo: () => true,
  10818. },
  10819. 10018: {
  10820. description: 'Используй зелье опыта', // ++++++++++++++++
  10821. doItCall: () => {
  10822. const expHero = this.getExpHero();
  10823. return [
  10824. {
  10825. name: 'consumableUseHeroXp',
  10826. args: {
  10827. heroId: expHero.heroId,
  10828. libId: expHero.libId,
  10829. amount: 1,
  10830. },
  10831. ident: 'consumableUseHeroXp',
  10832. },
  10833. ];
  10834. },
  10835. isWeCanDo: () => {
  10836. const expHero = this.getExpHero();
  10837. return expHero.heroId && expHero.libId;
  10838. },
  10839. },
  10840. 10019: {
  10841. description: 'Открой 1 сундук в Башне',
  10842. doItFunc: testTower,
  10843. isWeCanDo: () => false,
  10844. },
  10845. 10020: {
  10846. description: 'Открой 3 сундука в Запределье', // Готово
  10847. doItCall: () => {
  10848. return this.getOutlandChest();
  10849. },
  10850. isWeCanDo: () => {
  10851. const outlandChest = this.getOutlandChest();
  10852. return outlandChest.length > 0;
  10853. },
  10854. },
  10855. 10021: {
  10856. description: 'Собери 75 Титанита в Подземелье Гильдии',
  10857. isWeCanDo: () => false,
  10858. },
  10859. 10022: {
  10860. description: 'Собери 150 Титанита в Подземелье Гильдии',
  10861. doItFunc: testDungeon,
  10862. isWeCanDo: () => false,
  10863. },
  10864. 10023: {
  10865. description: 'Прокачай Дар Стихий на 1 уровень', // Готово
  10866. doItCall: () => {
  10867. const heroId = this.getHeroIdTitanGift();
  10868. return [
  10869. { name: 'heroTitanGiftLevelUp', args: { heroId }, ident: 'heroTitanGiftLevelUp' },
  10870. { name: 'heroTitanGiftDrop', args: { heroId }, ident: 'heroTitanGiftDrop' },
  10871. ];
  10872. },
  10873. isWeCanDo: () => {
  10874. const heroId = this.getHeroIdTitanGift();
  10875. return heroId;
  10876. },
  10877. },
  10878. 10024: {
  10879. description: 'Повысь уровень любого артефакта один раз', // Готово
  10880. doItCall: () => {
  10881. const upArtifact = this.getUpgradeArtifact();
  10882. return [
  10883. {
  10884. name: 'heroArtifactLevelUp',
  10885. args: {
  10886. heroId: upArtifact.heroId,
  10887. slotId: upArtifact.slotId,
  10888. },
  10889. ident: `heroArtifactLevelUp`,
  10890. },
  10891. ];
  10892. },
  10893. isWeCanDo: () => {
  10894. const upgradeArtifact = this.getUpgradeArtifact();
  10895. return upgradeArtifact.heroId;
  10896. },
  10897. },
  10898. 10025: {
  10899. description: 'Начни 1 Экспедицию',
  10900. doItFunc: checkExpedition,
  10901. isWeCanDo: () => false,
  10902. },
  10903. 10026: {
  10904. description: 'Начни 4 Экспедиции', // --------------
  10905. doItFunc: checkExpedition,
  10906. isWeCanDo: () => false,
  10907. },
  10908. 10027: {
  10909. description: 'Победи в 1 бою Турнира Стихий',
  10910. doItFunc: testTitanArena,
  10911. isWeCanDo: () => false,
  10912. },
  10913. 10028: {
  10914. description: 'Повысь уровень любого артефакта титанов', // Готово
  10915. doItCall: () => {
  10916. const upTitanArtifact = this.getUpgradeTitanArtifact();
  10917. return [
  10918. {
  10919. name: 'titanArtifactLevelUp',
  10920. args: {
  10921. titanId: upTitanArtifact.titanId,
  10922. slotId: upTitanArtifact.slotId,
  10923. },
  10924. ident: `titanArtifactLevelUp`,
  10925. },
  10926. ];
  10927. },
  10928. isWeCanDo: () => {
  10929. const upgradeTitanArtifact = this.getUpgradeTitanArtifact();
  10930. return upgradeTitanArtifact.titanId;
  10931. },
  10932. },
  10933. 10029: {
  10934. description: 'Открой сферу артефактов титанов', // ++++++++++++++++
  10935. doItCall: () => [{ name: 'titanArtifactChestOpen', args: { amount: 1, free: true }, ident: 'titanArtifactChestOpen' }],
  10936. isWeCanDo: () => {
  10937. return this.questInfo['inventoryGet']?.consumable[55] > 0;
  10938. },
  10939. },
  10940. 10030: {
  10941. description: 'Улучши облик любого героя 1 раз', // Готово
  10942. doItCall: () => {
  10943. const upSkin = this.getUpgradeSkin();
  10944. return [
  10945. {
  10946. name: 'heroSkinUpgrade',
  10947. args: {
  10948. heroId: upSkin.heroId,
  10949. skinId: upSkin.skinId,
  10950. },
  10951. ident: `heroSkinUpgrade`,
  10952. },
  10953. ];
  10954. },
  10955. isWeCanDo: () => {
  10956. const upgradeSkin = this.getUpgradeSkin();
  10957. return upgradeSkin.heroId;
  10958. },
  10959. },
  10960. 10031: {
  10961. description: 'Победи в 6 боях Турнира Стихий', // --------------
  10962. doItFunc: testTitanArena,
  10963. isWeCanDo: () => false,
  10964. },
  10965. 10043: {
  10966. description: 'Начни или присоеденись к Приключению', // --------------
  10967. isWeCanDo: () => false,
  10968. },
  10969. 10044: {
  10970. description: 'Воспользуйся призывом питомцев 1 раз', // ++++++++++++++++
  10971. doItCall: () => [{ name: 'pet_chestOpen', args: { amount: 1, paid: false }, ident: 'pet_chestOpen' }],
  10972. isWeCanDo: () => {
  10973. return this.questInfo['inventoryGet']?.consumable[90] > 0;
  10974. },
  10975. },
  10976. 10046: {
  10977. /**
  10978. * TODO: Watch Adventure
  10979. * TODO: Смотреть приключение
  10980. */
  10981. description: 'Открой 3 сундука в Приключениях',
  10982. isWeCanDo: () => false,
  10983. },
  10984. 10047: {
  10985. description: 'Набери 150 очков активности в Гильдии', // Готово
  10986. doItCall: () => {
  10987. const enchantRune = this.getEnchantRune();
  10988. return [
  10989. {
  10990. name: 'heroEnchantRune',
  10991. args: {
  10992. heroId: enchantRune.heroId,
  10993. tier: enchantRune.tier,
  10994. items: {
  10995. consumable: { [enchantRune.itemId]: 1 },
  10996. },
  10997. },
  10998. ident: `heroEnchantRune`,
  10999. },
  11000. ];
  11001. },
  11002. isWeCanDo: () => {
  11003. const userInfo = this.questInfo['userGetInfo'];
  11004. const enchantRune = this.getEnchantRune();
  11005. return enchantRune.heroId && userInfo.gold > 1e3;
  11006. },
  11007. },
  11008. };
  11009.  
  11010. constructor(resolve, reject, questInfo) {
  11011. this.resolve = resolve;
  11012. this.reject = reject;
  11013. }
  11014.  
  11015. init(questInfo) {
  11016. this.questInfo = questInfo;
  11017. this.isAuto = false;
  11018. }
  11019.  
  11020. async autoInit(isAuto) {
  11021. this.isAuto = isAuto || false;
  11022. const quests = {};
  11023. const calls = this.callsList.map((name) => ({
  11024. name,
  11025. args: {},
  11026. ident: name,
  11027. }));
  11028. const result = await Send(JSON.stringify({ calls })).then((e) => e.results);
  11029. for (const call of result) {
  11030. quests[call.ident] = call.result.response;
  11031. }
  11032. this.questInfo = quests;
  11033. }
  11034.  
  11035. async start() {
  11036. const weCanDo = [];
  11037. const selectedActions = getSaveVal('selectedActions', {});
  11038. for (let quest of this.questInfo['questGetAll']) {
  11039. if (quest.id in this.dataQuests && quest.state == 1) {
  11040. if (!selectedActions[quest.id]) {
  11041. selectedActions[quest.id] = {
  11042. checked: false,
  11043. };
  11044. }
  11045.  
  11046. const isWeCanDo = this.dataQuests[quest.id].isWeCanDo;
  11047. if (!isWeCanDo.call(this)) {
  11048. continue;
  11049. }
  11050.  
  11051. weCanDo.push({
  11052. name: quest.id,
  11053. label: I18N(`QUEST_${quest.id}`),
  11054. checked: selectedActions[quest.id].checked,
  11055. });
  11056. }
  11057. }
  11058.  
  11059. if (!weCanDo.length) {
  11060. this.end(I18N('NOTHING_TO_DO'));
  11061. return;
  11062. }
  11063.  
  11064. console.log(weCanDo);
  11065. let taskList = [];
  11066. if (this.isAuto) {
  11067. taskList = weCanDo;
  11068. } else {
  11069. const answer = await popup.confirm(
  11070. `${I18N('YOU_CAN_COMPLETE')}:`,
  11071. [
  11072. { msg: I18N('BTN_DO_IT'), result: true },
  11073. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  11074. ],
  11075. weCanDo
  11076. );
  11077. if (!answer) {
  11078. this.end('');
  11079. return;
  11080. }
  11081. taskList = popup.getCheckBoxes();
  11082. taskList.forEach((e) => {
  11083. selectedActions[e.name].checked = e.checked;
  11084. });
  11085. setSaveVal('selectedActions', selectedActions);
  11086. }
  11087.  
  11088. const calls = [];
  11089. let countChecked = 0;
  11090. for (const task of taskList) {
  11091. if (task.checked) {
  11092. countChecked++;
  11093. const quest = this.dataQuests[task.name];
  11094. console.log(quest.description);
  11095.  
  11096. if (quest.doItCall) {
  11097. const doItCall = quest.doItCall.call(this);
  11098. calls.push(...doItCall);
  11099. }
  11100. }
  11101. }
  11102.  
  11103. if (!countChecked) {
  11104. this.end(I18N('NOT_QUEST_COMPLETED'));
  11105. return;
  11106. }
  11107.  
  11108. const result = await Send(JSON.stringify({ calls }));
  11109. if (result.error) {
  11110. console.error(result.error, result.error.call);
  11111. }
  11112. this.end(`${I18N('COMPLETED_QUESTS')}: ${countChecked}`);
  11113. }
  11114.  
  11115. errorHandling(error) {
  11116. //console.error(error);
  11117. let errorInfo = error.toString() + '\n';
  11118. try {
  11119. const errorStack = error.stack.split('\n');
  11120. const endStack = errorStack.map((e) => e.split('@')[0]).indexOf('testDoYourBest');
  11121. errorInfo += errorStack.slice(0, endStack).join('\n');
  11122. } catch (e) {
  11123. errorInfo += error.stack;
  11124. }
  11125. copyText(errorInfo);
  11126. }
  11127.  
  11128. skillCost(lvl) {
  11129. return 573 * lvl ** 0.9 + lvl ** 2.379;
  11130. }
  11131.  
  11132. getUpgradeSkills() {
  11133. const heroes = Object.values(this.questInfo['heroGetAll']);
  11134. const upgradeSkills = [
  11135. { heroId: 0, slotId: 0, value: 130 },
  11136. { heroId: 0, slotId: 0, value: 130 },
  11137. { heroId: 0, slotId: 0, value: 130 },
  11138. ];
  11139. const skillLib = lib.getData('skill');
  11140. /**
  11141. * color - 1 (белый) открывает 1 навык
  11142. * color - 2 (зеленый) открывает 2 навык
  11143. * color - 4 (синий) открывает 3 навык
  11144. * color - 7 (фиолетовый) открывает 4 навык
  11145. */
  11146. const colors = [1, 2, 4, 7];
  11147. for (const hero of heroes) {
  11148. const level = hero.level;
  11149. const color = hero.color;
  11150. for (let skillId in hero.skills) {
  11151. const tier = skillLib[skillId].tier;
  11152. const sVal = hero.skills[skillId];
  11153. if (color < colors[tier] || tier < 1 || tier > 4) {
  11154. continue;
  11155. }
  11156. for (let upSkill of upgradeSkills) {
  11157. if (sVal < upSkill.value && sVal < level) {
  11158. upSkill.value = sVal;
  11159. upSkill.heroId = hero.id;
  11160. upSkill.skill = tier;
  11161. break;
  11162. }
  11163. }
  11164. }
  11165. }
  11166. return upgradeSkills;
  11167. }
  11168.  
  11169. getUpgradeArtifact() {
  11170. const heroes = Object.values(this.questInfo['heroGetAll']);
  11171. const inventory = this.questInfo['inventoryGet'];
  11172. const upArt = { heroId: 0, slotId: 0, level: 100 };
  11173.  
  11174. const heroLib = lib.getData('hero');
  11175. const artifactLib = lib.getData('artifact');
  11176.  
  11177. for (const hero of heroes) {
  11178. const heroInfo = heroLib[hero.id];
  11179. const level = hero.level;
  11180. if (level < 20) {
  11181. continue;
  11182. }
  11183.  
  11184. for (let slotId in hero.artifacts) {
  11185. const art = hero.artifacts[slotId];
  11186. /* Текущая звезданость арта */
  11187. const star = art.star;
  11188. if (!star) {
  11189. continue;
  11190. }
  11191. /* Текущий уровень арта */
  11192. const level = art.level;
  11193. if (level >= 100) {
  11194. continue;
  11195. }
  11196. /* Идентификатор арта в библиотеке */
  11197. const artifactId = heroInfo.artifacts[slotId];
  11198. const artInfo = artifactLib.id[artifactId];
  11199. const costNextLevel = artifactLib.type[artInfo.type].levels[level + 1].cost;
  11200.  
  11201. const costCurrency = Object.keys(costNextLevel).pop();
  11202. const costValues = Object.entries(costNextLevel[costCurrency]).pop();
  11203. const costId = costValues[0];
  11204. const costValue = +costValues[1];
  11205.  
  11206. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  11207. if (level < upArt.level && inventory[costCurrency][costId] >= costValue) {
  11208. upArt.level = level;
  11209. upArt.heroId = hero.id;
  11210. upArt.slotId = slotId;
  11211. upArt.costCurrency = costCurrency;
  11212. upArt.costId = costId;
  11213. upArt.costValue = costValue;
  11214. }
  11215. }
  11216. }
  11217. return upArt;
  11218. }
  11219.  
  11220. getUpgradeSkin() {
  11221. const heroes = Object.values(this.questInfo['heroGetAll']);
  11222. const inventory = this.questInfo['inventoryGet'];
  11223. const upSkin = { heroId: 0, skinId: 0, level: 60, cost: 1500 };
  11224.  
  11225. const skinLib = lib.getData('skin');
  11226.  
  11227. for (const hero of heroes) {
  11228. const level = hero.level;
  11229. if (level < 20) {
  11230. continue;
  11231. }
  11232.  
  11233. for (let skinId in hero.skins) {
  11234. /* Текущий уровень скина */
  11235. const level = hero.skins[skinId];
  11236. if (level >= 60) {
  11237. continue;
  11238. }
  11239. /* Идентификатор скина в библиотеке */
  11240. const skinInfo = skinLib[skinId];
  11241. if (!skinInfo.statData.levels?.[level + 1]) {
  11242. continue;
  11243. }
  11244. const costNextLevel = skinInfo.statData.levels[level + 1].cost;
  11245.  
  11246. const costCurrency = Object.keys(costNextLevel).pop();
  11247. const costCurrencyId = Object.keys(costNextLevel[costCurrency]).pop();
  11248. const costValue = +costNextLevel[costCurrency][costCurrencyId];
  11249.  
  11250. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  11251. if (level < upSkin.level && costValue < upSkin.cost && inventory[costCurrency][costCurrencyId] >= costValue) {
  11252. upSkin.cost = costValue;
  11253. upSkin.level = level;
  11254. upSkin.heroId = hero.id;
  11255. upSkin.skinId = skinId;
  11256. upSkin.costCurrency = costCurrency;
  11257. upSkin.costCurrencyId = costCurrencyId;
  11258. }
  11259. }
  11260. }
  11261. return upSkin;
  11262. }
  11263.  
  11264. getUpgradeTitanArtifact() {
  11265. const titans = Object.values(this.questInfo['titanGetAll']);
  11266. const inventory = this.questInfo['inventoryGet'];
  11267. const userInfo = this.questInfo['userGetInfo'];
  11268. const upArt = { titanId: 0, slotId: 0, level: 120 };
  11269.  
  11270. const titanLib = lib.getData('titan');
  11271. const artTitanLib = lib.getData('titanArtifact');
  11272.  
  11273. for (const titan of titans) {
  11274. const titanInfo = titanLib[titan.id];
  11275. // const level = titan.level
  11276. // if (level < 20) {
  11277. // continue;
  11278. // }
  11279.  
  11280. for (let slotId in titan.artifacts) {
  11281. const art = titan.artifacts[slotId];
  11282. /* Текущая звезданость арта */
  11283. const star = art.star;
  11284. if (!star) {
  11285. continue;
  11286. }
  11287. /* Текущий уровень арта */
  11288. const level = art.level;
  11289. if (level >= 120) {
  11290. continue;
  11291. }
  11292. /* Идентификатор арта в библиотеке */
  11293. const artifactId = titanInfo.artifacts[slotId];
  11294. const artInfo = artTitanLib.id[artifactId];
  11295. const costNextLevel = artTitanLib.type[artInfo.type].levels[level + 1].cost;
  11296.  
  11297. const costCurrency = Object.keys(costNextLevel).pop();
  11298. let costValue = 0;
  11299. let currentValue = 0;
  11300. if (costCurrency == 'gold') {
  11301. costValue = costNextLevel[costCurrency];
  11302. currentValue = userInfo.gold;
  11303. } else {
  11304. const costValues = Object.entries(costNextLevel[costCurrency]).pop();
  11305. const costId = costValues[0];
  11306. costValue = +costValues[1];
  11307. currentValue = inventory[costCurrency][costId];
  11308. }
  11309.  
  11310. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  11311. if (level < upArt.level && currentValue >= costValue) {
  11312. upArt.level = level;
  11313. upArt.titanId = titan.id;
  11314. upArt.slotId = slotId;
  11315. break;
  11316. }
  11317. }
  11318. }
  11319. return upArt;
  11320. }
  11321.  
  11322. getEnchantRune() {
  11323. const heroes = Object.values(this.questInfo['heroGetAll']);
  11324. const inventory = this.questInfo['inventoryGet'];
  11325. const enchRune = { heroId: 0, tier: 0, exp: 43750, itemId: 0 };
  11326. for (let i = 1; i <= 4; i++) {
  11327. if (inventory.consumable[i] > 0) {
  11328. enchRune.itemId = i;
  11329. break;
  11330. }
  11331. return enchRune;
  11332. }
  11333.  
  11334. const runeLib = lib.getData('rune');
  11335. const runeLvls = Object.values(runeLib.level);
  11336. /**
  11337. * color - 4 (синий) открывает 1 и 2 символ
  11338. * color - 7 (фиолетовый) открывает 3 символ
  11339. * color - 8 (фиолетовый +1) открывает 4 символ
  11340. * color - 9 (фиолетовый +2) открывает 5 символ
  11341. */
  11342. // TODO: кажется надо учесть уровень команды
  11343. const colors = [4, 4, 7, 8, 9];
  11344. for (const hero of heroes) {
  11345. const color = hero.color;
  11346.  
  11347. for (let runeTier in hero.runes) {
  11348. /* Проверка на доступность руны */
  11349. if (color < colors[runeTier]) {
  11350. continue;
  11351. }
  11352. /* Текущий опыт руны */
  11353. const exp = hero.runes[runeTier];
  11354. if (exp >= 43750) {
  11355. continue;
  11356. }
  11357.  
  11358. let level = 0;
  11359. if (exp) {
  11360. for (let lvl of runeLvls) {
  11361. if (exp >= lvl.enchantValue) {
  11362. level = lvl.level;
  11363. } else {
  11364. break;
  11365. }
  11366. }
  11367. }
  11368. /** Уровень героя необходимый для уровня руны */
  11369. const heroLevel = runeLib.level[level].heroLevel;
  11370. if (hero.level < heroLevel) {
  11371. continue;
  11372. }
  11373.  
  11374. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  11375. if (exp < enchRune.exp) {
  11376. enchRune.exp = exp;
  11377. enchRune.heroId = hero.id;
  11378. enchRune.tier = runeTier;
  11379. break;
  11380. }
  11381. }
  11382. }
  11383. return enchRune;
  11384. }
  11385.  
  11386. getOutlandChest() {
  11387. const bosses = this.questInfo['bossGetAll'];
  11388.  
  11389. const calls = [];
  11390.  
  11391. for (let boss of bosses) {
  11392. if (boss.mayRaid) {
  11393. calls.push({
  11394. name: 'bossRaid',
  11395. args: {
  11396. bossId: boss.id,
  11397. },
  11398. ident: 'bossRaid_' + boss.id,
  11399. });
  11400. calls.push({
  11401. name: 'bossOpenChest',
  11402. args: {
  11403. bossId: boss.id,
  11404. amount: 1,
  11405. starmoney: 0,
  11406. },
  11407. ident: 'bossOpenChest_' + boss.id,
  11408. });
  11409. } else if (boss.chestId == 1) {
  11410. calls.push({
  11411. name: 'bossOpenChest',
  11412. args: {
  11413. bossId: boss.id,
  11414. amount: 1,
  11415. starmoney: 0,
  11416. },
  11417. ident: 'bossOpenChest_' + boss.id,
  11418. });
  11419. }
  11420. }
  11421.  
  11422. return calls;
  11423. }
  11424.  
  11425. getExpHero() {
  11426. const heroes = Object.values(this.questInfo['heroGetAll']);
  11427. const inventory = this.questInfo['inventoryGet'];
  11428. const expHero = { heroId: 0, exp: 3625195, libId: 0 };
  11429. /** зелья опыта (consumable 9, 10, 11, 12) */
  11430. for (let i = 9; i <= 12; i++) {
  11431. if (inventory.consumable[i]) {
  11432. expHero.libId = i;
  11433. break;
  11434. }
  11435. }
  11436.  
  11437. for (const hero of heroes) {
  11438. const exp = hero.xp;
  11439. if (exp < expHero.exp) {
  11440. expHero.heroId = hero.id;
  11441. }
  11442. }
  11443. return expHero;
  11444. }
  11445.  
  11446. getHeroIdTitanGift() {
  11447. const heroes = Object.values(this.questInfo['heroGetAll']);
  11448. const inventory = this.questInfo['inventoryGet'];
  11449. const user = this.questInfo['userGetInfo'];
  11450. const titanGiftLib = lib.getData('titanGift');
  11451. /** Искры */
  11452. const titanGift = inventory.consumable[24];
  11453. let heroId = 0;
  11454. let minLevel = 30;
  11455.  
  11456. if (titanGift < 250 || user.gold < 7000) {
  11457. return 0;
  11458. }
  11459.  
  11460. for (const hero of heroes) {
  11461. if (hero.titanGiftLevel >= 30) {
  11462. continue;
  11463. }
  11464.  
  11465. if (!hero.titanGiftLevel) {
  11466. return hero.id;
  11467. }
  11468.  
  11469. const cost = titanGiftLib[hero.titanGiftLevel].cost;
  11470. if (minLevel > hero.titanGiftLevel && titanGift >= cost.consumable[24] && user.gold >= cost.gold) {
  11471. minLevel = hero.titanGiftLevel;
  11472. heroId = hero.id;
  11473. }
  11474. }
  11475.  
  11476. return heroId;
  11477. }
  11478.  
  11479. getHeroicMissionId() {
  11480. // Получаем доступные миссии с 3 звездами
  11481. const availableMissionsToRaid = Object.values(this.questInfo.missionGetAll)
  11482. .filter((mission) => mission.stars === 3)
  11483. .map((mission) => mission.id);
  11484.  
  11485. // Получаем героев для улучшения, у которых меньше 6 звезд
  11486. const heroesToUpgrade = Object.values(this.questInfo.heroGetAll)
  11487. .filter((hero) => hero.star < 6)
  11488. .sort((a, b) => b.power - a.power)
  11489. .map((hero) => hero.id);
  11490.  
  11491. // Получаем героические миссии, которые доступны для рейдов
  11492. const heroicMissions = Object.values(lib.data.mission).filter((mission) => mission.isHeroic && availableMissionsToRaid.includes(mission.id));
  11493.  
  11494. // Собираем дропы из героических миссий
  11495. const drops = heroicMissions.map((mission) => {
  11496. const lastWave = mission.normalMode.waves[mission.normalMode.waves.length - 1];
  11497. const allRewards = lastWave.enemies[lastWave.enemies.length - 1]
  11498. .drop.map((drop) => drop.reward);
  11499.  
  11500. const heroId = +Object.keys(allRewards.find((reward) => reward.fragmentHero).fragmentHero).pop();
  11501.  
  11502. return { id: mission.id, heroId };
  11503. });
  11504.  
  11505. // Определяем, какие дропы подходят для героев, которых нужно улучшить
  11506. const heroDrops = heroesToUpgrade.map((heroId) => drops.find((drop) => drop.heroId == heroId)).filter((drop) => drop);
  11507. const firstMission = heroDrops[0];
  11508. // Выбираем миссию для рейда
  11509. const selectedMissionId = firstMission ? firstMission.id : 1;
  11510.  
  11511. const stamina = this.questInfo.userGetInfo.refillable.find((x) => x.id == 1).amount;
  11512. const costMissions = 3 * lib.data.mission[selectedMissionId].normalMode.teamExp;
  11513. if (stamina < costMissions) {
  11514. console.log('Энергии не достаточно');
  11515. return 0;
  11516. }
  11517. return selectedMissionId;
  11518. }
  11519.  
  11520. end(status) {
  11521. setProgress(status, true);
  11522. this.resolve();
  11523. }
  11524. }
  11525.  
  11526. this.questRun = dailyQuests;
  11527. this.HWHClasses.dailyQuests = dailyQuests;
  11528.  
  11529. function testDoYourBest() {
  11530. const { doYourBest } = HWHClasses;
  11531. return new Promise((resolve, reject) => {
  11532. const doIt = new doYourBest(resolve, reject);
  11533. doIt.start();
  11534. });
  11535. }
  11536.  
  11537. /**
  11538. * Do everything button
  11539. *
  11540. * Кнопка сделать все
  11541. */
  11542. class doYourBest {
  11543.  
  11544. funcList = [
  11545. {
  11546. name: 'getOutland',
  11547. label: I18N('ASSEMBLE_OUTLAND'),
  11548. checked: false
  11549. },
  11550. {
  11551. name: 'testTower',
  11552. label: I18N('PASS_THE_TOWER'),
  11553. checked: false
  11554. },
  11555. {
  11556. name: 'checkExpedition',
  11557. label: I18N('CHECK_EXPEDITIONS'),
  11558. checked: false
  11559. },
  11560. {
  11561. name: 'testTitanArena',
  11562. label: I18N('COMPLETE_TOE'),
  11563. checked: false
  11564. },
  11565. {
  11566. name: 'mailGetAll',
  11567. label: I18N('COLLECT_MAIL'),
  11568. checked: false
  11569. },
  11570. {
  11571. name: 'collectAllStuff',
  11572. label: I18N('COLLECT_MISC'),
  11573. title: I18N('COLLECT_MISC_TITLE'),
  11574. checked: false
  11575. },
  11576. {
  11577. name: 'getDailyBonus',
  11578. label: I18N('DAILY_BONUS'),
  11579. checked: false
  11580. },
  11581. {
  11582. name: 'dailyQuests',
  11583. label: I18N('DO_DAILY_QUESTS'),
  11584. checked: false
  11585. },
  11586. {
  11587. name: 'rollAscension',
  11588. label: I18N('SEER_TITLE'),
  11589. checked: false
  11590. },
  11591. {
  11592. name: 'questAllFarm',
  11593. label: I18N('COLLECT_QUEST_REWARDS'),
  11594. checked: false
  11595. },
  11596. {
  11597. name: 'testDungeon',
  11598. label: I18N('COMPLETE_DUNGEON'),
  11599. checked: false
  11600. },
  11601. {
  11602. name: 'synchronization',
  11603. label: I18N('MAKE_A_SYNC'),
  11604. checked: false
  11605. },
  11606. {
  11607. name: 'reloadGame',
  11608. label: I18N('RELOAD_GAME'),
  11609. checked: false
  11610. },
  11611. ];
  11612.  
  11613. functions = {
  11614. getOutland,
  11615. testTower,
  11616. checkExpedition,
  11617. testTitanArena,
  11618. mailGetAll,
  11619. collectAllStuff: async () => {
  11620. await offerFarmAllReward();
  11621. 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"}]}');
  11622. },
  11623. dailyQuests: async function () {
  11624. const quests = new dailyQuests(() => { }, () => { });
  11625. await quests.autoInit(true);
  11626. await quests.start();
  11627. },
  11628. rollAscension,
  11629. getDailyBonus,
  11630. questAllFarm,
  11631. testDungeon,
  11632. synchronization: async () => {
  11633. cheats.refreshGame();
  11634. },
  11635. reloadGame: async () => {
  11636. location.reload();
  11637. },
  11638. }
  11639.  
  11640. constructor(resolve, reject, questInfo) {
  11641. this.resolve = resolve;
  11642. this.reject = reject;
  11643. this.questInfo = questInfo
  11644. }
  11645.  
  11646. async start() {
  11647. const selectedDoIt = getSaveVal('selectedDoIt', {});
  11648.  
  11649. this.funcList.forEach(task => {
  11650. if (!selectedDoIt[task.name]) {
  11651. selectedDoIt[task.name] = {
  11652. checked: task.checked
  11653. }
  11654. } else {
  11655. task.checked = selectedDoIt[task.name].checked
  11656. }
  11657. });
  11658.  
  11659. const answer = await popup.confirm(I18N('RUN_FUNCTION'), [
  11660. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  11661. { msg: I18N('BTN_GO'), result: true },
  11662. ], this.funcList);
  11663.  
  11664. if (!answer) {
  11665. this.end('');
  11666. return;
  11667. }
  11668.  
  11669. const taskList = popup.getCheckBoxes();
  11670. taskList.forEach(task => {
  11671. selectedDoIt[task.name].checked = task.checked;
  11672. });
  11673. setSaveVal('selectedDoIt', selectedDoIt);
  11674. for (const task of popup.getCheckBoxes()) {
  11675. if (task.checked) {
  11676. try {
  11677. setProgress(`${task.label} <br>${I18N('PERFORMED')}!`);
  11678. await this.functions[task.name]();
  11679. setProgress(`${task.label} <br>${I18N('DONE')}!`);
  11680. } catch (error) {
  11681. if (await popup.confirm(`${I18N('ERRORS_OCCURRES')}:<br> ${task.label} <br>${I18N('COPY_ERROR')}?`, [
  11682. { msg: I18N('BTN_NO'), result: false },
  11683. { msg: I18N('BTN_YES'), result: true },
  11684. ])) {
  11685. this.errorHandling(error);
  11686. }
  11687. }
  11688. }
  11689. }
  11690. setTimeout((msg) => {
  11691. this.end(msg);
  11692. }, 2000, I18N('ALL_TASK_COMPLETED'));
  11693. return;
  11694. }
  11695.  
  11696. errorHandling(error) {
  11697. //console.error(error);
  11698. let errorInfo = error.toString() + '\n';
  11699. try {
  11700. const errorStack = error.stack.split('\n');
  11701. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testDoYourBest");
  11702. errorInfo += errorStack.slice(0, endStack).join('\n');
  11703. } catch (e) {
  11704. errorInfo += error.stack;
  11705. }
  11706. copyText(errorInfo);
  11707. }
  11708.  
  11709. end(status) {
  11710. setProgress(status, true);
  11711. this.resolve();
  11712. }
  11713. }
  11714.  
  11715. this.HWHClasses.doYourBest = doYourBest;
  11716.  
  11717. /**
  11718. * Passing the adventure along the specified route
  11719. *
  11720. * Прохождение приключения по указанному маршруту
  11721. */
  11722. function testAdventure(type) {
  11723. const { executeAdventure } = HWHClasses;
  11724. return new Promise((resolve, reject) => {
  11725. const bossBattle = new executeAdventure(resolve, reject);
  11726. bossBattle.start(type);
  11727. });
  11728. }
  11729.  
  11730. /**
  11731. * Passing the adventure along the specified route
  11732. *
  11733. * Прохождение приключения по указанному маршруту
  11734. */
  11735. class executeAdventure {
  11736.  
  11737. type = 'default';
  11738.  
  11739. actions = {
  11740. default: {
  11741. getInfo: "adventure_getInfo",
  11742. startBattle: 'adventure_turnStartBattle',
  11743. endBattle: 'adventure_endBattle',
  11744. collectBuff: 'adventure_turnCollectBuff'
  11745. },
  11746. solo: {
  11747. getInfo: "adventureSolo_getInfo",
  11748. startBattle: 'adventureSolo_turnStartBattle',
  11749. endBattle: 'adventureSolo_endBattle',
  11750. collectBuff: 'adventureSolo_turnCollectBuff'
  11751. }
  11752. }
  11753.  
  11754. terminatеReason = I18N('UNKNOWN');
  11755. callAdventureInfo = {
  11756. name: "adventure_getInfo",
  11757. args: {},
  11758. ident: "adventure_getInfo"
  11759. }
  11760. callTeamGetAll = {
  11761. name: "teamGetAll",
  11762. args: {},
  11763. ident: "teamGetAll"
  11764. }
  11765. callTeamGetFavor = {
  11766. name: "teamGetFavor",
  11767. args: {},
  11768. ident: "teamGetFavor"
  11769. }
  11770. callStartBattle = {
  11771. name: "adventure_turnStartBattle",
  11772. args: {},
  11773. ident: "body"
  11774. }
  11775. callEndBattle = {
  11776. name: "adventure_endBattle",
  11777. args: {
  11778. result: {},
  11779. progress: {},
  11780. },
  11781. ident: "body"
  11782. }
  11783. callCollectBuff = {
  11784. name: "adventure_turnCollectBuff",
  11785. args: {},
  11786. ident: "body"
  11787. }
  11788.  
  11789. constructor(resolve, reject) {
  11790. this.resolve = resolve;
  11791. this.reject = reject;
  11792. }
  11793.  
  11794. async start(type) {
  11795. this.type = type || this.type;
  11796. this.callAdventureInfo.name = this.actions[this.type].getInfo;
  11797. const data = await Send(JSON.stringify({
  11798. calls: [
  11799. this.callAdventureInfo,
  11800. this.callTeamGetAll,
  11801. this.callTeamGetFavor
  11802. ]
  11803. }));
  11804. return this.checkAdventureInfo(data.results);
  11805. }
  11806.  
  11807. async getPath() {
  11808. const oldVal = getSaveVal('adventurePath', '');
  11809. const keyPath = `adventurePath:${this.mapIdent}`;
  11810. const answer = await popup.confirm(I18N('ENTER_THE_PATH'), [
  11811. {
  11812. msg: I18N('START_ADVENTURE'),
  11813. placeholder: '1,2,3,4,5,6',
  11814. isInput: true,
  11815. default: getSaveVal(keyPath, oldVal)
  11816. },
  11817. {
  11818. msg: I18N('BTN_CANCEL'),
  11819. result: false,
  11820. isCancel: true
  11821. },
  11822. ]);
  11823. if (!answer) {
  11824. this.terminatеReason = I18N('BTN_CANCELED');
  11825. return false;
  11826. }
  11827.  
  11828. let path = answer.split(',');
  11829. if (path.length < 2) {
  11830. path = answer.split('-');
  11831. }
  11832. if (path.length < 2) {
  11833. this.terminatеReason = I18N('MUST_TWO_POINTS');
  11834. return false;
  11835. }
  11836.  
  11837. for (let p in path) {
  11838. path[p] = +path[p].trim()
  11839. if (Number.isNaN(path[p])) {
  11840. this.terminatеReason = I18N('MUST_ONLY_NUMBERS');
  11841. return false;
  11842. }
  11843. }
  11844.  
  11845. if (!this.checkPath(path)) {
  11846. return false;
  11847. }
  11848. setSaveVal(keyPath, answer);
  11849. return path;
  11850. }
  11851.  
  11852. checkPath(path) {
  11853. for (let i = 0; i < path.length - 1; i++) {
  11854. const currentPoint = path[i];
  11855. const nextPoint = path[i + 1];
  11856.  
  11857. const isValidPath = this.paths.some(p =>
  11858. (p.from_id === currentPoint && p.to_id === nextPoint) ||
  11859. (p.from_id === nextPoint && p.to_id === currentPoint)
  11860. );
  11861.  
  11862. if (!isValidPath) {
  11863. this.terminatеReason = I18N('INCORRECT_WAY', {
  11864. from: currentPoint,
  11865. to: nextPoint,
  11866. });
  11867. return false;
  11868. }
  11869. }
  11870.  
  11871. return true;
  11872. }
  11873.  
  11874. async checkAdventureInfo(data) {
  11875. this.advInfo = data[0].result.response;
  11876. if (!this.advInfo) {
  11877. this.terminatеReason = I18N('NOT_ON_AN_ADVENTURE') ;
  11878. return this.end();
  11879. }
  11880. const heroesTeam = data[1].result.response.adventure_hero;
  11881. const favor = data[2]?.result.response.adventure_hero;
  11882. const heroes = heroesTeam.slice(0, 5);
  11883. const pet = heroesTeam[5];
  11884. this.args = {
  11885. pet,
  11886. heroes,
  11887. favor,
  11888. path: [],
  11889. broadcast: false
  11890. }
  11891. const advUserInfo = this.advInfo.users[userInfo.id];
  11892. this.turnsLeft = advUserInfo.turnsLeft;
  11893. this.currentNode = advUserInfo.currentNode;
  11894. this.nodes = this.advInfo.nodes;
  11895. this.paths = this.advInfo.paths;
  11896. this.mapIdent = this.advInfo.mapIdent;
  11897.  
  11898. this.path = await this.getPath();
  11899. if (!this.path) {
  11900. return this.end();
  11901. }
  11902.  
  11903. if (this.currentNode == 1 && this.path[0] != 1) {
  11904. this.path.unshift(1);
  11905. }
  11906.  
  11907. return this.loop();
  11908. }
  11909.  
  11910. async loop() {
  11911. const position = this.path.indexOf(+this.currentNode);
  11912. if (!(~position)) {
  11913. this.terminatеReason = I18N('YOU_IN_NOT_ON_THE_WAY');
  11914. return this.end();
  11915. }
  11916. this.path = this.path.slice(position);
  11917. if ((this.path.length - 1) > this.turnsLeft &&
  11918. await popup.confirm(I18N('ATTEMPTS_NOT_ENOUGH'), [
  11919. { msg: I18N('YES_CONTINUE'), result: false },
  11920. { msg: I18N('BTN_NO'), result: true },
  11921. ])) {
  11922. this.terminatеReason = I18N('NOT_ENOUGH_AP');
  11923. return this.end();
  11924. }
  11925. const toPath = [];
  11926. for (const nodeId of this.path) {
  11927. if (!this.turnsLeft) {
  11928. this.terminatеReason = I18N('ATTEMPTS_ARE_OVER');
  11929. return this.end();
  11930. }
  11931. toPath.push(nodeId);
  11932. console.log(toPath);
  11933. if (toPath.length > 1) {
  11934. setProgress(toPath.join(' > ') + ` ${I18N('MOVES')}: ` + this.turnsLeft);
  11935. }
  11936. if (nodeId == this.currentNode) {
  11937. continue;
  11938. }
  11939.  
  11940. const nodeInfo = this.getNodeInfo(nodeId);
  11941. if (nodeInfo.type == 'TYPE_COMBAT') {
  11942. if (nodeInfo.state == 'empty') {
  11943. this.turnsLeft--;
  11944. continue;
  11945. }
  11946.  
  11947. /**
  11948. * Disable regular battle cancellation
  11949. *
  11950. * Отключаем штатную отменую боя
  11951. */
  11952. setIsCancalBattle(false);
  11953. if (await this.battle(toPath)) {
  11954. this.turnsLeft--;
  11955. toPath.splice(0, toPath.indexOf(nodeId));
  11956. nodeInfo.state = 'empty';
  11957. setIsCancalBattle(true);
  11958. continue;
  11959. }
  11960. setIsCancalBattle(true);
  11961. return this.end()
  11962. }
  11963.  
  11964. if (nodeInfo.type == 'TYPE_PLAYERBUFF') {
  11965. const buff = this.checkBuff(nodeInfo);
  11966. if (buff == null) {
  11967. continue;
  11968. }
  11969.  
  11970. if (await this.collectBuff(buff, toPath)) {
  11971. this.turnsLeft--;
  11972. toPath.splice(0, toPath.indexOf(nodeId));
  11973. continue;
  11974. }
  11975. this.terminatеReason = I18N('BUFF_GET_ERROR');
  11976. return this.end();
  11977. }
  11978. }
  11979. this.terminatеReason = I18N('SUCCESS');
  11980. return this.end();
  11981. }
  11982.  
  11983. /**
  11984. * Carrying out a fight
  11985. *
  11986. * Проведение боя
  11987. */
  11988. async battle(path, preCalc = true) {
  11989. const data = await this.startBattle(path);
  11990. try {
  11991. const battle = data.results[0].result.response.battle;
  11992. const result = await Calc(battle);
  11993. if (result.result.win) {
  11994. const info = await this.endBattle(result);
  11995. if (info.results[0].result.response?.error) {
  11996. this.terminatеReason = I18N('BATTLE_END_ERROR');
  11997. return false;
  11998. }
  11999. } else {
  12000. await this.cancelBattle(result);
  12001.  
  12002. if (preCalc && await this.preCalcBattle(battle)) {
  12003. path = path.slice(-2);
  12004. for (let i = 1; i <= getInput('countAutoBattle'); i++) {
  12005. setProgress(`${I18N('AUTOBOT')}: ${i}/${getInput('countAutoBattle')}`);
  12006. const result = await this.battle(path, false);
  12007. if (result) {
  12008. setProgress(I18N('VICTORY'));
  12009. return true;
  12010. }
  12011. }
  12012. this.terminatеReason = I18N('FAILED_TO_WIN_AUTO');
  12013. return false;
  12014. }
  12015. return false;
  12016. }
  12017. } catch (error) {
  12018. console.error(error);
  12019. if (await popup.confirm(I18N('ERROR_OF_THE_BATTLE_COPY'), [
  12020. { msg: I18N('BTN_NO'), result: false },
  12021. { msg: I18N('BTN_YES'), result: true },
  12022. ])) {
  12023. this.errorHandling(error, data);
  12024. }
  12025. this.terminatеReason = I18N('ERROR_DURING_THE_BATTLE');
  12026. return false;
  12027. }
  12028. return true;
  12029. }
  12030.  
  12031. /**
  12032. * Recalculate battles
  12033. *
  12034. * Прерасчтет битвы
  12035. */
  12036. async preCalcBattle(battle) {
  12037. const countTestBattle = getInput('countTestBattle');
  12038. for (let i = 0; i < countTestBattle; i++) {
  12039. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  12040. const result = await Calc(battle);
  12041. if (result.result.win) {
  12042. console.log(i, countTestBattle);
  12043. return true;
  12044. }
  12045. }
  12046. this.terminatеReason = I18N('NO_CHANCE_WIN') + countTestBattle;
  12047. return false;
  12048. }
  12049.  
  12050. /**
  12051. * Starts a fight
  12052. *
  12053. * Начинает бой
  12054. */
  12055. startBattle(path) {
  12056. this.args.path = path;
  12057. this.callStartBattle.name = this.actions[this.type].startBattle;
  12058. this.callStartBattle.args = this.args
  12059. const calls = [this.callStartBattle];
  12060. return Send(JSON.stringify({ calls }));
  12061. }
  12062.  
  12063. cancelBattle(battle) {
  12064. const fixBattle = function (heroes) {
  12065. for (const ids in heroes) {
  12066. const hero = heroes[ids];
  12067. hero.energy = random(1, 999);
  12068. if (hero.hp > 0) {
  12069. hero.hp = random(1, hero.hp);
  12070. }
  12071. }
  12072. }
  12073. fixBattle(battle.progress[0].attackers.heroes);
  12074. fixBattle(battle.progress[0].defenders.heroes);
  12075. return this.endBattle(battle);
  12076. }
  12077.  
  12078. /**
  12079. * Ends the fight
  12080. *
  12081. * Заканчивает бой
  12082. */
  12083. endBattle(battle) {
  12084. this.callEndBattle.name = this.actions[this.type].endBattle;
  12085. this.callEndBattle.args.result = battle.result
  12086. this.callEndBattle.args.progress = battle.progress
  12087. const calls = [this.callEndBattle];
  12088. return Send(JSON.stringify({ calls }));
  12089. }
  12090.  
  12091. /**
  12092. * Checks if you can get a buff
  12093. *
  12094. * Проверяет можно ли получить баф
  12095. */
  12096. checkBuff(nodeInfo) {
  12097. let id = null;
  12098. let value = 0;
  12099. for (const buffId in nodeInfo.buffs) {
  12100. const buff = nodeInfo.buffs[buffId];
  12101. if (buff.owner == null && buff.value > value) {
  12102. id = buffId;
  12103. value = buff.value;
  12104. }
  12105. }
  12106. nodeInfo.buffs[id].owner = 'Я';
  12107. return id;
  12108. }
  12109.  
  12110. /**
  12111. * Collects a buff
  12112. *
  12113. * Собирает баф
  12114. */
  12115. async collectBuff(buff, path) {
  12116. this.callCollectBuff.name = this.actions[this.type].collectBuff;
  12117. this.callCollectBuff.args = { buff, path };
  12118. const calls = [this.callCollectBuff];
  12119. return Send(JSON.stringify({ calls }));
  12120. }
  12121.  
  12122. getNodeInfo(nodeId) {
  12123. return this.nodes.find(node => node.id == nodeId);
  12124. }
  12125.  
  12126. errorHandling(error, data) {
  12127. //console.error(error);
  12128. let errorInfo = error.toString() + '\n';
  12129. try {
  12130. const errorStack = error.stack.split('\n');
  12131. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testAdventure");
  12132. errorInfo += errorStack.slice(0, endStack).join('\n');
  12133. } catch (e) {
  12134. errorInfo += error.stack;
  12135. }
  12136. if (data) {
  12137. errorInfo += '\nData: ' + JSON.stringify(data);
  12138. }
  12139. copyText(errorInfo);
  12140. }
  12141.  
  12142. end() {
  12143. setIsCancalBattle(true);
  12144. setProgress(this.terminatеReason, true);
  12145. console.log(this.terminatеReason);
  12146. this.resolve();
  12147. }
  12148. }
  12149.  
  12150. this.HWHClasses.executeAdventure = executeAdventure;
  12151.  
  12152. /**
  12153. * Passage of brawls
  12154. *
  12155. * Прохождение потасовок
  12156. */
  12157. function testBrawls(isAuto) {
  12158. const { executeBrawls } = HWHClasses;
  12159. return new Promise((resolve, reject) => {
  12160. const brawls = new executeBrawls(resolve, reject);
  12161. brawls.start(brawlsPack, isAuto);
  12162. });
  12163. }
  12164. /**
  12165. * Passage of brawls
  12166. *
  12167. * Прохождение потасовок
  12168. */
  12169. class executeBrawls {
  12170. callBrawlQuestGetInfo = {
  12171. name: "brawl_questGetInfo",
  12172. args: {},
  12173. ident: "brawl_questGetInfo"
  12174. }
  12175. callBrawlFindEnemies = {
  12176. name: "brawl_findEnemies",
  12177. args: {},
  12178. ident: "brawl_findEnemies"
  12179. }
  12180. callBrawlQuestFarm = {
  12181. name: "brawl_questFarm",
  12182. args: {},
  12183. ident: "brawl_questFarm"
  12184. }
  12185. callUserGetInfo = {
  12186. name: "userGetInfo",
  12187. args: {},
  12188. ident: "userGetInfo"
  12189. }
  12190. callTeamGetMaxUpgrade = {
  12191. name: "teamGetMaxUpgrade",
  12192. args: {},
  12193. ident: "teamGetMaxUpgrade"
  12194. }
  12195. callBrawlGetInfo = {
  12196. name: "brawl_getInfo",
  12197. args: {},
  12198. ident: "brawl_getInfo"
  12199. }
  12200.  
  12201. stats = {
  12202. win: 0,
  12203. loss: 0,
  12204. count: 0,
  12205. }
  12206.  
  12207. stage = {
  12208. '3': 1,
  12209. '7': 2,
  12210. '12': 3,
  12211. }
  12212.  
  12213. attempts = 0;
  12214.  
  12215. constructor(resolve, reject) {
  12216. this.resolve = resolve;
  12217. this.reject = reject;
  12218.  
  12219. const allHeroIds = Object.keys(lib.getData('hero'));
  12220. this.callTeamGetMaxUpgrade.args.units = {
  12221. hero: allHeroIds.filter((id) => +id < 1000),
  12222. titan: allHeroIds.filter((id) => +id >= 4000 && +id < 4100),
  12223. pet: allHeroIds.filter((id) => +id >= 6000 && +id < 6100),
  12224. };
  12225. }
  12226.  
  12227. async start(args, isAuto) {
  12228. this.isAuto = isAuto;
  12229. this.args = args;
  12230. setIsCancalBattle(false);
  12231. this.brawlInfo = await this.getBrawlInfo();
  12232. this.attempts = this.brawlInfo.attempts;
  12233.  
  12234. if (!this.attempts && !this.info.boughtEndlessLivesToday) {
  12235. this.end(I18N('DONT_HAVE_LIVES'));
  12236. return;
  12237. }
  12238.  
  12239. while (1) {
  12240. if (!isBrawlsAutoStart) {
  12241. this.end(I18N('BTN_CANCELED'));
  12242. return;
  12243. }
  12244.  
  12245. const maxStage = this.brawlInfo.questInfo.stage;
  12246. const stage = this.stage[maxStage];
  12247. const progress = this.brawlInfo.questInfo.progress;
  12248.  
  12249. setProgress(
  12250. `${I18N('STAGE')} ${stage}: ${progress}/${maxStage}<br>${I18N('FIGHTS')}: ${this.stats.count}<br>${I18N('WINS')}: ${
  12251. this.stats.win
  12252. }<br>${I18N('LOSSES')}: ${this.stats.loss}<br>${I18N('LIVES')}: ${this.attempts}<br>${I18N('STOP')}`,
  12253. false,
  12254. function () {
  12255. isBrawlsAutoStart = false;
  12256. }
  12257. );
  12258.  
  12259. if (this.brawlInfo.questInfo.canFarm) {
  12260. const result = await this.questFarm();
  12261. console.log(result);
  12262. }
  12263.  
  12264. if (!this.continueAttack && this.brawlInfo.questInfo.stage == 12 && this.brawlInfo.questInfo.progress == 12) {
  12265. if (
  12266. await popup.confirm(I18N('BRAWL_DAILY_TASK_COMPLETED'), [
  12267. { msg: I18N('BTN_NO'), result: true },
  12268. { msg: I18N('BTN_YES'), result: false },
  12269. ])
  12270. ) {
  12271. this.end(I18N('SUCCESS'));
  12272. return;
  12273. } else {
  12274. this.continueAttack = true;
  12275. }
  12276. }
  12277.  
  12278. if (!this.attempts && !this.info.boughtEndlessLivesToday) {
  12279. this.end(I18N('DONT_HAVE_LIVES'));
  12280. return;
  12281. }
  12282.  
  12283. const enemie = Object.values(this.brawlInfo.findEnemies).shift();
  12284.  
  12285. // Автоматический подбор пачки
  12286. if (this.isAuto) {
  12287. if (this.mandatoryId <= 4000 && this.mandatoryId != 13) {
  12288. this.end(I18N('BRAWL_AUTO_PACK_NOT_CUR_HERO'));
  12289. return;
  12290. }
  12291. if (this.mandatoryId >= 4000 && this.mandatoryId < 4100) {
  12292. this.args = await this.updateTitanPack(enemie.heroes);
  12293. } else if (this.mandatoryId < 4000 && this.mandatoryId == 13) {
  12294. this.args = await this.updateHeroesPack(enemie.heroes);
  12295. }
  12296. }
  12297.  
  12298. const result = await this.battle(enemie.userId);
  12299. this.brawlInfo = {
  12300. questInfo: result[1].result.response,
  12301. findEnemies: result[2].result.response,
  12302. };
  12303. }
  12304. }
  12305.  
  12306. async updateTitanPack(enemieHeroes) {
  12307. const packs = [
  12308. [4033, 4040, 4041, 4042, 4043],
  12309. [4032, 4040, 4041, 4042, 4043],
  12310. [4031, 4040, 4041, 4042, 4043],
  12311. [4030, 4040, 4041, 4042, 4043],
  12312. [4032, 4033, 4040, 4042, 4043],
  12313. [4030, 4033, 4041, 4042, 4043],
  12314. [4031, 4033, 4040, 4042, 4043],
  12315. [4032, 4033, 4040, 4041, 4043],
  12316. [4023, 4040, 4041, 4042, 4043],
  12317. [4030, 4033, 4040, 4042, 4043],
  12318. [4031, 4033, 4040, 4041, 4043],
  12319. [4022, 4040, 4041, 4042, 4043],
  12320. [4030, 4033, 4040, 4041, 4043],
  12321. [4021, 4040, 4041, 4042, 4043],
  12322. [4020, 4040, 4041, 4042, 4043],
  12323. [4023, 4033, 4040, 4042, 4043],
  12324. [4030, 4032, 4033, 4042, 4043],
  12325. [4023, 4033, 4040, 4041, 4043],
  12326. [4031, 4032, 4033, 4040, 4043],
  12327. [4030, 4032, 4033, 4041, 4043],
  12328. [4030, 4031, 4033, 4042, 4043],
  12329. [4013, 4040, 4041, 4042, 4043],
  12330. [4030, 4032, 4033, 4040, 4043],
  12331. [4030, 4031, 4033, 4041, 4043],
  12332. [4012, 4040, 4041, 4042, 4043],
  12333. [4030, 4031, 4033, 4040, 4043],
  12334. [4011, 4040, 4041, 4042, 4043],
  12335. [4010, 4040, 4041, 4042, 4043],
  12336. [4023, 4032, 4033, 4042, 4043],
  12337. [4022, 4032, 4033, 4042, 4043],
  12338. [4023, 4032, 4033, 4041, 4043],
  12339. [4021, 4032, 4033, 4042, 4043],
  12340. [4022, 4032, 4033, 4041, 4043],
  12341. [4023, 4030, 4033, 4042, 4043],
  12342. [4023, 4032, 4033, 4040, 4043],
  12343. [4013, 4033, 4040, 4042, 4043],
  12344. [4020, 4032, 4033, 4042, 4043],
  12345. [4021, 4032, 4033, 4041, 4043],
  12346. [4022, 4030, 4033, 4042, 4043],
  12347. [4022, 4032, 4033, 4040, 4043],
  12348. [4023, 4030, 4033, 4041, 4043],
  12349. [4023, 4031, 4033, 4040, 4043],
  12350. [4013, 4033, 4040, 4041, 4043],
  12351. [4020, 4031, 4033, 4042, 4043],
  12352. [4020, 4032, 4033, 4041, 4043],
  12353. [4021, 4030, 4033, 4042, 4043],
  12354. [4021, 4032, 4033, 4040, 4043],
  12355. [4022, 4030, 4033, 4041, 4043],
  12356. [4022, 4031, 4033, 4040, 4043],
  12357. [4023, 4030, 4033, 4040, 4043],
  12358. [4030, 4031, 4032, 4033, 4043],
  12359. [4003, 4040, 4041, 4042, 4043],
  12360. [4020, 4030, 4033, 4042, 4043],
  12361. [4020, 4031, 4033, 4041, 4043],
  12362. [4020, 4032, 4033, 4040, 4043],
  12363. [4021, 4030, 4033, 4041, 4043],
  12364. [4021, 4031, 4033, 4040, 4043],
  12365. [4022, 4030, 4033, 4040, 4043],
  12366. [4030, 4031, 4032, 4033, 4042],
  12367. [4002, 4040, 4041, 4042, 4043],
  12368. [4020, 4030, 4033, 4041, 4043],
  12369. [4020, 4031, 4033, 4040, 4043],
  12370. [4021, 4030, 4033, 4040, 4043],
  12371. [4030, 4031, 4032, 4033, 4041],
  12372. [4001, 4040, 4041, 4042, 4043],
  12373. [4030, 4031, 4032, 4033, 4040],
  12374. [4000, 4040, 4041, 4042, 4043],
  12375. [4013, 4032, 4033, 4042, 4043],
  12376. [4012, 4032, 4033, 4042, 4043],
  12377. [4013, 4032, 4033, 4041, 4043],
  12378. [4023, 4031, 4032, 4033, 4043],
  12379. [4011, 4032, 4033, 4042, 4043],
  12380. [4012, 4032, 4033, 4041, 4043],
  12381. [4013, 4030, 4033, 4042, 4043],
  12382. [4013, 4032, 4033, 4040, 4043],
  12383. [4023, 4030, 4032, 4033, 4043],
  12384. [4003, 4033, 4040, 4042, 4043],
  12385. [4013, 4023, 4040, 4042, 4043],
  12386. [4010, 4032, 4033, 4042, 4043],
  12387. [4011, 4032, 4033, 4041, 4043],
  12388. [4012, 4030, 4033, 4042, 4043],
  12389. [4012, 4032, 4033, 4040, 4043],
  12390. [4013, 4030, 4033, 4041, 4043],
  12391. [4013, 4031, 4033, 4040, 4043],
  12392. [4023, 4030, 4031, 4033, 4043],
  12393. [4003, 4033, 4040, 4041, 4043],
  12394. [4013, 4023, 4040, 4041, 4043],
  12395. [4010, 4031, 4033, 4042, 4043],
  12396. [4010, 4032, 4033, 4041, 4043],
  12397. [4011, 4030, 4033, 4042, 4043],
  12398. [4011, 4032, 4033, 4040, 4043],
  12399. [4012, 4030, 4033, 4041, 4043],
  12400. [4012, 4031, 4033, 4040, 4043],
  12401. [4013, 4030, 4033, 4040, 4043],
  12402. [4010, 4030, 4033, 4042, 4043],
  12403. [4010, 4031, 4033, 4041, 4043],
  12404. [4010, 4032, 4033, 4040, 4043],
  12405. [4011, 4030, 4033, 4041, 4043],
  12406. [4011, 4031, 4033, 4040, 4043],
  12407. [4012, 4030, 4033, 4040, 4043],
  12408. [4010, 4030, 4033, 4041, 4043],
  12409. [4010, 4031, 4033, 4040, 4043],
  12410. [4011, 4030, 4033, 4040, 4043],
  12411. [4003, 4032, 4033, 4042, 4043],
  12412. [4002, 4032, 4033, 4042, 4043],
  12413. [4003, 4032, 4033, 4041, 4043],
  12414. [4013, 4031, 4032, 4033, 4043],
  12415. [4001, 4032, 4033, 4042, 4043],
  12416. [4002, 4032, 4033, 4041, 4043],
  12417. [4003, 4030, 4033, 4042, 4043],
  12418. [4003, 4032, 4033, 4040, 4043],
  12419. [4013, 4030, 4032, 4033, 4043],
  12420. [4003, 4023, 4040, 4042, 4043],
  12421. [4000, 4032, 4033, 4042, 4043],
  12422. [4001, 4032, 4033, 4041, 4043],
  12423. [4002, 4030, 4033, 4042, 4043],
  12424. [4002, 4032, 4033, 4040, 4043],
  12425. [4003, 4030, 4033, 4041, 4043],
  12426. [4003, 4031, 4033, 4040, 4043],
  12427. [4020, 4022, 4023, 4042, 4043],
  12428. [4013, 4030, 4031, 4033, 4043],
  12429. [4003, 4023, 4040, 4041, 4043],
  12430. [4000, 4031, 4033, 4042, 4043],
  12431. [4000, 4032, 4033, 4041, 4043],
  12432. [4001, 4030, 4033, 4042, 4043],
  12433. [4001, 4032, 4033, 4040, 4043],
  12434. [4002, 4030, 4033, 4041, 4043],
  12435. [4002, 4031, 4033, 4040, 4043],
  12436. [4003, 4030, 4033, 4040, 4043],
  12437. [4021, 4022, 4023, 4040, 4043],
  12438. [4020, 4022, 4023, 4041, 4043],
  12439. [4020, 4021, 4023, 4042, 4043],
  12440. [4023, 4030, 4031, 4032, 4033],
  12441. [4000, 4030, 4033, 4042, 4043],
  12442. [4000, 4031, 4033, 4041, 4043],
  12443. [4000, 4032, 4033, 4040, 4043],
  12444. [4001, 4030, 4033, 4041, 4043],
  12445. [4001, 4031, 4033, 4040, 4043],
  12446. [4002, 4030, 4033, 4040, 4043],
  12447. [4020, 4022, 4023, 4040, 4043],
  12448. [4020, 4021, 4023, 4041, 4043],
  12449. [4022, 4030, 4031, 4032, 4033],
  12450. [4000, 4030, 4033, 4041, 4043],
  12451. [4000, 4031, 4033, 4040, 4043],
  12452. [4001, 4030, 4033, 4040, 4043],
  12453. [4020, 4021, 4023, 4040, 4043],
  12454. [4021, 4030, 4031, 4032, 4033],
  12455. [4020, 4030, 4031, 4032, 4033],
  12456. [4003, 4031, 4032, 4033, 4043],
  12457. [4020, 4022, 4023, 4033, 4043],
  12458. [4003, 4030, 4032, 4033, 4043],
  12459. [4003, 4013, 4040, 4042, 4043],
  12460. [4020, 4021, 4023, 4033, 4043],
  12461. [4003, 4030, 4031, 4033, 4043],
  12462. [4003, 4013, 4040, 4041, 4043],
  12463. [4013, 4030, 4031, 4032, 4033],
  12464. [4012, 4030, 4031, 4032, 4033],
  12465. [4011, 4030, 4031, 4032, 4033],
  12466. [4010, 4030, 4031, 4032, 4033],
  12467. [4013, 4023, 4031, 4032, 4033],
  12468. [4013, 4023, 4030, 4032, 4033],
  12469. [4020, 4022, 4023, 4032, 4033],
  12470. [4013, 4023, 4030, 4031, 4033],
  12471. [4021, 4022, 4023, 4030, 4033],
  12472. [4020, 4022, 4023, 4031, 4033],
  12473. [4020, 4021, 4023, 4032, 4033],
  12474. [4020, 4021, 4022, 4023, 4043],
  12475. [4003, 4030, 4031, 4032, 4033],
  12476. [4020, 4022, 4023, 4030, 4033],
  12477. [4020, 4021, 4023, 4031, 4033],
  12478. [4020, 4021, 4022, 4023, 4042],
  12479. [4002, 4030, 4031, 4032, 4033],
  12480. [4020, 4021, 4023, 4030, 4033],
  12481. [4020, 4021, 4022, 4023, 4041],
  12482. [4001, 4030, 4031, 4032, 4033],
  12483. [4020, 4021, 4022, 4023, 4040],
  12484. [4000, 4030, 4031, 4032, 4033],
  12485. [4003, 4023, 4031, 4032, 4033],
  12486. [4013, 4020, 4022, 4023, 4043],
  12487. [4003, 4023, 4030, 4032, 4033],
  12488. [4010, 4012, 4013, 4042, 4043],
  12489. [4013, 4020, 4021, 4023, 4043],
  12490. [4003, 4023, 4030, 4031, 4033],
  12491. [4011, 4012, 4013, 4040, 4043],
  12492. [4010, 4012, 4013, 4041, 4043],
  12493. [4010, 4011, 4013, 4042, 4043],
  12494. [4020, 4021, 4022, 4023, 4033],
  12495. [4010, 4012, 4013, 4040, 4043],
  12496. [4010, 4011, 4013, 4041, 4043],
  12497. [4020, 4021, 4022, 4023, 4032],
  12498. [4010, 4011, 4013, 4040, 4043],
  12499. [4020, 4021, 4022, 4023, 4031],
  12500. [4020, 4021, 4022, 4023, 4030],
  12501. [4003, 4013, 4031, 4032, 4033],
  12502. [4010, 4012, 4013, 4033, 4043],
  12503. [4003, 4020, 4022, 4023, 4043],
  12504. [4013, 4020, 4022, 4023, 4033],
  12505. [4003, 4013, 4030, 4032, 4033],
  12506. [4010, 4011, 4013, 4033, 4043],
  12507. [4003, 4020, 4021, 4023, 4043],
  12508. [4013, 4020, 4021, 4023, 4033],
  12509. [4003, 4013, 4030, 4031, 4033],
  12510. [4010, 4012, 4013, 4023, 4043],
  12511. [4003, 4020, 4022, 4023, 4033],
  12512. [4010, 4012, 4013, 4032, 4033],
  12513. [4010, 4011, 4013, 4023, 4043],
  12514. [4003, 4020, 4021, 4023, 4033],
  12515. [4011, 4012, 4013, 4030, 4033],
  12516. [4010, 4012, 4013, 4031, 4033],
  12517. [4010, 4011, 4013, 4032, 4033],
  12518. [4013, 4020, 4021, 4022, 4023],
  12519. [4010, 4012, 4013, 4030, 4033],
  12520. [4010, 4011, 4013, 4031, 4033],
  12521. [4012, 4020, 4021, 4022, 4023],
  12522. [4010, 4011, 4013, 4030, 4033],
  12523. [4011, 4020, 4021, 4022, 4023],
  12524. [4010, 4020, 4021, 4022, 4023],
  12525. [4010, 4012, 4013, 4023, 4033],
  12526. [4000, 4002, 4003, 4042, 4043],
  12527. [4010, 4011, 4013, 4023, 4033],
  12528. [4001, 4002, 4003, 4040, 4043],
  12529. [4000, 4002, 4003, 4041, 4043],
  12530. [4000, 4001, 4003, 4042, 4043],
  12531. [4010, 4011, 4012, 4013, 4043],
  12532. [4003, 4020, 4021, 4022, 4023],
  12533. [4000, 4002, 4003, 4040, 4043],
  12534. [4000, 4001, 4003, 4041, 4043],
  12535. [4010, 4011, 4012, 4013, 4042],
  12536. [4002, 4020, 4021, 4022, 4023],
  12537. [4000, 4001, 4003, 4040, 4043],
  12538. [4010, 4011, 4012, 4013, 4041],
  12539. [4001, 4020, 4021, 4022, 4023],
  12540. [4010, 4011, 4012, 4013, 4040],
  12541. [4000, 4020, 4021, 4022, 4023],
  12542. [4001, 4002, 4003, 4033, 4043],
  12543. [4000, 4002, 4003, 4033, 4043],
  12544. [4003, 4010, 4012, 4013, 4043],
  12545. [4003, 4013, 4020, 4022, 4023],
  12546. [4000, 4001, 4003, 4033, 4043],
  12547. [4003, 4010, 4011, 4013, 4043],
  12548. [4003, 4013, 4020, 4021, 4023],
  12549. [4010, 4011, 4012, 4013, 4033],
  12550. [4010, 4011, 4012, 4013, 4032],
  12551. [4010, 4011, 4012, 4013, 4031],
  12552. [4010, 4011, 4012, 4013, 4030],
  12553. [4001, 4002, 4003, 4023, 4043],
  12554. [4000, 4002, 4003, 4023, 4043],
  12555. [4003, 4010, 4012, 4013, 4033],
  12556. [4000, 4002, 4003, 4032, 4033],
  12557. [4000, 4001, 4003, 4023, 4043],
  12558. [4003, 4010, 4011, 4013, 4033],
  12559. [4001, 4002, 4003, 4030, 4033],
  12560. [4000, 4002, 4003, 4031, 4033],
  12561. [4000, 4001, 4003, 4032, 4033],
  12562. [4010, 4011, 4012, 4013, 4023],
  12563. [4000, 4002, 4003, 4030, 4033],
  12564. [4000, 4001, 4003, 4031, 4033],
  12565. [4010, 4011, 4012, 4013, 4022],
  12566. [4000, 4001, 4003, 4030, 4033],
  12567. [4010, 4011, 4012, 4013, 4021],
  12568. [4010, 4011, 4012, 4013, 4020],
  12569. [4001, 4002, 4003, 4013, 4043],
  12570. [4001, 4002, 4003, 4023, 4033],
  12571. [4000, 4002, 4003, 4013, 4043],
  12572. [4000, 4002, 4003, 4023, 4033],
  12573. [4003, 4010, 4012, 4013, 4023],
  12574. [4000, 4001, 4003, 4013, 4043],
  12575. [4000, 4001, 4003, 4023, 4033],
  12576. [4003, 4010, 4011, 4013, 4023],
  12577. [4001, 4002, 4003, 4013, 4033],
  12578. [4000, 4002, 4003, 4013, 4033],
  12579. [4000, 4001, 4003, 4013, 4033],
  12580. [4000, 4001, 4002, 4003, 4043],
  12581. [4003, 4010, 4011, 4012, 4013],
  12582. [4000, 4001, 4002, 4003, 4042],
  12583. [4002, 4010, 4011, 4012, 4013],
  12584. [4000, 4001, 4002, 4003, 4041],
  12585. [4001, 4010, 4011, 4012, 4013],
  12586. [4000, 4001, 4002, 4003, 4040],
  12587. [4000, 4010, 4011, 4012, 4013],
  12588. [4001, 4002, 4003, 4013, 4023],
  12589. [4000, 4002, 4003, 4013, 4023],
  12590. [4000, 4001, 4003, 4013, 4023],
  12591. [4000, 4001, 4002, 4003, 4033],
  12592. [4000, 4001, 4002, 4003, 4032],
  12593. [4000, 4001, 4002, 4003, 4031],
  12594. [4000, 4001, 4002, 4003, 4030],
  12595. [4000, 4001, 4002, 4003, 4023],
  12596. [4000, 4001, 4002, 4003, 4022],
  12597. [4000, 4001, 4002, 4003, 4021],
  12598. [4000, 4001, 4002, 4003, 4020],
  12599. [4000, 4001, 4002, 4003, 4013],
  12600. [4000, 4001, 4002, 4003, 4012],
  12601. [4000, 4001, 4002, 4003, 4011],
  12602. [4000, 4001, 4002, 4003, 4010],
  12603. ].filter((p) => p.includes(this.mandatoryId));
  12604.  
  12605. const bestPack = {
  12606. pack: packs[0],
  12607. winRate: 0,
  12608. countBattle: 0,
  12609. id: 0,
  12610. };
  12611.  
  12612. for (const id in packs) {
  12613. const pack = packs[id];
  12614. const attackers = this.maxUpgrade.filter((e) => pack.includes(e.id)).reduce((obj, e) => ({ ...obj, [e.id]: e }), {});
  12615. const battle = {
  12616. attackers,
  12617. defenders: [enemieHeroes],
  12618. type: 'brawl_titan',
  12619. };
  12620. const isRandom = this.isRandomBattle(battle);
  12621. const stat = {
  12622. count: 0,
  12623. win: 0,
  12624. winRate: 0,
  12625. };
  12626. for (let i = 1; i <= 20; i++) {
  12627. battle.seed = Math.floor(Date.now() / 1000) + Math.random() * 1000;
  12628. const result = await Calc(battle);
  12629. stat.win += result.result.win;
  12630. stat.count += 1;
  12631. stat.winRate = stat.win / stat.count;
  12632. if (!isRandom || (i >= 2 && stat.winRate < 0.65) || (i >= 10 && stat.winRate == 1)) {
  12633. break;
  12634. }
  12635. }
  12636.  
  12637. if (!isRandom && stat.win) {
  12638. return {
  12639. favor: {},
  12640. heroes: pack,
  12641. };
  12642. }
  12643. if (stat.winRate > 0.85) {
  12644. return {
  12645. favor: {},
  12646. heroes: pack,
  12647. };
  12648. }
  12649. if (stat.winRate > bestPack.winRate) {
  12650. bestPack.countBattle = stat.count;
  12651. bestPack.winRate = stat.winRate;
  12652. bestPack.pack = pack;
  12653. bestPack.id = id;
  12654. }
  12655. }
  12656.  
  12657. //console.log(bestPack.id, bestPack.pack, bestPack.winRate, bestPack.countBattle);
  12658. return {
  12659. favor: {},
  12660. heroes: bestPack.pack,
  12661. };
  12662. }
  12663.  
  12664. isRandomPack(pack) {
  12665. const ids = Object.keys(pack);
  12666. return ids.includes('4023') || ids.includes('4021');
  12667. }
  12668.  
  12669. isRandomBattle(battle) {
  12670. return this.isRandomPack(battle.attackers) || this.isRandomPack(battle.defenders[0]);
  12671. }
  12672.  
  12673. async updateHeroesPack(enemieHeroes) {
  12674. 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}}}];
  12675.  
  12676. const bestPack = {
  12677. pack: packs[0],
  12678. countWin: 0,
  12679. }
  12680.  
  12681. for (const pack of packs) {
  12682. const attackers = pack.attackers;
  12683. const battle = {
  12684. attackers,
  12685. defenders: [enemieHeroes],
  12686. type: 'brawl',
  12687. };
  12688.  
  12689. let countWinBattles = 0;
  12690. let countTestBattle = 10;
  12691. for (let i = 0; i < countTestBattle; i++) {
  12692. battle.seed = Math.floor(Date.now() / 1000) + Math.random() * 1000;
  12693. const result = await Calc(battle);
  12694. if (result.result.win) {
  12695. countWinBattles++;
  12696. }
  12697. if (countWinBattles > 7) {
  12698. console.log(pack)
  12699. return pack.args;
  12700. }
  12701. }
  12702. if (countWinBattles > bestPack.countWin) {
  12703. bestPack.countWin = countWinBattles;
  12704. bestPack.pack = pack.args;
  12705. }
  12706. }
  12707.  
  12708. console.log(bestPack);
  12709. return bestPack.pack;
  12710. }
  12711.  
  12712. async questFarm() {
  12713. const calls = [this.callBrawlQuestFarm];
  12714. const result = await Send(JSON.stringify({ calls }));
  12715. return result.results[0].result.response;
  12716. }
  12717.  
  12718. async getBrawlInfo() {
  12719. const data = await Send(JSON.stringify({
  12720. calls: [
  12721. this.callUserGetInfo,
  12722. this.callBrawlQuestGetInfo,
  12723. this.callBrawlFindEnemies,
  12724. this.callTeamGetMaxUpgrade,
  12725. this.callBrawlGetInfo,
  12726. ]
  12727. }));
  12728.  
  12729. let attempts = data.results[0].result.response.refillable.find(n => n.id == 48);
  12730.  
  12731. const maxUpgrade = data.results[3].result.response;
  12732. const maxHero = Object.values(maxUpgrade.hero);
  12733. const maxTitan = Object.values(maxUpgrade.titan);
  12734. const maxPet = Object.values(maxUpgrade.pet);
  12735. this.maxUpgrade = [...maxHero, ...maxPet, ...maxTitan];
  12736.  
  12737. this.info = data.results[4].result.response;
  12738. this.mandatoryId = lib.data.brawl.promoHero[this.info.id].promoHero;
  12739. return {
  12740. attempts: attempts.amount,
  12741. questInfo: data.results[1].result.response,
  12742. findEnemies: data.results[2].result.response,
  12743. }
  12744. }
  12745.  
  12746. /**
  12747. * Carrying out a fight
  12748. *
  12749. * Проведение боя
  12750. */
  12751. async battle(userId) {
  12752. this.stats.count++;
  12753. const battle = await this.startBattle(userId, this.args);
  12754. const result = await Calc(battle);
  12755. console.log(result.result);
  12756. if (result.result.win) {
  12757. this.stats.win++;
  12758. } else {
  12759. this.stats.loss++;
  12760. if (!this.info.boughtEndlessLivesToday) {
  12761. this.attempts--;
  12762. }
  12763. }
  12764. return await this.endBattle(result);
  12765. // return await this.cancelBattle(result);
  12766. }
  12767.  
  12768. /**
  12769. * Starts a fight
  12770. *
  12771. * Начинает бой
  12772. */
  12773. async startBattle(userId, args) {
  12774. const call = {
  12775. name: "brawl_startBattle",
  12776. args,
  12777. ident: "brawl_startBattle"
  12778. }
  12779. call.args.userId = userId;
  12780. const calls = [call];
  12781. const result = await Send(JSON.stringify({ calls }));
  12782. return result.results[0].result.response;
  12783. }
  12784.  
  12785. cancelBattle(battle) {
  12786. const fixBattle = function (heroes) {
  12787. for (const ids in heroes) {
  12788. const hero = heroes[ids];
  12789. hero.energy = random(1, 999);
  12790. if (hero.hp > 0) {
  12791. hero.hp = random(1, hero.hp);
  12792. }
  12793. }
  12794. }
  12795. fixBattle(battle.progress[0].attackers.heroes);
  12796. fixBattle(battle.progress[0].defenders.heroes);
  12797. return this.endBattle(battle);
  12798. }
  12799.  
  12800. /**
  12801. * Ends the fight
  12802. *
  12803. * Заканчивает бой
  12804. */
  12805. async endBattle(battle) {
  12806. battle.progress[0].attackers.input = ['auto', 0, 0, 'auto', 0, 0];
  12807. const calls = [{
  12808. name: "brawl_endBattle",
  12809. args: {
  12810. result: battle.result,
  12811. progress: battle.progress
  12812. },
  12813. ident: "brawl_endBattle"
  12814. },
  12815. this.callBrawlQuestGetInfo,
  12816. this.callBrawlFindEnemies,
  12817. ];
  12818. const result = await Send(JSON.stringify({ calls }));
  12819. return result.results;
  12820. }
  12821.  
  12822. end(endReason) {
  12823. setIsCancalBattle(true);
  12824. isBrawlsAutoStart = false;
  12825. setProgress(endReason, true);
  12826. console.log(endReason);
  12827. this.resolve();
  12828. }
  12829. }
  12830.  
  12831. this.HWHClasses.executeBrawls = executeBrawls;
  12832.  
  12833. })();
  12834.  
  12835. /**
  12836. * TODO:
  12837. * Получение всех уровней при сборе всех наград (квест на титанит и на энку) +-
  12838. * Добивание на арене титанов
  12839. * Закрытие окошек по Esc +-
  12840. * Починить работу скрипта на уровне команды ниже 10 +-
  12841. * Написать номальную синхронизацию
  12842. * Запрет сбора квестов и отправки экспеиций в промежуток между локальным обновлением и глобальным обновлением дня
  12843. * Улучшение боев
  12844. */