HeroWarsHelper

Automation of actions for the game Hero Wars

目前为 2023-09-18 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name HeroWarsHelper
  3. // @name:en HeroWarsHelper
  4. // @name:ru HeroWarsHelper
  5. // @namespace HeroWarsHelper
  6. // @version 2.134
  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 http://ilovemycomp.narod.ru/HeroWarsHelper.user.js
  13. // @icon http://ilovemycomp.narod.ru/VaultBoyIco16.ico
  14. // @icon64 http://ilovemycomp.narod.ru/VaultBoyIco64.png
  15. // @encoding utf-8
  16. // @include https://*.nextersglobal.com/*
  17. // @include https://*.hero-wars*.com/*
  18. // @match https://www.solfors.com/
  19. // @match https://t.me/s/hw_ru
  20. // @run-at document-start
  21. // ==/UserScript==
  22.  
  23. (function() {
  24. /**
  25. * Start script
  26. *
  27. * Стартуем скрипт
  28. */
  29. console.log('Start ' + GM_info.script.name + ', v' + GM_info.script.version);
  30. /**
  31. * Script info
  32. *
  33. * Информация о скрипте
  34. */
  35. const scriptInfo = (({name, version, author, homepage, lastModified}, updateUrl, source) =>
  36. ({name, version, author, homepage, lastModified, updateUrl, source}))
  37. (GM_info.script, GM_info.scriptUpdateURL, arguments.callee.toString());
  38. /**
  39. * If we are on the gifts page, then we collect and send them to the server
  40. *
  41. * Если находимся на странице подарков, то собираем и отправляем их на сервер
  42. */
  43. if (['www.solfors.com', 't.me'].includes(location.host)) {
  44. setTimeout(sendCodes, 2000);
  45. return;
  46. }
  47. /**
  48. * Information for completing daily quests
  49. *
  50. * Информация для выполнения ежендевных квестов
  51. */
  52. const questsInfo = {};
  53. /**
  54. * Is the game data loaded
  55. *
  56. * Загружены ли данные игры
  57. */
  58. let isLoadGame = false;
  59. /**
  60. * Headers of the last request
  61. *
  62. * Заголовки последнего запроса
  63. */
  64. let lastHeaders = {};
  65. /**
  66. * Information about sent gifts
  67. *
  68. * Информация об отправленных подарках
  69. */
  70. let freebieCheckInfo = null;
  71. /**
  72. * User data
  73. *
  74. * Данные пользователя
  75. */
  76. let userInfo;
  77. /**
  78. * Original methods for working with AJAX
  79. *
  80. * Оригинальные методы для работы с AJAX
  81. */
  82. const original = {
  83. open: XMLHttpRequest.prototype.open,
  84. send: XMLHttpRequest.prototype.send,
  85. setRequestHeader: XMLHttpRequest.prototype.setRequestHeader,
  86. };
  87. /**
  88. * Decoder for converting byte data to JSON string
  89. *
  90. * Декодер для перобразования байтовых данных в JSON строку
  91. */
  92. const decoder = new TextDecoder("utf-8");
  93. /**
  94. * Stores a history of requests
  95. *
  96. * Хранит историю запросов
  97. */
  98. let requestHistory = {};
  99. /**
  100. * URL for API requests
  101. *
  102. * URL для запросов к API
  103. */
  104. let apiUrl = '';
  105.  
  106. /**
  107. * Connecting to the game code
  108. *
  109. * Подключение к коду игры
  110. */
  111. this.cheats = new hackGame();
  112. /**
  113. * The function of calculating the results of the battle
  114. *
  115. * Функция расчета результатов боя
  116. */
  117. this.BattleCalc = cheats.BattleCalc;
  118. /**
  119. * Sending a request available through the console
  120. *
  121. * Отправка запроса доступная через консоль
  122. */
  123. this.SendRequest = send;
  124. /**
  125. * Simple combat calculation available through the console
  126. *
  127. * Простой расчет боя доступный через консоль
  128. */
  129. this.Calc = function (data) {
  130. const type = getBattleType(data?.type);
  131. return new Promise((resolve, reject) => {
  132. try {
  133. BattleCalc(data, type, resolve);
  134. } catch (e) {
  135. reject(e);
  136. }
  137. })
  138. }
  139. /**
  140. * Short asynchronous request
  141. * Usage example (returns information about a character):
  142. * const userInfo = await Send('{"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}')
  143. *
  144. * Короткий асинхронный запрос
  145. * Пример использования (возвращает информацию о персонаже):
  146. * const userInfo = await Send('{"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}')
  147. */
  148. this.Send = function (json, pr) {
  149. return new Promise((resolve, reject) => {
  150. try {
  151. send(json, resolve, pr);
  152. } catch (e) {
  153. reject(e);
  154. }
  155. })
  156. }
  157.  
  158. const i18nLangData = {
  159. /* English translation by BaBa */
  160. en: {
  161. /* Checkboxes */
  162. SKIP_FIGHTS: 'Skip battle',
  163. SKIP_FIGHTS_TITLE: 'Skip battle in Outland and the arena of the titans, auto-pass in the tower and campaign',
  164. ENDLESS_CARDS: 'Infinite cards',
  165. ENDLESS_CARDS_TITLE: 'Disable Divination Cards wasting',
  166. AUTO_EXPEDITION: 'Auto Expedition',
  167. AUTO_EXPEDITION_TITLE: 'Auto-sending expeditions',
  168. CANCEL_FIGHT: 'Cancel battle',
  169. CANCEL_FIGHT_TITLE: 'The possibility of canceling the battle on VG',
  170. GIFTS: 'Gifts',
  171. GIFTS_TITLE: 'Collect gifts automatically',
  172. BATTLE_RECALCULATION: 'Battle recalculation',
  173. BATTLE_RECALCULATION_TITLE: 'Preliminary calculation of the battle',
  174. QUANTITY_CONTROL: 'Quantity control',
  175. QUANTITY_CONTROL_TITLE: 'Ability to specify the number of opened "lootboxes"',
  176. REPEAT_CAMPAIGN: 'Repeat missions',
  177. REPEAT_CAMPAIGN_TITLE: 'Auto-repeat battles in the campaign',
  178. DISABLE_DONAT: 'Disable donation',
  179. DISABLE_DONAT_TITLE: 'Removes all donation offers',
  180. DAILY_QUESTS: 'Quests',
  181. DAILY_QUESTS_TITLE: 'Complete daily quests',
  182. AUTO_QUIZ: 'AutoQuiz',
  183. AUTO_QUIZ_TITLE: 'Automatically receive correct answers to quiz questions',
  184. SECRET_WEALTH_CHECKBOX: 'Automatic purchase in the store "Secret Wealth" when entering the game',
  185. /* Input fields */
  186. HOW_MUCH_TITANITE: 'How much titanite to farm',
  187. COMBAT_SPEED: 'Combat Speed Multiplier',
  188. NUMBER_OF_TEST: 'Number of test fights',
  189. NUMBER_OF_AUTO_BATTLE: 'Number of auto-battle attempts',
  190. /* Buttons */
  191. RUN_SCRIPT: 'Run the',
  192. TO_DO_EVERYTHING: 'Do All',
  193. TO_DO_EVERYTHING_TITLE: 'Perform multiple actions of your choice',
  194. OUTLAND: 'Outland',
  195. OUTLAND_TITLE: 'Collect Outland',
  196. TITAN_ARENA: 'ToE',
  197. TITAN_ARENA_TITLE: 'Complete the titan arena',
  198. DUNGEON: 'Dungeon',
  199. DUNGEON_TITLE: 'Go through the dungeon',
  200. TOWER: 'Tower',
  201. TOWER_TITLE: 'Pass the tower',
  202. EXPEDITIONS: 'Expeditions',
  203. EXPEDITIONS_TITLE: 'Sending and collecting expeditions',
  204. SYNC: 'Sync',
  205. SYNC_TITLE: 'Partial synchronization of game data without reloading the page',
  206. ARCHDEMON: 'Archdemon',
  207. ARCHDEMON_TITLE: 'Hitting kills and collecting rewards',
  208. ESTER_EGGS: 'Easter eggs',
  209. ESTER_EGGS_TITLE: 'Collect all Easter eggs or rewards',
  210. REWARDS: 'Rewards',
  211. REWARDS_TITLE: 'Collect all quest rewards',
  212. MAIL: 'Mail',
  213. MAIL_TITLE: 'Collect all mail, except letters with energy and charges of the portal',
  214. MINIONS: 'Minions',
  215. MINIONS_TITLE: 'Attack minions with saved packs',
  216. ADVENTURE: 'Adventure',
  217. ADVENTURE_TITLE: 'Passes the adventure along the specified route',
  218. STORM: 'Storm',
  219. STORM_TITLE: 'Passes the Storm along the specified route',
  220. SANCTUARY: 'Sanctuary',
  221. SANCTUARY_TITLE: 'Fast travel to Sanctuary',
  222. GUILD_WAR: 'Guild War',
  223. GUILD_WAR_TITLE: 'Fast travel to Guild War',
  224. SECRET_WEALTH: 'Secret Wealth',
  225. SECRET_WEALTH_TITLE: 'Buy something in the store "Secret Wealth"',
  226. /* Misc */
  227. BOTTOM_URLS: '<a href="https://t.me/+0oMwICyV1aQ1MDAy" target="_blank" title="Telegram"><svg style="margin: 2px;" width="20" height="20" viewBox="0 0 1000 1000" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><defs><linearGradient x1="50%" y1="0%" x2="50%" y2="99.2583404%" id="linearGradient-1"><stop stop-color="#2AABEE" offset="0%"></stop><stop stop-color="#229ED9" offset="100%"></stop></linearGradient></defs><g id="Artboard" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"><circle id="Oval" fill="url(#linearGradient-1)" cx="500" cy="500" r="500"></circle><path d="M226.328419,494.722069 C372.088573,431.216685 469.284839,389.350049 517.917216,369.122161 C656.772535,311.36743 685.625481,301.334815 704.431427,301.003532 C708.567621,300.93067 717.815839,301.955743 723.806446,306.816707 C728.864797,310.92121 730.256552,316.46581 730.922551,320.357329 C731.588551,324.248848 732.417879,333.113828 731.758626,340.040666 C724.234007,419.102486 691.675104,610.964674 675.110982,699.515267 C668.10208,736.984342 654.301336,749.547532 640.940618,750.777006 C611.904684,753.448938 589.856115,731.588035 561.733393,713.153237 C517.726886,684.306416 492.866009,666.349181 450.150074,638.200013 C400.78442,605.66878 432.786119,587.789048 460.919462,558.568563 C468.282091,550.921423 596.21508,434.556479 598.691227,424.000355 C599.00091,422.680135 599.288312,417.758981 596.36474,415.160431 C593.441168,412.561881 589.126229,413.450484 586.012448,414.157198 C581.598758,415.158943 511.297793,461.625274 375.109553,553.556189 C355.154858,567.258623 337.080515,573.934908 320.886524,573.585046 C303.033948,573.199351 268.692754,563.490928 243.163606,555.192408 C211.851067,545.013936 186.964484,539.632504 189.131547,522.346309 C190.260287,513.342589 202.659244,504.134509 226.328419,494.722069 Z" id="Path-3" fill="#FFFFFF"></path></g></svg></a>',
  228. GIFTS_SENT: 'Gifts sent!',
  229. DO_YOU_WANT: "Do you really want to do this?",
  230. BTN_RUN: 'Run',
  231. BTN_CANCEL: 'Cancel',
  232. BTN_OK: 'OK',
  233. MSG_HAVE_BEEN_DEFEATED: 'You have been defeated!',
  234. BTN_AUTO: 'Auto',
  235. MSG_YOU_APPLIED: 'You applied',
  236. MSG_DAMAGE: 'damage',
  237. MSG_CANCEL_AND_STAT: 'Auto (F5) and show statistic',
  238. MSG_REPEAT_MISSION: 'Repeat the mission?',
  239. BTN_REPEAT: 'Repeat',
  240. BTN_NO: 'No',
  241. MSG_SPECIFY_QUANT: 'Specify Quantity:',
  242. BTN_OPEN: 'Open',
  243. QUESTION_COPY: 'Question copied to clipboard',
  244. ANSWER_KNOWN: 'The answer is known',
  245. ANSWER_NOT_KNOWN: 'ATTENTION THE ANSWER IS NOT KNOWN',
  246. BEING_RECALC: 'The battle is being recalculated',
  247. THIS_TIME: 'This time',
  248. VICTORY: 'VICTORY',
  249. DEFEAT: 'DEFEAT',
  250. CHANCE_TO_WIN: "Chance to win",
  251. OPEN_DOLLS: 'nesting dolls recursively',
  252. SENT_QUESTION: 'Question sent',
  253. SETTINGS: 'Settings',
  254. MSG_BAN_ATTENTION: '<p style="color:red;">Using this feature may result in a ban.</p> Continue?',
  255. BTN_YES_I_AGREE: 'Yes, I understand the risks!',
  256. BTN_NO_I_AM_AGAINST: 'No, I refuse it!',
  257. VALUES: 'Values',
  258. EXPEDITIONS_SENT: 'Expeditions sent',
  259. TITANIT: 'Titanit',
  260. COMPLETED: 'completed',
  261. FLOOR: 'Floor',
  262. LEVEL: 'Level',
  263. BATTLES: 'battles',
  264. EVENT: 'Event',
  265. NOT_AVAILABLE: 'not available',
  266. NO_HEROES: 'No heroes',
  267. DAMAGE_AMOUNT: 'Damage amount',
  268. NOTHING_TO_COLLECT: 'Nothing to collect',
  269. COLLECTED: 'Collected',
  270. REWARD: 'rewards',
  271. REMAINING_ATTEMPTS: 'Remaining attempts',
  272. BATTLES_CANCELED: 'Battles canceled',
  273. MINION_RAID: 'Minion Raid',
  274. STOPPED: 'Stopped',
  275. REPETITIONS: 'Repetitions',
  276. MISSIONS_PASSED: 'Missions passed',
  277. STOP: 'stop',
  278. TOTAL_OPEN: 'Total open',
  279. OPEN: 'Open',
  280. ROUND_STAT: 'Damage statistics for ',
  281. BATTLE: 'battles',
  282. MINIMUM: 'Minimum',
  283. MAXIMUM: 'Maximum',
  284. AVERAGE: 'Average',
  285. NOT_THIS_TIME: 'Not this time',
  286. RETRY_LIMIT_EXCEEDED: 'Retry limit exceeded',
  287. SUCCESS: 'Success',
  288. RECEIVED: 'Received',
  289. LETTERS: 'letters',
  290. PORTALS: 'portals',
  291. ATTEMPTS: 'attempts',
  292. /* Quests */
  293. QUEST_10001: 'Upgrade the skills of heroes 3 times',
  294. QUEST_10002: 'Complete 10 missions',
  295. QUEST_10003: 'Complete 3 heroic missions',
  296. QUEST_10004: 'Fight 3 times in the Arena or Grand Arena',
  297. QUEST_10006: 'Use the exchange of emeralds 1 time',
  298. QUEST_10007: 'Perform 1 summon in the Solu Atrium',
  299. QUEST_10016: 'Send gifts to guildmates',
  300. QUEST_10018: 'Use an experience potion',
  301. QUEST_10019: 'Open 1 chest in the Tower',
  302. QUEST_10020: 'Open 3 chests in Outland',
  303. QUEST_10021: 'Collect 75 Titanite in the Guild Dungeon',
  304. QUEST_10021: 'Collect 150 Titanite in the Guild Dungeon',
  305. QUEST_10023: 'Upgrade Gift of the Elements by 1 level',
  306. QUEST_10024: 'Level up any artifact once',
  307. QUEST_10025: 'Start Expedition 1',
  308. QUEST_10026: 'Start 4 Expeditions',
  309. QUEST_10027: 'Win 1 battle of the Tournament of Elements',
  310. QUEST_10028: 'Level up any titan artifact',
  311. QUEST_10029: 'Unlock the Orb of Titan Artifacts',
  312. QUEST_10030: 'Upgrade any Skin of any hero 1 time',
  313. QUEST_10031: 'Win 6 battles of the Tournament of Elements',
  314. QUEST_10043: 'Start or Join an Adventure',
  315. QUEST_10044: 'Use Summon Pets 1 time',
  316. QUEST_10046: 'Open 3 chests in Adventure',
  317. QUEST_10047: 'Get 150 Guild Activity Points',
  318. NOTHING_TO_DO: 'Nothing to do',
  319. YOU_CAN_COMPLETE: 'You can complete quests',
  320. BTN_DO_IT: 'Do it',
  321. NOT_QUEST_COMPLETED: 'Not a single quest completed',
  322. COMPLETED_QUESTS: 'Completed quests',
  323. /* everything button */
  324. ASSEMBLE_OUTLAND: 'Assemble Outland',
  325. PASS_THE_TOWER: 'Pass the tower',
  326. CHECK_EXPEDITIONS: 'Check Expeditions',
  327. COMPLETE_TOE: 'Complete ToE',
  328. COMPLETE_DUNGEON: 'Complete the dungeon',
  329. COLLECT_MAIL: 'Collect mail',
  330. COLLECT_MISC: 'Collect some bullshit',
  331. COLLECT_MISC_TITLE: 'Collect Easter Eggs, Skin Gems, Keys, Arena Coins and Soul Crystal',
  332. COLLECT_QUEST_REWARDS: 'Collect quest rewards',
  333. MAKE_A_SYNC: 'Make a sync',
  334.  
  335. RUN_FUNCTION: 'Run the following functions?',
  336. BTN_GO: 'Go!',
  337. PERFORMED: 'Performed',
  338. DONE: 'Done',
  339. ERRORS_OCCURRES: 'Errors occurred while executing',
  340. COPY_ERROR: 'Copy error information to clipboard',
  341. BTN_YES: 'Yes',
  342. ALL_TASK_COMPLETED: 'All tasks completed',
  343.  
  344. UNKNOWN: 'unknown',
  345. ENTER_THE_PATH: 'Enter the path of adventure using commas or dashes',
  346. START_ADVENTURE: 'Start your adventure along this path!',
  347. BTN_CANCELED: 'Canceled',
  348. MUST_TWO_POINTS: 'The path must contain at least 2 points.',
  349. MUST_ONLY_NUMBERS: 'The path must contain only numbers and commas',
  350. NOT_ON_AN_ADVENTURE: 'You are not on an adventure',
  351. YOU_IN_NOT_ON_THE_WAY: 'Your location is not on the way',
  352. ATTEMPTS_NOT_ENOUGH: 'Your attempts are not enough to complete the path, continue?',
  353. YES_CONTINUE: 'Yes, continue!',
  354. NOT_ENOUGH_AP: 'Not enough action points',
  355. ATTEMPTS_ARE_OVER: 'The attempts are over',
  356. MOVES: 'Moves',
  357. BUFF_GET_ERROR: 'Buff getting error',
  358. BATTLE_END_ERROR: 'Battle end error',
  359. AUTOBOT: 'Autobot',
  360. FAILED_TO_WIN_AUTO: 'Failed to win the auto battle',
  361. ERROR_OF_THE_BATTLE_COPY: 'An error occurred during the passage of the battle<br>Copy the error to the clipboard?',
  362. ERROR_DURING_THE_BATTLE: 'Error during the battle',
  363. NO_CHANCE_WIN: 'No chance of winning this fight: 0/',
  364. LOST_HEROES: 'You have won, but you have lost one or several heroes',
  365. VICTORY_IMPOSSIBLE: 'Is victory impossible, should we focus on the result?',
  366. FIND_COEFF: 'Find the coefficient greater than',
  367. BTN_PASS: 'PASS',
  368. BRAWLS: 'Brawls',
  369. BRAWLS_TITLE: 'Activates the ability to auto-brawl',
  370. START_AUTO_BRAWLS: 'Start Auto Brawls?',
  371. LOSSES: 'Losses',
  372. WINS: 'Wins',
  373. FIGHTS: 'Fights',
  374. STAGE: 'Stage',
  375. DONT_HAVE_LIVES: 'You don\'t have lives',
  376. SECRET_WEALTH_ALREADY: 'Secret Wealth: Item for Pet Potions already purchased',
  377. SECRET_WEALTH_NOT_ENOUGH: 'Secret Wealth: Not Enough Pet Potion, You Have {available}, Need {need}',
  378. SECRET_WEALTH_UPGRADE_NEW_PET: 'Secret Wealth: After purchasing the Pet Potion, it will not be enough to upgrade a new pet',
  379. SECRET_WEALTH_PURCHASED: 'Secret wealth: Purchased {count} {name}',
  380. SECRET_WEALTH_CANCELED: 'Secret Wealth: Purchase Canceled',
  381. SECRET_WEALTH_BUY: 'You have {available} Pet Potion.<br>Do you want to buy {countBuy} {name} for {price} Pet Potion?',
  382. DAILY_BONUS: 'Daily bonus',
  383. DO_DAILY_QUESTS: 'Do daily quests',
  384. ACTIONS: 'Actions',
  385. ACTIONS_TITLE: 'Dialog box with various actions',
  386. OTHERS: 'Others',
  387. OTHERS_TITLE: 'Others',
  388. CHOOSE_ACTION: 'Choose an action',
  389. OPEN_LOOTBOX: 'You have {lootBox} boxes, should we open them?',
  390. STAMINA: 'Energy',
  391. BOXES_OVER: 'The boxes are over',
  392. NO_BOXES: 'No boxes',
  393. NO_MORE_ACTIVITY: 'No more activity for items today',
  394. EXCHANGE_ITEMS: 'Exchange items for activity points (max {maxActive})?',
  395. GET_ACTIVITY: 'Get Activity',
  396. NOT_ENOUGH_ITEMS: 'Not enough items',
  397. ACTIVITY_RECEIVED: 'Activity received',
  398. NO_PURCHASABLE_HERO_SOULS: 'No purchasable Hero Souls',
  399. PURCHASED_HERO_SOULS: 'Purchased {countHeroSouls} Hero Souls',
  400. NOT_ENOUGH_EMERALDS_540: 'Not enough emeralds, you need 540 you have {currentStarMoney}',
  401. CHESTS_NOT_AVAILABLE: 'Chests not available',
  402. OUTLAND_CHESTS_RECEIVED: 'Outland chests received',
  403. RAID_NOT_AVAILABLE: 'The raid is not available or there are no spheres',
  404. RAID_ADVENTURE: 'Raid {adventureId} adventure!',
  405. SOMETHING_WENT_WRONG: 'Something went wrong',
  406. ADVENTURE_COMPLETED: 'Adventure {adventureId} completed {times} times',
  407. CLAN_STAT_COPY: 'Clan statistics copied to clipboard',
  408. GET_ENERGY: 'Get Energy',
  409. GET_ENERGY_TITLE: 'Opens platinum boxes one at a time until you get 250 energy',
  410. ITEM_EXCHANGE: 'Item Exchange',
  411. ITEM_EXCHANGE_TITLE: 'Exchanges items for the specified amount of activity',
  412. BUY_SOULS: 'Buy souls',
  413. BUY_SOULS_TITLE: 'Buy hero souls from all available shops',
  414. BUY_OUTLAND: 'Buy Outland',
  415. BUY_OUTLAND_TITLE: 'Buy 9 chests in Outland for 540 emeralds',
  416. AUTO_RAID_ADVENTURE: 'Raid adventure',
  417. AUTO_RAID_ADVENTURE_TITLE: 'Raid adventure set number of times',
  418. CLAN_STAT: 'Clan statistics',
  419. CLAN_STAT_TITLE: 'Copies clan statistics to the clipboard',
  420. BTN_AUTO_F5: 'Auto (F5)',
  421. BOSS_DAMAGE: 'Boss Damage: ',
  422. NOTHING_BUY: 'Nothing to buy',
  423. LOTS_BOUGHT: '{countBuy} lots bought for gold',
  424. BUY_FOR_GOLD: 'Buy for gold',
  425. BUY_FOR_GOLD_TITLE: 'Buy items for gold in the Town Shop and in the Pet Soul Stone Shop',
  426. REWARDS_AND_MAIL: 'Rewars and Mail',
  427. REWARDS_AND_MAIL_TITLE: 'Collects rewards and mail',
  428. COLLECT_REWARDS_AND_MAIL: 'Collected {countQuests} rewards and {countMail} letters',
  429. TIMER_ALREADY: 'Timer already started',
  430. NO_ATTEMPTS_TIMER_START: 'No attempts, timer started',
  431. EPIC_BRAWL_RESULT: 'Wins: {wins}/{attempts}, Coins: {coins}, Streak: {progress}/{nextStage} [Close]{end}',
  432. ATTEMPT_ENDED: '<br>Attempts ended, timer started',
  433. EPIC_BRAWL: 'Cosmic Battle',
  434. EPIC_BRAWL_TITLE: 'Spends attempts in the Cosmic Battle',
  435. RELOAD_GAME: 'Reload game',
  436. TIMER: 'Timer:',
  437. SHOW_ERRORS: 'Show errors',
  438. SHOW_ERRORS_TITLE: 'Show server request errors',
  439. ERROR_MSG: 'Error: {name}<br>{desciption}',
  440. },
  441. ru: {
  442. /* Чекбоксы */
  443. SKIP_FIGHTS: 'Пропуск боев',
  444. SKIP_FIGHTS_TITLE: 'Пропуск боев в запределье и арене титанов, автопропуск в башне и кампании',
  445. ENDLESS_CARDS: 'Бесконечные карты',
  446. ENDLESS_CARDS_TITLE: 'Отключить трату карт предсказаний',
  447. AUTO_EXPEDITION: 'АвтоЭкспедиции',
  448. AUTO_EXPEDITION_TITLE: 'Автоотправка экспедиций',
  449. CANCEL_FIGHT: 'Отмена боя',
  450. CANCEL_FIGHT_TITLE: 'Возможность отмены боя на ВГ, СМ и в Асгарде',
  451. GIFTS: 'Подарки',
  452. GIFTS_TITLE: 'Собирать подарки автоматически',
  453. BATTLE_RECALCULATION: 'Прерасчет боя',
  454. BATTLE_RECALCULATION_TITLE: 'Предварительный расчет боя',
  455. QUANTITY_CONTROL: 'Контроль кол-ва',
  456. QUANTITY_CONTROL_TITLE: 'Возможность указывать количество открываемых "лутбоксов"',
  457. REPEAT_CAMPAIGN: 'Повтор в компании',
  458. REPEAT_CAMPAIGN_TITLE: 'Автоповтор боев в кампании',
  459. DISABLE_DONAT: 'Отключить донат',
  460. DISABLE_DONAT_TITLE: 'Убирает все предложения доната',
  461. DAILY_QUESTS: 'Квесты',
  462. DAILY_QUESTS_TITLE: 'Выполнять ежедневные квесты',
  463. AUTO_QUIZ: 'АвтоВикторина',
  464. AUTO_QUIZ_TITLE: 'Автоматическое получение правильных ответов на вопросы викторины',
  465. SECRET_WEALTH_CHECKBOX: 'Автоматическая покупка в магазине "Тайное Богатство" при заходе в игру',
  466. /* Поля ввода */
  467. HOW_MUCH_TITANITE: 'Сколько фармим титанита',
  468. COMBAT_SPEED: 'Множитель ускорения боя',
  469. NUMBER_OF_TEST: 'Количество тестовых боев',
  470. NUMBER_OF_AUTO_BATTLE: 'Количество попыток автобоев',
  471. /* Кнопки */
  472. RUN_SCRIPT: 'Запустить скрипт',
  473. TO_DO_EVERYTHING: 'Сделать все',
  474. TO_DO_EVERYTHING_TITLE: 'Выполнить несколько действий',
  475. OUTLAND: 'Запределье',
  476. OUTLAND_TITLE: 'Собрать Запределье',
  477. TITAN_ARENA: 'Турнир Стихий',
  478. TITAN_ARENA_TITLE: 'Автопрохождение Турнира Стихий',
  479. DUNGEON: 'Подземелье',
  480. DUNGEON_TITLE: 'Автопрохождение подземелья',
  481. TOWER: 'Башня',
  482. TOWER_TITLE: 'Автопрохождение башни',
  483. EXPEDITIONS: 'Экспедиции',
  484. EXPEDITIONS_TITLE: 'Отправка и сбор экспедиций',
  485. SYNC: 'Синхронизация',
  486. SYNC_TITLE: 'Частичная синхронизация данных игры без перезагрузки сатраницы',
  487. ARCHDEMON: 'Архидемон',
  488. ARCHDEMON_TITLE: 'Набивает килы и собирает награду',
  489. ESTER_EGGS: 'Пасхалки',
  490. ESTER_EGGS_TITLE: 'Собрать все пасхалки или награды',
  491. REWARDS: 'Награды',
  492. REWARDS_TITLE: 'Собрать все награды за задания',
  493. MAIL: 'Почта',
  494. MAIL_TITLE: 'Собрать всю почту, кроме писем с энергией и зарядами портала',
  495. MINIONS: 'Прислужники',
  496. MINIONS_TITLE: 'Атакует прислужников сохраннеными пачками',
  497. ADVENTURE: 'Приключение',
  498. ADVENTURE_TITLE: 'Проходит приключение по указанному маршруту',
  499. STORM: 'Буря',
  500. STORM_TITLE: 'Проходит бурю по указанному маршруту',
  501. SANCTUARY: 'Святилище',
  502. SANCTUARY_TITLE: 'Быстрый переход к Святилищу',
  503. GUILD_WAR: 'Война гильдий',
  504. GUILD_WAR_TITLE: 'Быстрый переход к Войне гильдий',
  505. SECRET_WEALTH: 'Тайное богатство',
  506. SECRET_WEALTH_TITLE: 'Купить что-то в магазине "Тайное богатство"',
  507. /* Разное */
  508. BOTTOM_URLS: '<a href="https://t.me/+q6gAGCRpwyFkNTYy" target="_blank" title="Telegram"><svg style="margin: 2px;" width="20" height="20" viewBox="0 0 1000 1000" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><defs><linearGradient x1="50%" y1="0%" x2="50%" y2="99.2583404%" id="linearGradient-1"><stop stop-color="#2AABEE" offset="0%"></stop><stop stop-color="#229ED9" offset="100%"></stop></linearGradient></defs><g id="Artboard" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"><circle id="Oval" fill="url(#linearGradient-1)" cx="500" cy="500" r="500"></circle><path d="M226.328419,494.722069 C372.088573,431.216685 469.284839,389.350049 517.917216,369.122161 C656.772535,311.36743 685.625481,301.334815 704.431427,301.003532 C708.567621,300.93067 717.815839,301.955743 723.806446,306.816707 C728.864797,310.92121 730.256552,316.46581 730.922551,320.357329 C731.588551,324.248848 732.417879,333.113828 731.758626,340.040666 C724.234007,419.102486 691.675104,610.964674 675.110982,699.515267 C668.10208,736.984342 654.301336,749.547532 640.940618,750.777006 C611.904684,753.448938 589.856115,731.588035 561.733393,713.153237 C517.726886,684.306416 492.866009,666.349181 450.150074,638.200013 C400.78442,605.66878 432.786119,587.789048 460.919462,558.568563 C468.282091,550.921423 596.21508,434.556479 598.691227,424.000355 C599.00091,422.680135 599.288312,417.758981 596.36474,415.160431 C593.441168,412.561881 589.126229,413.450484 586.012448,414.157198 C581.598758,415.158943 511.297793,461.625274 375.109553,553.556189 C355.154858,567.258623 337.080515,573.934908 320.886524,573.585046 C303.033948,573.199351 268.692754,563.490928 243.163606,555.192408 C211.851067,545.013936 186.964484,539.632504 189.131547,522.346309 C190.260287,513.342589 202.659244,504.134509 226.328419,494.722069 Z" id="Path-3" fill="#FFFFFF"></path></g></svg></a><a href="https://vk.com/invite/YNPxKGX" target="_blank" title="Вконтакте"><svg style="margin: 2px;" width="20" height="20" viewBox="0 0 101 100" fill="none" xmlns="http://www.w3.org/2000/svg"><g clip-path="url(#clip0_2_40)"><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="#0077FF"/><path d="M53.7085 72.042C30.9168 72.042 17.9169 56.417 17.3752 30.417H28.7919C29.1669 49.5003 37.5834 57.5836 44.25 59.2503V30.417H55.0004V46.8752C61.5837 46.1669 68.4995 38.667 70.8329 30.417H81.5832C79.7915 40.5837 72.2915 48.0836 66.9582 51.1669C72.2915 53.6669 80.8336 60.2086 84.0836 72.042H72.2499C69.7082 64.1253 63.3754 58.0003 55.0004 57.1669V72.042H53.7085Z" fill="white"/></g><defs><clipPath id="clip0_2_40"><rect width="100" height="100" fill="white" transform="translate(0.5)"/></clipPath></defs></svg></a>',
  509. GIFTS_SENT: 'Подарки отправлены!',
  510. DO_YOU_WANT: "Вы действительно хотите это сделать?",
  511. BTN_RUN: 'Запускай',
  512. BTN_CANCEL: 'Отмена',
  513. BTN_OK: 'Ок',
  514. MSG_HAVE_BEEN_DEFEATED: 'Вы потерпели поражение!',
  515. BTN_AUTO: 'Авто',
  516. MSG_YOU_APPLIED: 'Вы нанесли',
  517. MSG_DAMAGE: 'урона',
  518. MSG_CANCEL_AND_STAT: 'Авто (F5) и показать Статистику',
  519. MSG_REPEAT_MISSION: 'Повторить миссию?',
  520. BTN_REPEAT: 'Повторить',
  521. BTN_NO: 'Нет',
  522. MSG_SPECIFY_QUANT: 'Указать количество:',
  523. BTN_OPEN: 'Открыть',
  524. QUESTION_COPY: 'Вопрос скопирован в буфер обмена',
  525. ANSWER_KNOWN: 'Ответ известен',
  526. ANSWER_NOT_KNOWN: 'ВНИМАНИЕ ОТВЕТ НЕ ИЗВЕСТЕН',
  527. BEING_RECALC: 'Идет прерасчет боя',
  528. THIS_TIME: 'На этот раз',
  529. VICTORY: 'ПОБЕДА',
  530. DEFEAT: 'ПОРАЖЕНИЕ',
  531. CHANCE_TO_WIN: 'Шансы на победу',
  532. OPEN_DOLLS: 'матрешек рекурсивно',
  533. SENT_QUESTION: 'Вопрос отправлен',
  534. SETTINGS: 'Настройки',
  535. MSG_BAN_ATTENTION: '<p style="color:red;">Использование этой функции может привести к бану.</p> Продолжить?',
  536. BTN_YES_I_AGREE: 'Да, я беру на себя все риски!',
  537. BTN_NO_I_AM_AGAINST: 'Нет, я отказываюсь от этого!',
  538. VALUES: 'Значения',
  539. EXPEDITIONS_SENT: 'Экспедиции отправлены',
  540. TITANIT: 'Титанит',
  541. COMPLETED: 'завершено',
  542. FLOOR: 'Этаж',
  543. LEVEL: 'Уровень',
  544. BATTLES: 'бои',
  545. EVENT: 'Эвент',
  546. NOT_AVAILABLE: 'недоступен',
  547. NO_HEROES: 'Нет героев',
  548. DAMAGE_AMOUNT: 'Количество урона',
  549. NOTHING_TO_COLLECT: 'Нечего собирать',
  550. COLLECTED: 'Собрано',
  551. REWARD: 'наград',
  552. REMAINING_ATTEMPTS: 'Осталось попыток',
  553. BATTLES_CANCELED: 'Битв отменено',
  554. MINION_RAID: 'Рейд прислужников',
  555. STOPPED: 'Остановлено',
  556. REPETITIONS: 'Повторений',
  557. MISSIONS_PASSED: 'Миссий пройдено',
  558. STOP: 'остановить',
  559. TOTAL_OPEN: 'Всего открыто',
  560. OPEN: 'Открыто',
  561. ROUND_STAT: 'Статистика урона за',
  562. BATTLE: 'боев',
  563. MINIMUM: 'Минимальный',
  564. MAXIMUM: 'Максимальный',
  565. AVERAGE: 'Средний',
  566. NOT_THIS_TIME: 'Не в этот раз',
  567. RETRY_LIMIT_EXCEEDED: 'Превышен лимит попыток',
  568. SUCCESS: 'Успех',
  569. RECEIVED: 'Получено',
  570. LETTERS: 'писем',
  571. PORTALS: 'порталов',
  572. ATTEMPTS: 'попыток',
  573. QUEST_10001: 'Улучши умения героев 3 раза',
  574. QUEST_10002: 'Пройди 10 миссий',
  575. QUEST_10003: 'Пройди 3 героические миссии',
  576. QUEST_10004: 'Сразись 3 раза на Арене или Гранд Арене',
  577. QUEST_10006: 'Используй обмен изумрудов 1 раз',
  578. QUEST_10007: 'Соверши 1 призыв в Атриуме Душ',
  579. QUEST_10016: 'Отправь подарки согильдийцам',
  580. QUEST_10018: 'Используй зелье опыта',
  581. QUEST_10019: 'Открой 1 сундук в Башне',
  582. QUEST_10020: 'Открой 3 сундука в Запределье',
  583. QUEST_10021: 'Собери 75 Титанита в Подземелье Гильдии',
  584. QUEST_10021: 'Собери 150 Титанита в Подземелье Гильдии',
  585. QUEST_10023: 'Прокачай Дар Стихий на 1 уровень',
  586. QUEST_10024: 'Повысь уровень любого артефакта один раз',
  587. QUEST_10025: 'Начни 1 Экспедицию',
  588. QUEST_10026: 'Начни 4 Экспедиции',
  589. QUEST_10027: 'Победи в 1 бою Турнира Стихий',
  590. QUEST_10028: 'Повысь уровень любого артефакта титанов',
  591. QUEST_10029: 'Открой сферу артефактов титанов',
  592. QUEST_10030: 'Улучши облик любого героя 1 раз',
  593. QUEST_10031: 'Победи в 6 боях Турнира Стихий',
  594. QUEST_10043: 'Начни или присоеденись к Приключению',
  595. QUEST_10044: 'Воспользуйся призывом питомцев 1 раз',
  596. QUEST_10046: 'Открой 3 сундука в Приключениях',
  597. QUEST_10047: 'Набери 150 очков активности в Гильдии',
  598. NOTHING_TO_DO: 'Нечего выполнять',
  599. YOU_CAN_COMPLETE: 'Можно выполнить квесты',
  600. BTN_DO_IT: 'Выполняй',
  601. NOT_QUEST_COMPLETED: 'Ни одного квеста не выполенно',
  602. COMPLETED_QUESTS: 'Выполенно квестов',
  603. /* everything button */
  604. ASSEMBLE_OUTLAND: 'Собрать Запределье',
  605. PASS_THE_TOWER: 'Пройти башню',
  606. CHECK_EXPEDITIONS: 'Проверить экспедиции',
  607. COMPLETE_TOE: 'Пройти Турнир Стихий',
  608. COMPLETE_DUNGEON: 'Пройти подземелье',
  609. COLLECT_MAIL: 'Собрать почту',
  610. COLLECT_MISC: 'Собрать всякую херню',
  611. COLLECT_MISC_TITLE: 'Собрать пасхалки, камни облика, ключи, монеты арены и Хрусталь души',
  612. COLLECT_QUEST_REWARDS: 'Собрать награды за квесты',
  613. MAKE_A_SYNC: 'Сделать синхронизацю',
  614.  
  615. RUN_FUNCTION: 'Выполнить следующие функции?',
  616. BTN_GO: 'Погнали!',
  617. PERFORMED: 'Выполняется',
  618. DONE: 'Выполнено',
  619. ERRORS_OCCURRES: 'Призошли ошибки при выполнении',
  620. COPY_ERROR: 'Скопировать в буфер информацию об ошибке',
  621. BTN_YES: 'Да',
  622. ALL_TASK_COMPLETED: 'Все задачи выполнены',
  623.  
  624. UNKNOWN: 'Неизвестно',
  625. ENTER_THE_PATH: 'Введите путь приключения через запятые или дефисы',
  626. START_ADVENTURE: 'Начать приключение по этому пути!',
  627. BTN_CANCELED: 'Отменено',
  628. MUST_TWO_POINTS: 'Путь должен состоять минимум из 2х точек',
  629. MUST_ONLY_NUMBERS: 'Путь должен содержать только цифры и запятые',
  630. NOT_ON_AN_ADVENTURE: 'Вы не в приключении',
  631. YOU_IN_NOT_ON_THE_WAY: 'Указанный путь должен включать точку вашего положения',
  632. ATTEMPTS_NOT_ENOUGH: 'Ваших попыток не достаточно для завершения пути, продолжить?',
  633. YES_CONTINUE: 'Да, продолжай!',
  634. NOT_ENOUGH_AP: 'Попыток не достаточно',
  635. ATTEMPTS_ARE_OVER: 'Попытки закончились',
  636. MOVES: 'Ходы',
  637. BUFF_GET_ERROR: 'Ошибка при получении бафа',
  638. BATTLE_END_ERROR: 'Ошибка завершения боя',
  639. AUTOBOT: 'АвтоБой',
  640. FAILED_TO_WIN_AUTO: 'Не удалось победить в автобою',
  641. ERROR_OF_THE_BATTLE_COPY: 'Призошли ошибка в процессе прохождения боя<br>Скопировать ошибку в буфер обмена?',
  642. ERROR_DURING_THE_BATTLE: 'Ошибка в процессе прохождения боя',
  643. NO_CHANCE_WIN: 'Нет шансов победить в этом бою: 0/',
  644. LOST_HEROES: 'Вы победили, но потеряли одного или несколько героев!',
  645. VICTORY_IMPOSSIBLE: 'Победа не возможна, бъем на результат?',
  646. FIND_COEFF: 'Поиск коэффициента больше чем',
  647. BTN_PASS: 'ПРОПУСК',
  648. BRAWLS: 'Потасовки',
  649. BRAWLS_TITLE: 'Включает возможность автопотасовок',
  650. START_AUTO_BRAWLS: 'Запустить Автопотасовки?',
  651. LOSSES: 'Поражений',
  652. WINS: 'Побед',
  653. FIGHTS: 'Боев',
  654. STAGE: 'Стадия',
  655. DONT_HAVE_LIVES: 'У Вас нет жизней',
  656. SECRET_WEALTH_ALREADY: 'Тайное богатство: товар за Зелья питомцев уже куплен',
  657. SECRET_WEALTH_NOT_ENOUGH: 'Тайное богатство: Не достаточно Зелье Питомца, у Вас {available}, нужно {need}',
  658. SECRET_WEALTH_UPGRADE_NEW_PET: 'Тайное богатство: После покупки Зелье Питомца будет не достаточно для прокачки нового питомца',
  659. SECRET_WEALTH_PURCHASED: 'Тайное богатство: Куплено {count} {name}',
  660. SECRET_WEALTH_CANCELED: 'Тайное богатство: покупка отменена',
  661. SECRET_WEALTH_BUY: 'У вас {available} Зелье Питомца.<br>Вы хотите купить {countBuy} {name} за {price} Зелье Питомца?',
  662. DAILY_BONUS: 'Ежедневная награда',
  663. DO_DAILY_QUESTS: 'Сделать ежедневные квесты',
  664. ACTIONS: 'Действия',
  665. ACTIONS_TITLE: 'Диалоговое окно с различными действиями',
  666. OTHERS: 'Разное',
  667. OTHERS_TITLE: 'Диалоговое окно с дополнительными различными действиями',
  668. CHOOSE_ACTION: 'Выберите действие',
  669. OPEN_LOOTBOX: 'У Вас {lootBox} ящиков, откываем?',
  670. STAMINA: 'Энергия',
  671. BOXES_OVER: 'Ящики закончились',
  672. NO_BOXES: 'Нет ящиков',
  673. NO_MORE_ACTIVITY: 'Больше активности за предметы сегодня не получить',
  674. EXCHANGE_ITEMS: 'Обменять предметы на очки активности (не более {maxActive})?',
  675. GET_ACTIVITY: 'Получить активность',
  676. NOT_ENOUGH_ITEMS: 'Предметов недостаточно',
  677. ACTIVITY_RECEIVED: 'Получено активности',
  678. NO_PURCHASABLE_HERO_SOULS: 'Нет доступных для покупки душ героев',
  679. PURCHASED_HERO_SOULS: 'Куплено {countHeroSouls} душ героев',
  680. NOT_ENOUGH_EMERALDS_540: 'Недостаточно изюма, нужно 540 у Вас {currentStarMoney}',
  681. CHESTS_NOT_AVAILABLE: 'Сундуки не доступны',
  682. OUTLAND_CHESTS_RECEIVED: 'Получено сундуков Запределья',
  683. RAID_NOT_AVAILABLE: 'Рейд не доступен или сфер нет',
  684. RAID_ADVENTURE: 'Рейд {adventureId} приключения!',
  685. SOMETHING_WENT_WRONG: 'Что-то пошло не так',
  686. ADVENTURE_COMPLETED: 'Приключение {adventureId} пройдено {times} раз',
  687. CLAN_STAT_COPY: 'Клановая статистика скопирована в буфер обмена',
  688. GET_ENERGY: 'Получить энергию',
  689. GET_ENERGY_TITLE: 'Открывает платиновые шкатулки по одной до получения 250 энергии',
  690. ITEM_EXCHANGE: 'Обмен предметов',
  691. ITEM_EXCHANGE_TITLE: 'Обменивает предметы на указанное количество активности',
  692. BUY_SOULS: 'Купить души',
  693. BUY_SOULS_TITLE: 'Купить души героев из всех доступных магазинов',
  694. BUY_OUTLAND: 'Купить Запределье',
  695. BUY_OUTLAND_TITLE: 'Купить 9 сундуков в Запределье за 540 изумрудов',
  696. AUTO_RAID_ADVENTURE: 'Рейд приключения',
  697. AUTO_RAID_ADVENTURE_TITLE: 'Рейд приключения заданное количество раз',
  698. CLAN_STAT: 'Клановая статистика',
  699. CLAN_STAT_TITLE: 'Копирует клановую статистику в буфер обмена',
  700. BTN_AUTO_F5: 'Авто (F5)',
  701. BOSS_DAMAGE: 'Урон по боссу: ',
  702. NOTHING_BUY: 'Нечего покупать',
  703. LOTS_BOUGHT: 'За золото куплено {countBuy} лотов',
  704. BUY_FOR_GOLD: 'Скупить за золото',
  705. BUY_FOR_GOLD_TITLE: 'Скупить предметы за золото в Городской лавке и в магазине Камней Душ Питомцев',
  706. REWARDS_AND_MAIL: 'Награды и почта',
  707. REWARDS_AND_MAIL_TITLE: 'Собирает награды и почту',
  708. COLLECT_REWARDS_AND_MAIL: 'Собрано {countQuests} наград и {countMail} писем',
  709. TIMER_ALREADY: 'Таймер уже запущен',
  710. NO_ATTEMPTS_TIMER_START: 'Попыток нет, запущен таймер',
  711. EPIC_BRAWL_RESULT: '{i} Победы: {wins}/{attempts}, Монеты: {coins}, Серия: {progress}/{nextStage} [Закрыть]{end}',
  712. ATTEMPT_ENDED: '<br>Попытки закончились, запущен таймер',
  713. EPIC_BRAWL: 'Вселенская битва',
  714. EPIC_BRAWL_TITLE: 'Тратит попытки во Вселенской битве',
  715. RELOAD_GAME: 'Перезагрузить игру',
  716. TIMER: 'Таймер:',
  717. SHOW_ERRORS: 'Отображать ошибки',
  718. SHOW_ERRORS_TITLE: 'Отображать ошибки запросов к серверу',
  719. ERROR_MSG: 'Ошибка: {name}<br>{description}',
  720. }
  721. }
  722.  
  723. function getLang() {
  724. let lang = '';
  725. if (typeof NXFlashVars !== 'undefined') {
  726. lang = NXFlashVars.interface_lang
  727. }
  728. if (!lang) {
  729. lang = (navigator.language || navigator.userLanguage).substr(0, 2);
  730. }
  731. if (lang == 'ru') {
  732. return lang;
  733. }
  734. return 'en';
  735. }
  736.  
  737. this.I18N = function (constant, replace) {
  738. const selectLang = getLang();
  739. if (constant && constant in i18nLangData[selectLang]) {
  740. const result = i18nLangData[selectLang][constant];
  741. if (replace) {
  742. return result.sprintf(replace);
  743. }
  744. return result;
  745. }
  746. return `% ${constant} %`;
  747. };
  748.  
  749. String.prototype.sprintf = String.prototype.sprintf ||
  750. function () {
  751. "use strict";
  752. var str = this.toString();
  753. if (arguments.length) {
  754. var t = typeof arguments[0];
  755. var key;
  756. var args = ("string" === t || "number" === t) ?
  757. Array.prototype.slice.call(arguments)
  758. : arguments[0];
  759.  
  760. for (key in args) {
  761. str = str.replace(new RegExp("\\{" + key + "\\}", "gi"), args[key]);
  762. }
  763. }
  764.  
  765. return str;
  766. };
  767.  
  768. /**
  769. * Checkboxes
  770. *
  771. * Чекбоксы
  772. */
  773. const checkboxes = {
  774. passBattle: {
  775. label: I18N('SKIP_FIGHTS'),
  776. cbox: null,
  777. title: I18N('SKIP_FIGHTS_TITLE'),
  778. default: false
  779. },
  780. endlessCards: {
  781. label: I18N('ENDLESS_CARDS'),
  782. cbox: null,
  783. title: I18N('ENDLESS_CARDS_TITLE'),
  784. default: true
  785. },
  786. sendExpedition: {
  787. label: I18N('AUTO_EXPEDITION'),
  788. cbox: null,
  789. title: I18N('AUTO_EXPEDITION_TITLE'),
  790. default: true
  791. },
  792. cancelBattle: {
  793. label: I18N('CANCEL_FIGHT'),
  794. cbox: null,
  795. title: I18N('CANCEL_FIGHT_TITLE'),
  796. default: false,
  797. },
  798. preCalcBattle: {
  799. label: I18N('BATTLE_RECALCULATION'),
  800. cbox: null,
  801. title: I18N('BATTLE_RECALCULATION_TITLE'),
  802. default: false
  803. },
  804. countControl: {
  805. label: I18N('QUANTITY_CONTROL'),
  806. cbox: null,
  807. title: I18N('QUANTITY_CONTROL_TITLE'),
  808. default: true
  809. },
  810. repeatMission: {
  811. label: I18N('REPEAT_CAMPAIGN'),
  812. cbox: null,
  813. title: I18N('REPEAT_CAMPAIGN_TITLE'),
  814. default: false
  815. },
  816. noOfferDonat: {
  817. label: I18N('DISABLE_DONAT'),
  818. cbox: null,
  819. title: I18N('DISABLE_DONAT_TITLE'),
  820. /**
  821. * A crutch to get the field before getting the character id
  822. *
  823. * Костыль чтоб получать поле до получения id персонажа
  824. */
  825. default: (() => {
  826. $result = false;
  827. try {
  828. $result = JSON.parse(localStorage[GM_info.script.name + ':noOfferDonat'])
  829. } catch(e) {
  830. $result = false;
  831. }
  832. return $result || false;
  833. })(),
  834. },
  835. dailyQuests: {
  836. label: I18N('DAILY_QUESTS'),
  837. cbox: null,
  838. title: I18N('DAILY_QUESTS_TITLE'),
  839. default: false
  840. },
  841. secretWealth: {
  842. label: I18N('SECRET_WEALTH'),
  843. cbox: null,
  844. title: I18N('SECRET_WEALTH_CHECKBOX'),
  845. default: false
  846. },
  847. /*
  848. autoBrawls: {
  849. label: I18N('BRAWLS'),
  850. cbox: null,
  851. title: I18N('BRAWLS_TITLE'),
  852. default: (() => {
  853. $result = false;
  854. try {
  855. $result = JSON.parse(localStorage[GM_info.script.name + ':autoBrawls'])
  856. } catch (e) {
  857. $result = false;
  858. }
  859. return $result || false;
  860. })(),
  861. }
  862. */
  863. /*
  864. getAnswer: {
  865. label: I18N('AUTO_QUIZ'),
  866. cbox: null,
  867. title: I18N('AUTO_QUIZ_TITLE'),
  868. default: false
  869. },
  870. */
  871. showErrors: {
  872. label: I18N('SHOW_ERRORS'),
  873. cbox: null,
  874. title: I18N('SHOW_ERRORS_TITLE'),
  875. default: true
  876. },
  877. buyForGold: {
  878. label: I18N('BUY_FOR_GOLD'),
  879. cbox: null,
  880. title: I18N('BUY_FOR_GOLD_TITLE'),
  881. default: false
  882. },
  883. };
  884. /**
  885. * Get checkbox state
  886. *
  887. * Получить состояние чекбокса
  888. */
  889. function isChecked(checkBox) {
  890. if (!(checkBox in checkboxes)) {
  891. return false;
  892. }
  893. return checkboxes[checkBox].cbox?.checked;
  894. }
  895. /**
  896. * Input fields
  897. *
  898. * Поля ввода
  899. */
  900. const inputs = {
  901. countTitanit: {
  902. input: null,
  903. title: I18N('HOW_MUCH_TITANITE'),
  904. default: 150,
  905. },
  906. speedBattle: {
  907. input: null,
  908. title: I18N('COMBAT_SPEED'),
  909. default: 5,
  910. },
  911. countTestBattle: {
  912. input: null,
  913. title: I18N('NUMBER_OF_TEST'),
  914. default: 10,
  915. },
  916. countAutoBattle: {
  917. input: null,
  918. title: I18N('NUMBER_OF_AUTO_BATTLE'),
  919. default: 10,
  920. }
  921. }
  922. /**
  923. * Checks the checkbox
  924. *
  925. * Поплучить данные поля ввода
  926. */
  927. function getInput(inputName) {
  928. return inputs[inputName].input.value;
  929. }
  930. /**
  931. * Button List
  932. *
  933. * Список кнопочек
  934. */
  935. const buttons = {
  936. getOutland: {
  937. name: I18N('TO_DO_EVERYTHING'),
  938. title: I18N('TO_DO_EVERYTHING_TITLE'),
  939. func: testDoYourBest,
  940. },
  941. doActions: {
  942. name: I18N('ACTIONS'),
  943. title: I18N('ACTIONS_TITLE'),
  944. func: async function () {
  945. const popupButtons = [
  946. {
  947. msg: I18N('OUTLAND'),
  948. result: function () {
  949. confShow(`${I18N('RUN_SCRIPT')} ${I18N('OUTLAND')}?`, getOutland);
  950. },
  951. title: I18N('OUTLAND_TITLE'),
  952. },
  953. {
  954. msg: I18N('TOWER'),
  955. result: function () {
  956. confShow(`${I18N('RUN_SCRIPT')} ${I18N('TOWER')}?`, testTower);
  957. },
  958. title: I18N('TOWER_TITLE'),
  959. },
  960. {
  961. msg: I18N('EXPEDITIONS'),
  962. result: function () {
  963. confShow(`${I18N('RUN_SCRIPT')} ${I18N('EXPEDITIONS')}?`, checkExpedition);
  964. },
  965. title: I18N('EXPEDITIONS_TITLE'),
  966. },
  967. {
  968. msg: I18N('MINIONS'),
  969. result: function () {
  970. confShow(`${I18N('RUN_SCRIPT')} ${I18N('MINIONS')}?`, testRaidNodes);
  971. },
  972. title: I18N('MINIONS_TITLE'),
  973. },
  974. {
  975. msg: I18N('ESTER_EGGS'),
  976. result: function () {
  977. confShow(`${I18N('RUN_SCRIPT')} ${I18N('ESTER_EGGS')}?`, offerFarmAllReward);
  978. },
  979. title: I18N('ESTER_EGGS_TITLE'),
  980. },
  981. {
  982. msg: I18N('STORM'),
  983. result: function () {
  984. testAdventure('solo');
  985. },
  986. title: I18N('STORM_TITLE'),
  987. },
  988. {
  989. msg: I18N('REWARDS'),
  990. result: function () {
  991. confShow(`${I18N('RUN_SCRIPT')} ${I18N('REWARDS')}?`, questAllFarm);
  992. },
  993. title: I18N('REWARDS_TITLE'),
  994. },
  995. {
  996. msg: I18N('MAIL'),
  997. result: function () {
  998. confShow(`${I18N('RUN_SCRIPT')} ${I18N('MAIL')}?`, mailGetAll);
  999. },
  1000. title: I18N('MAIL_TITLE'),
  1001. },
  1002. ];
  1003. popupButtons.push({ result: false, isClose: true })
  1004. const answer = await popup.confirm(`${I18N('CHOOSE_ACTION')}:`, popupButtons);
  1005. if (typeof answer === 'function') {
  1006. answer();
  1007. }
  1008. }
  1009. },
  1010. doOthers: {
  1011. name: I18N('OTHERS'),
  1012. title: I18N('OTHERS_TITLE'),
  1013. func: async function () {
  1014. const popupButtons = [
  1015. {
  1016. msg: I18N('GET_ENERGY'),
  1017. result: farmStamina,
  1018. title: I18N('GET_ENERGY_TITLE'),
  1019. },
  1020. {
  1021. msg: I18N('ITEM_EXCHANGE'),
  1022. result: fillActive,
  1023. title: I18N('ITEM_EXCHANGE_TITLE'),
  1024. },
  1025. {
  1026. msg: I18N('BUY_SOULS'),
  1027. result: function () {
  1028. confShow(`${I18N('RUN_SCRIPT')} ${I18N('BUY_SOULS')}?`, buyHeroFragments);
  1029. },
  1030. title: I18N('BUY_SOULS_TITLE'),
  1031. },
  1032. {
  1033. msg: I18N('BUY_FOR_GOLD'),
  1034. result: function () {
  1035. confShow(`${I18N('RUN_SCRIPT')} ${I18N('BUY_FOR_GOLD')}?`, buyInStoreForGold);
  1036. },
  1037. title: I18N('BUY_FOR_GOLD_TITLE'),
  1038. },
  1039. {
  1040. msg: I18N('BUY_OUTLAND'),
  1041. result: function () {
  1042. confShow(I18N('BUY_OUTLAND_TITLE') + '?', bossOpenChestPay);
  1043. },
  1044. title: I18N('BUY_OUTLAND_TITLE'),
  1045. },
  1046. {
  1047. msg: I18N('AUTO_RAID_ADVENTURE'),
  1048. result: autoRaidAdventure,
  1049. title: I18N('AUTO_RAID_ADVENTURE_TITLE'),
  1050. },
  1051. {
  1052. msg: I18N('CLAN_STAT'),
  1053. result: clanStatistic,
  1054. title: I18N('CLAN_STAT_TITLE'),
  1055. },
  1056. {
  1057. msg: I18N('SECRET_WEALTH'),
  1058. result: buyWithPetExperience,
  1059. title: I18N('SECRET_WEALTH_TITLE'),
  1060. },
  1061. {
  1062. msg: I18N('EPIC_BRAWL'),
  1063. result: async function () {
  1064. confShow(`${I18N('RUN_SCRIPT')} ${I18N('EPIC_BRAWL')}?`, () => {
  1065. const brawl = new epicBrawl;
  1066. brawl.start();
  1067. });
  1068. },
  1069. title: I18N('EPIC_BRAWL_TITLE'),
  1070. },
  1071. ];
  1072. popupButtons.push({ result: false, isClose: true })
  1073. const answer = await popup.confirm(`${I18N('CHOOSE_ACTION')}:`, popupButtons);
  1074. if (typeof answer === 'function') {
  1075. answer();
  1076. }
  1077. }
  1078. },
  1079. testTitanArena: {
  1080. name: I18N('TITAN_ARENA'),
  1081. title: I18N('TITAN_ARENA_TITLE'),
  1082. func: function () {
  1083. confShow(`${I18N('RUN_SCRIPT')} ${I18N('TITAN_ARENA')}?`, testTitanArena);
  1084. },
  1085. },
  1086. testDungeon: {
  1087. name: I18N('DUNGEON'),
  1088. title: I18N('DUNGEON_TITLE'),
  1089. func: function () {
  1090. confShow(`${I18N('RUN_SCRIPT')} ${I18N('DUNGEON')}?`, testDungeon);
  1091. },
  1092. },
  1093. /*
  1094. bossRatingEvent: {
  1095. name: I18N('ARCHDEMON'),
  1096. title: I18N('ARCHDEMON_TITLE'),
  1097. func: function () {
  1098. confShow(`${I18N('RUN_SCRIPT')} ${I18N('ARCHDEMON')}?`, bossRatingEvent);
  1099. },
  1100. },
  1101. */
  1102. rewardsAndMailFarm: {
  1103. name: I18N('REWARDS_AND_MAIL'),
  1104. title: I18N('REWARDS_AND_MAIL_TITLE'),
  1105. func: function () {
  1106. confShow(`${I18N('RUN_SCRIPT')} ${I18N('REWARDS_AND_MAIL')}?`, rewardsAndMailFarm);
  1107. },
  1108. },
  1109. testAdventure: {
  1110. name: I18N('ADVENTURE'),
  1111. title: I18N('ADVENTURE_TITLE'),
  1112. func: () => {
  1113. testAdventure();
  1114. },
  1115. },
  1116. goToSanctuary: {
  1117. name: I18N('SANCTUARY'),
  1118. title: I18N('SANCTUARY_TITLE'),
  1119. func: cheats.goSanctuary,
  1120. },
  1121. goToClanWar: {
  1122. name: I18N('GUILD_WAR'),
  1123. title: I18N('GUILD_WAR_TITLE'),
  1124. func: cheats.goClanWar,
  1125. },
  1126. dailyQuests: {
  1127. name: I18N('DAILY_QUESTS'),
  1128. title: I18N('DAILY_QUESTS_TITLE'),
  1129. func: async function () {
  1130. const quests = new dailyQuests(() => { }, () => { });
  1131. await quests.autoInit();
  1132. quests.start();
  1133. },
  1134. },
  1135. newDay: {
  1136. name: I18N('SYNC'),
  1137. title: I18N('SYNC_TITLE'),
  1138. func: function () {
  1139. confShow(`${I18N('RUN_SCRIPT')} ${I18N('SYNC')}?`, cheats.refreshGame);
  1140. },
  1141. },
  1142. }
  1143. /**
  1144. * Display buttons
  1145. *
  1146. * Вывести кнопочки
  1147. */
  1148. function addControlButtons() {
  1149. for (let name in buttons) {
  1150. button = buttons[name];
  1151. button['button'] = scriptMenu.addButton(button.name, button.func, button.title);
  1152. }
  1153. }
  1154. /**
  1155. * Adds links
  1156. *
  1157. * Добавляет ссылки
  1158. */
  1159. function addBottomUrls() {
  1160. scriptMenu.addHeader(I18N('BOTTOM_URLS'));
  1161. }
  1162. /**
  1163. * Stop repetition of the mission
  1164. *
  1165. * Остановить повтор миссии
  1166. */
  1167. let isStopSendMission = false;
  1168. /**
  1169. * There is a repetition of the mission
  1170. *
  1171. * Идет повтор миссии
  1172. */
  1173. let isSendsMission = false;
  1174. /**
  1175. * Data on the past mission
  1176. *
  1177. * Данные о прошедшей мисии
  1178. */
  1179. let lastMissionStart = {}
  1180.  
  1181. /**
  1182. * Data on the past attack on the boss
  1183. *
  1184. * Данные о прошедшей атаке на босса
  1185. */
  1186. let lastBossBattle = {}
  1187. /**
  1188. * Data for calculating the last battle with the boss
  1189. *
  1190. * Данные для расчете последнего боя с боссом
  1191. */
  1192. let lastBossBattleInfo = null;
  1193. /**
  1194. * Ability to cancel the battle in Asgard
  1195. *
  1196. * Возможность отменить бой в Астгарде
  1197. */
  1198. let isCancalBossBattle = true;
  1199. /**
  1200. * Information about the last battle
  1201. *
  1202. * Данные о прошедшей битве
  1203. */
  1204. let lastBattleArg = {}
  1205. /**
  1206. * The name of the function of the beginning of the battle
  1207. *
  1208. * Имя функции начала боя
  1209. */
  1210. let nameFuncStartBattle = '';
  1211. /**
  1212. * The name of the function of the end of the battle
  1213. *
  1214. * Имя функции конца боя
  1215. */
  1216. let nameFuncEndBattle = '';
  1217. /**
  1218. * Data for calculating the last battle
  1219. *
  1220. * Данные для расчета последнего боя
  1221. */
  1222. let lastBattleInfo = null;
  1223. /**
  1224. * The ability to cancel the battle
  1225. *
  1226. * Возможность отменить бой
  1227. */
  1228. let isCancalBattle = true;
  1229.  
  1230. /**
  1231. * Certificator of the last open nesting doll
  1232. *
  1233. * Идетификатор последней открытой матрешки
  1234. */
  1235. let lastRussianDollId = null;
  1236. /**
  1237. * Cancel the training guide
  1238. *
  1239. * Отменить обучающее руководство
  1240. */
  1241. this.isCanceledTutorial = false;
  1242.  
  1243. /**
  1244. * Data from the last question of the quiz
  1245. *
  1246. * Данные последнего вопроса викторины
  1247. */
  1248. let lastQuestion = null;
  1249. /**
  1250. * Answer to the last question of the quiz
  1251. *
  1252. * Ответ на последний вопрос викторины
  1253. */
  1254. let lastAnswer = null;
  1255. /**
  1256. * Flag for opening keys or titan artifact spheres
  1257. *
  1258. * Флаг открытия ключей или сфер артефактов титанов
  1259. */
  1260. let artifactChestOpen = false;
  1261. /**
  1262. * The name of the function to open keys or orbs of titan artifacts
  1263. *
  1264. * Имя функции открытия ключей или сфер артефактов титанов
  1265. */
  1266. let artifactChestOpenCallName = '';
  1267. /**
  1268. * Data for the last battle in the dungeon
  1269. * (Fix endless cards)
  1270. *
  1271. * Данные для последнего боя в подземке
  1272. * (Исправление бесконечных карт)
  1273. */
  1274. let lastDungeonBattleData = null;
  1275. /**
  1276. * Start time of the last battle in the dungeon
  1277. *
  1278. * Время начала последнего боя в подземелье
  1279. */
  1280. let lastDungeonBattleStart = 0;
  1281.  
  1282. /**
  1283. * Brawl pack
  1284. *
  1285. * Пачка для потасовок
  1286. */
  1287. let brawlsPack = null;
  1288. /**
  1289. * Autobrawl started
  1290. *
  1291. * Автопотасовка запущена
  1292. */
  1293. let isBrawlsAutoStart = false;
  1294. /**
  1295. * Timer divider
  1296. *
  1297. * Делитель таймера
  1298. */
  1299. this.timerDiv = 1.5;
  1300. /**
  1301. * Copies the text to the clipboard
  1302. *
  1303. * Копирует тест в буфер обмена
  1304. * @param {*} text copied text // копируемый текст
  1305. */
  1306. function copyText(text) {
  1307. let copyTextarea = document.createElement("textarea");
  1308. copyTextarea.style.opacity = "0";
  1309. copyTextarea.textContent = text;
  1310. document.body.appendChild(copyTextarea);
  1311. copyTextarea.select();
  1312. document.execCommand("copy");
  1313. document.body.removeChild(copyTextarea);
  1314. delete copyTextarea;
  1315. }
  1316. /**
  1317. * Returns the history of requests
  1318. *
  1319. * Возвращает историю запросов
  1320. */
  1321. this.getRequestHistory = function() {
  1322. return requestHistory;
  1323. }
  1324. /**
  1325. * Generates a random integer from min to max
  1326. *
  1327. * Гененирует случайное целое число от min до max
  1328. */
  1329. const random = function (min, max) {
  1330. return Math.floor(Math.random() * (max - min + 1) + min);
  1331. }
  1332. /**
  1333. * Clearing the request history
  1334. *
  1335. * Очистка истоии запросов
  1336. */
  1337. setInterval(function () {
  1338. let now = Date.now();
  1339. for (let i in requestHistory) {
  1340. if (now - i > 300000) {
  1341. delete requestHistory[i];
  1342. }
  1343. }
  1344. }, 300000);
  1345. /**
  1346. * DOM Loading Event page
  1347. *
  1348. * Событие загрузки DOM дерева страницы
  1349. */
  1350. document.addEventListener("DOMContentLoaded", () => {
  1351. /**
  1352. * Create the script interface
  1353. *
  1354. * Создание интерфеса скрипта
  1355. */
  1356. createInterface();
  1357. });
  1358. /**
  1359. * Gift codes collecting and sending codes
  1360. *
  1361. * Сбор и отправка кодов подарков
  1362. */
  1363. function sendCodes() {
  1364. let codes = [], count = 0;
  1365. if (!localStorage['giftSendIds']) {
  1366. localStorage['giftSendIds'] = '';
  1367. }
  1368. document.querySelectorAll('a[target="_blank"]').forEach(e => {
  1369. let url = e?.href;
  1370. if (!url) return;
  1371. url = new URL(url);
  1372. let giftId = url.searchParams.get('gift_id');
  1373. if (!giftId || localStorage['giftSendIds'].includes(giftId)) return;
  1374. localStorage['giftSendIds'] += ';' + giftId;
  1375. codes.push(giftId);
  1376. count++;
  1377. });
  1378.  
  1379. if (codes.length) {
  1380. localStorage['giftSendIds'] = localStorage['giftSendIds'].split(';').splice(-50).join(';');
  1381. sendGiftsCodes(codes);
  1382. }
  1383.  
  1384. if (!count) {
  1385. setTimeout(sendCodes, 2000);
  1386. }
  1387. }
  1388. /**
  1389. * Checking sent codes
  1390. *
  1391. * Проверка отправленных кодов
  1392. */
  1393. function checkSendGifts() {
  1394. if (!freebieCheckInfo) {
  1395. return;
  1396. }
  1397.  
  1398. let giftId = freebieCheckInfo.args.giftId;
  1399. let valName = 'giftSendIds_' + userInfo.id;
  1400. localStorage[valName] = localStorage[valName] ?? '';
  1401. if (!localStorage[valName].includes(giftId)) {
  1402. localStorage[valName] += ';' + giftId;
  1403. sendGiftsCodes([giftId]);
  1404. }
  1405. }
  1406. /**
  1407. * Sending codes
  1408. *
  1409. * Отправка кодов
  1410. */
  1411. function sendGiftsCodes(codes) {
  1412. fetch('https://zingery.ru/heroes/setGifts.php', {
  1413. method: 'POST',
  1414. body: JSON.stringify(codes)
  1415. }).then(
  1416. response => response.json()
  1417. ).then(
  1418. data => {
  1419. if (data.result) {
  1420. console.log(I18N('GIFTS_SENT'));
  1421. }
  1422. }
  1423. )
  1424. }
  1425. /**
  1426. * Displays the dialog box
  1427. *
  1428. * Отображает диалоговое окно
  1429. */
  1430. function confShow(message, yesCallback, noCallback) {
  1431. let buts = [];
  1432. message = message || I18N('DO_YOU_WANT');
  1433. noCallback = noCallback || (() => {});
  1434. if (yesCallback) {
  1435. buts = [
  1436. { msg: I18N('BTN_RUN'), result: true},
  1437. { msg: I18N('BTN_CANCEL'), result: false},
  1438. ]
  1439. } else {
  1440. yesCallback = () => {};
  1441. buts = [
  1442. { msg: I18N('BTN_OK'), result: true},
  1443. ];
  1444. }
  1445. popup.confirm(message, buts).then((e) => {
  1446. if (e) {
  1447. yesCallback();
  1448. } else {
  1449. noCallback();
  1450. }
  1451. });
  1452. }
  1453. /**
  1454. * Overriding/Proxying the Ajax Request Creation Method
  1455. *
  1456. * Переопределяем/проксируем метод создания Ajax запроса
  1457. */
  1458. XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
  1459. this.uniqid = Date.now();
  1460. this.errorRequest = false;
  1461. if (method == 'POST' && url.includes('.nextersglobal.com/api/') && /api\/$/.test(url)) {
  1462. if (!apiUrl) {
  1463. apiUrl = url;
  1464. socialInfo = /heroes-(.+?)\./.exec(apiUrl);
  1465. sNetwork = socialInfo ? socialInfo[1] : 'vk';
  1466. }
  1467. requestHistory[this.uniqid] = {
  1468. method,
  1469. url,
  1470. error: [],
  1471. headers: {},
  1472. request: null,
  1473. response: null,
  1474. signature: [],
  1475. calls: {},
  1476. };
  1477. } else if (method == 'POST' && url.includes('error.nextersglobal.com/client/')) {
  1478. this.errorRequest = true;
  1479. }
  1480. return original.open.call(this, method, url, async, user, password);
  1481. };
  1482. /**
  1483. * Overriding/Proxying the header setting method for the AJAX request
  1484. *
  1485. * Переопределяем/проксируем метод установки заголовков для AJAX запроса
  1486. */
  1487. XMLHttpRequest.prototype.setRequestHeader = function (name, value, check) {
  1488. if (this.uniqid in requestHistory) {
  1489. requestHistory[this.uniqid].headers[name] = value;
  1490. } else {
  1491. check = true;
  1492. }
  1493.  
  1494. if (name == 'X-Auth-Signature') {
  1495. requestHistory[this.uniqid].signature.push(value);
  1496. if (!check) {
  1497. return;
  1498. }
  1499. }
  1500.  
  1501. return original.setRequestHeader.call(this, name, value);
  1502. };
  1503. /**
  1504. * Overriding/Proxying the AJAX Request Sending Method
  1505. *
  1506. * Переопределяем/проксируем метод отправки AJAX запроса
  1507. */
  1508. XMLHttpRequest.prototype.send = async function (sourceData) {
  1509. if (this.uniqid in requestHistory) {
  1510. let tempData = null;
  1511. if (getClass(sourceData) == "ArrayBuffer") {
  1512. tempData = decoder.decode(sourceData);
  1513. } else {
  1514. tempData = sourceData;
  1515. }
  1516. requestHistory[this.uniqid].request = tempData;
  1517. let headers = requestHistory[this.uniqid].headers;
  1518. lastHeaders = Object.assign({}, headers);
  1519. /**
  1520. * Game loading event
  1521. *
  1522. * Событие загрузки игры
  1523. */
  1524. if (headers["X-Request-Id"] > 2 && !isLoadGame) {
  1525. isLoadGame = true;
  1526. await openOrMigrateDatabase(userInfo.id);
  1527. await lib.load(cheats.libGame);
  1528. addControls();
  1529. addControlButtons();
  1530. addBottomUrls();
  1531.  
  1532. if (isChecked('sendExpedition')) {
  1533. checkExpedition();
  1534. }
  1535.  
  1536. checkSendGifts();
  1537. getAutoGifts();
  1538.  
  1539. cheats.activateHacks();
  1540. justInfo();
  1541. if (isChecked('dailyQuests')) {
  1542. testDailyQuests();
  1543. }
  1544.  
  1545. if (isChecked('secretWealth')) {
  1546. buyWithPetExperienceAuto();
  1547. }
  1548.  
  1549. if (isChecked('buyForGold')) {
  1550. buyInStoreForGold();
  1551. }
  1552. }
  1553. /**
  1554. * Outgoing request data processing
  1555. *
  1556. * Обработка данных исходящего запроса
  1557. */
  1558. sourceData = await checkChangeSend.call(this, sourceData, tempData);
  1559. /**
  1560. * Handling incoming request data
  1561. *
  1562. * Обработка данных входящего запроса
  1563. */
  1564. const oldReady = this.onreadystatechange;
  1565. this.onreadystatechange = function (e) {
  1566. if(this.readyState == 4 && this.status == 200) {
  1567. isTextResponse = this.responseType != "json";
  1568. let response = isTextResponse ? this.responseText : this.response;
  1569. requestHistory[this.uniqid].response = response;
  1570. /**
  1571. * Replacing incoming request data
  1572. *
  1573. * Заменна данных входящего запроса
  1574. */
  1575. if (isTextResponse) {
  1576. checkChangeResponse.call(this, response);
  1577. }
  1578. /**
  1579. * A function to run after the request is executed
  1580. *
  1581. * Функция запускаемая после выполения запроса
  1582. */
  1583. if (typeof this.onReadySuccess == 'function') {
  1584. setTimeout(this.onReadySuccess, 500);
  1585. }
  1586. }
  1587. if (oldReady) {
  1588. return oldReady.apply(this, arguments);
  1589. }
  1590. }
  1591. }
  1592. if (this.errorRequest) {
  1593. const oldReady = this.onreadystatechange;
  1594. this.onreadystatechange = function () {
  1595. Object.defineProperty(this, 'status', {
  1596. writable: true
  1597. });
  1598. this.status = 200;
  1599. Object.defineProperty(this, 'readyState', {
  1600. writable: true
  1601. });
  1602. this.readyState = 4;
  1603. Object.defineProperty(this, 'responseText', {
  1604. writable: true
  1605. });
  1606. this.responseText = JSON.stringify({
  1607. "result": true
  1608. });
  1609. return oldReady.apply(this, arguments);
  1610. }
  1611. this.onreadystatechange();
  1612. } else {
  1613. return original.send.call(this, sourceData);
  1614. }
  1615. };
  1616. /**
  1617. * Processing and substitution of outgoing data
  1618. *
  1619. * Обработка и подмена исходящих данных
  1620. */
  1621. async function checkChangeSend(sourceData, tempData) {
  1622. try {
  1623. /**
  1624. * A function that replaces battle data with incorrect ones to cancel combatя
  1625. *
  1626. * Функция заменяющая данные боя на неверные для отмены боя
  1627. */
  1628. const fixBattle = function (heroes) {
  1629. for (const ids in heroes) {
  1630. hero = heroes[ids];
  1631. hero.energy = random(1, 999);
  1632. if (hero.hp > 0) {
  1633. hero.hp = random(1, hero.hp);
  1634. }
  1635. }
  1636. }
  1637. /**
  1638. * Dialog window 2
  1639. *
  1640. * Диалоговое окно 2
  1641. */
  1642. const showMsg = async function (msg, ansF, ansS) {
  1643. if (typeof popup == 'object') {
  1644. return await popup.confirm(msg, [
  1645. {msg: ansF, result: false},
  1646. {msg: ansS, result: true},
  1647. ]);
  1648. } else {
  1649. return !confirm(`${msg}\n ${ansF} (${I18N('BTN_OK')})\n ${ansS} (${I18N('BTN_CANCEL')})`);
  1650. }
  1651. }
  1652. /**
  1653. * Dialog window 3
  1654. *
  1655. * Диалоговое окно 3
  1656. */
  1657. const showMsgs = async function (msg, ansF, ansS, ansT) {
  1658. return await popup.confirm(msg, [
  1659. {msg: ansF, result: 0},
  1660. {msg: ansS, result: 1},
  1661. {msg: ansT, result: 2},
  1662. ]);
  1663. }
  1664.  
  1665. let changeRequest = false;
  1666. testData = JSON.parse(tempData);
  1667. for (const call of testData.calls) {
  1668. if (!artifactChestOpen) {
  1669. requestHistory[this.uniqid].calls[call.name] = call.ident;
  1670. }
  1671. /**
  1672. * Cancellation of the battle in adventures, on VG and with minions of Asgard
  1673. * Отмена боя в приключениях, на ВГ и с прислужниками Асгарда
  1674. */
  1675. if ((call.name == 'adventure_endBattle' ||
  1676. call.name == 'adventureSolo_endBattle' ||
  1677. call.name == 'clanWarEndBattle' &&
  1678. isChecked('cancelBattle') ||
  1679. call.name == 'crossClanWar_endBattle' &&
  1680. isChecked('cancelBattle') ||
  1681. call.name == 'brawl_endBattle' ||
  1682. call.name == 'towerEndBattle' ||
  1683. call.name == 'clanRaid_endNodeBattle') &&
  1684. isCancalBattle) {
  1685. nameFuncEndBattle = call.name;
  1686. if (!call.args.result.win) {
  1687. let resultPopup = false;
  1688. if (call.name == 'adventure_endBattle' ||
  1689. call.name == 'adventureSolo_endBattle') {
  1690. resultPopup = await showMsgs(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_CANCEL'), I18N('BTN_AUTO'));
  1691. } else if (call.name == 'clanWarEndBattle' ||
  1692. call.name == 'crossClanWar_endBattle') {
  1693. resultPopup = await showMsg(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_AUTO_F5'));
  1694. } else {
  1695. resultPopup = await showMsg(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_CANCEL'));
  1696. }
  1697. if (resultPopup) {
  1698. fixBattle(call.args.progress[0].attackers.heroes);
  1699. fixBattle(call.args.progress[0].defenders.heroes);
  1700. changeRequest = true;
  1701. if (resultPopup > 1) {
  1702. this.onReadySuccess = testAutoBattle;
  1703. // setTimeout(bossBattle, 1000);
  1704. }
  1705. }
  1706. } else if (call.args.result.stars < 3 && call.name == 'towerEndBattle') {
  1707. resultPopup = await showMsg(I18N('LOST_HEROES'), I18N('BTN_OK'), I18N('BTN_CANCEL'));
  1708. if (resultPopup) {
  1709. fixBattle(call.args.progress[0].attackers.heroes);
  1710. fixBattle(call.args.progress[0].defenders.heroes);
  1711. changeRequest = true;
  1712. }
  1713. }
  1714. /*
  1715. if (isChecked('autoBrawls') && !isBrawlsAutoStart && call.name == 'brawl_endBattle') {
  1716. if (await popup.confirm(I18N('START_AUTO_BRAWLS'), [
  1717. { msg: I18N('BTN_NO'), result: false },
  1718. { msg: I18N('BTN_YES'), result: true },
  1719. ])) {
  1720. this.onReadySuccess = testBrawls;
  1721. isBrawlsAutoStart = true;
  1722. }
  1723. }
  1724. */
  1725. }
  1726. /**
  1727. * Save pack for Brawls
  1728. *
  1729. * Сохраняем пачку для потасовок
  1730. */
  1731. if (call.name == 'brawl_startBattle') {
  1732. console.log(JSON.stringify(call.args));
  1733. brawlsPack = call.args.heroes;
  1734. }
  1735. /**
  1736. * Canceled fight in Asgard
  1737. * Отмена боя в Асгарде
  1738. */
  1739. if (call.name == 'clanRaid_endBossBattle' &&
  1740. isCancalBossBattle &&
  1741. isChecked('cancelBattle')) {
  1742. bossDamage = call.args.progress[0].defenders.heroes[1].extra;
  1743. sumDamage = bossDamage.damageTaken + bossDamage.damageTakenNextLevel;
  1744. let resultPopup = await showMsgs(
  1745. `${I18N('MSG_YOU_APPLIED')} ${sumDamage.toLocaleString()} ${I18N('MSG_DAMAGE')}.`,
  1746. I18N('BTN_OK'), I18N('BTN_AUTO_F5'), I18N('MSG_CANCEL_AND_STAT'))
  1747. if (resultPopup) {
  1748. fixBattle(call.args.progress[0].attackers.heroes);
  1749. fixBattle(call.args.progress[0].defenders.heroes);
  1750. changeRequest = true;
  1751. if (resultPopup > 1) {
  1752. this.onReadySuccess = testBossBattle;
  1753. // setTimeout(bossBattle, 1000);
  1754. }
  1755. }
  1756. }
  1757. /**
  1758. * Save the Asgard Boss Attack Pack
  1759. * Сохраняем пачку для атаки босса Асгарда
  1760. */
  1761. if (call.name == 'clanRaid_startBossBattle') {
  1762. lastBossBattle = call.args;
  1763. }
  1764. /**
  1765. * Saving the request to start the last battle
  1766. * Сохранение запроса начала последнего боя
  1767. */
  1768. if (call.name == 'clanWarAttack' ||
  1769. call.name == 'crossClanWar_startBattle' ||
  1770. call.name == 'adventure_turnStartBattle') {
  1771. nameFuncStartBattle = call.name;
  1772. lastBattleArg = call.args;
  1773. }
  1774. /**
  1775. * Disable spending divination cards
  1776. * Отключить трату карт предсказаний
  1777. */
  1778. if (call.name == 'dungeonEndBattle') {
  1779. if (call.args.isRaid && isChecked('endlessCards')) {
  1780. delete call.args.isRaid;
  1781. changeRequest = true;
  1782. }
  1783. /**
  1784. * Fix endless cards
  1785. * Исправление бесконечных карт
  1786. */
  1787. const lastBattle = lastDungeonBattleData;
  1788. if (!call.args.isRaid) {
  1789. lastBattle.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  1790. const result = await Calc(lastBattle);
  1791. if (isChecked('endlessCards')) {
  1792. call.args.progress = result.progress;
  1793. call.args.result = result.result;
  1794. changeRequest = true;
  1795. }
  1796. let timer = Math.max(result.battleTime / timerDiv + 1.5, 3);
  1797. const period = Math.ceil((Date.now() - lastDungeonBattleStart) / 1000);
  1798. if (period < timer) {
  1799. timer = timer - period;
  1800. }
  1801. console.log(timer);
  1802. await countdownTimer(timer);
  1803. }
  1804. }
  1805. /**
  1806. * Quiz Answer
  1807. * Ответ на викторину
  1808. */
  1809. if (call.name == 'quizAnswer') {
  1810. /**
  1811. * Automatically changes the answer to the correct one if there is one.
  1812. * Автоматически меняет ответ на правильный если он есть
  1813. */
  1814. if (lastAnswer && isChecked('getAnswer')) {
  1815. call.args.answerId = lastAnswer;
  1816. lastAnswer = null;
  1817. changeRequest = true;
  1818. }
  1819. }
  1820. /**
  1821. * Present
  1822. * Подарки
  1823. */
  1824. if (call.name == 'freebieCheck') {
  1825. freebieCheckInfo = call;
  1826. }
  1827. /**
  1828. * Getting mission data for auto-repeat
  1829. * Получение данных миссии для автоповтора
  1830. */
  1831. if (isChecked('repeatMission') &&
  1832. call.name == 'missionEnd') {
  1833. let missionInfo = {
  1834. id: call.args.id,
  1835. result: call.args.result,
  1836. heroes: call.args.progress[0].attackers.heroes,
  1837. count: 0,
  1838. }
  1839. setTimeout(async () => {
  1840. if (!isSendsMission && await popup.confirm(I18N('MSG_REPEAT_MISSION'), [
  1841. { msg: I18N('BTN_REPEAT'), result: true},
  1842. { msg: I18N('BTN_NO'), result: false},
  1843. ])) {
  1844. isStopSendMission = false;
  1845. isSendsMission = true;
  1846. sendsMission(missionInfo);
  1847. }
  1848. }, 0);
  1849. }
  1850. /**
  1851. * Getting mission data
  1852. * Получение данных миссии
  1853. */
  1854. if (call.name == 'missionStart') {
  1855. lastMissionStart = call.args;
  1856. }
  1857. /**
  1858. * Specify the quantity for Titan Orbs and Pet Eggs
  1859. * Указать количество для сфер титанов и яиц петов
  1860. */
  1861. if (isChecked('countControl') &&
  1862. (call.name == 'pet_chestOpen' ||
  1863. call.name == 'titanUseSummonCircle') &&
  1864. call.args.amount > 1) {
  1865. call.args.amount = 1;
  1866. const result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  1867. { msg: I18N('BTN_OPEN'), isInput: true, default: call.args.amount},
  1868. ]);
  1869. if (result) {
  1870. call.args.amount = result;
  1871. changeRequest = true;
  1872. }
  1873. }
  1874. /**
  1875. * Specify the amount for keys and spheres of titan artifacts
  1876. * Указать колличество для ключей и сфер артефактов титанов
  1877. */
  1878. if (isChecked('countControl') &&
  1879. (call.name == 'artifactChestOpen' ||
  1880. call.name == 'titanArtifactChestOpen') &&
  1881. call.args.amount > 1 &&
  1882. call.args.free &&
  1883. !changeRequest) {
  1884. artifactChestOpenCallName = call.name;
  1885. let result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  1886. { msg: I18N('BTN_OPEN'), isInput: true, default: call.args.amount },
  1887. ]);
  1888. if (result) {
  1889. let sphere = result < 10 ? 1 : 10;
  1890.  
  1891. call.args.amount = sphere;
  1892. result -= sphere;
  1893.  
  1894. for (let count = result; count > 0; count -= sphere) {
  1895. if (count < 10) sphere = 1;
  1896. const ident = artifactChestOpenCallName + "_" + count;
  1897. testData.calls.push({
  1898. name: artifactChestOpenCallName,
  1899. args: {
  1900. amount: sphere,
  1901. free: true,
  1902. },
  1903. ident: ident
  1904. });
  1905. if (!Array.isArray(requestHistory[this.uniqid].calls[call.name])) {
  1906. requestHistory[this.uniqid].calls[call.name] = [requestHistory[this.uniqid].calls[call.name]];
  1907. }
  1908. requestHistory[this.uniqid].calls[call.name].push(ident);
  1909. }
  1910.  
  1911. artifactChestOpen = true;
  1912. changeRequest = true;
  1913. }
  1914. }
  1915. if (call.name == 'consumableUseLootBox') {
  1916. lastRussianDollId = call.args.libId;
  1917. /**
  1918. * Specify quantity for gold caskets
  1919. * Указать количество для золотых шкатулок
  1920. */
  1921. if (isChecked('countControl') &&
  1922. call.args.libId == 148 &&
  1923. call.args.amount > 1) {
  1924. const result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  1925. { msg: I18N('BTN_OPEN'), isInput: true, default: call.args.amount},
  1926. ]);
  1927. call.args.amount = result;
  1928. changeRequest = true;
  1929. }
  1930. }
  1931. /**
  1932. * Adding a request to receive 26 store
  1933. * Добавление запроса на получение 26 магазина
  1934. */
  1935. if (call.name == 'registration') {
  1936. testData.calls.push({
  1937. name: "shopGet",
  1938. args: {
  1939. shopId: "26"
  1940. },
  1941. ident: "shopGet"
  1942. });
  1943. changeRequest = true;
  1944. }
  1945. /**
  1946. * Changing the maximum number of raids in the campaign
  1947. * Изменение максимального количества рейдов в кампании
  1948. */
  1949. // if (call.name == 'missionRaid') {
  1950. // if (isChecked('countControl') && call.args.times > 1) {
  1951. // const result = +(await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  1952. // { msg: I18N('BTN_RUN'), isInput: true, default: call.args.times },
  1953. // ]));
  1954. // call.args.times = result > call.args.times ? call.args.times : result;
  1955. // changeRequest = true;
  1956. // }
  1957. // }
  1958. }
  1959.  
  1960. let headers = requestHistory[this.uniqid].headers;
  1961. if (changeRequest) {
  1962. sourceData = JSON.stringify(testData);
  1963. headers['X-Auth-Signature'] = getSignature(headers, sourceData);
  1964. }
  1965.  
  1966. let signature = headers['X-Auth-Signature'];
  1967. if (signature) {
  1968. original.setRequestHeader.call(this, 'X-Auth-Signature', signature);
  1969. }
  1970. } catch (err) {
  1971. console.log("Request(send, " + this.uniqid + "):\n", sourceData, "Error:\n", err);
  1972. }
  1973. return sourceData;
  1974. }
  1975. /**
  1976. * Processing and substitution of incoming data
  1977. *
  1978. * Обработка и подмена входящих данных
  1979. */
  1980. async function checkChangeResponse(response) {
  1981. try {
  1982. isChange = false;
  1983. let nowTime = Math.round(Date.now() / 1000);
  1984. callsIdent = requestHistory[this.uniqid].calls;
  1985. respond = JSON.parse(response);
  1986. /**
  1987. * If the request returned an error removes the error (removes synchronization errors)
  1988. * Если запрос вернул ошибку удаляет ошибку (убирает ошибки синхронизации)
  1989. */
  1990. if (respond.error) {
  1991. isChange = true;
  1992. console.error(respond.error);
  1993. if (isChecked('showErrors')) {
  1994. popup.confirm(I18N('ERROR_MSG', {
  1995. name: respond.error.name,
  1996. description: respond.error.description,
  1997. }));
  1998. }
  1999. delete respond.error;
  2000. respond.results = [];
  2001. }
  2002. let mainReward = null;
  2003. const allReward = {};
  2004. let readQuestInfo = false;
  2005. for (const call of respond.results) {
  2006. /**
  2007. * Obtaining initial data for completing quests
  2008. * Получение исходных данных для выполнения квестов
  2009. */
  2010. if (readQuestInfo) {
  2011. questsInfo[call.ident] = call.result.response;
  2012. }
  2013. /**
  2014. * Getting a user ID
  2015. * Получение идетификатора пользователя
  2016. */
  2017. if (call.ident == callsIdent['registration']) {
  2018. userId = call.result.response.userId;
  2019. readQuestInfo = true;
  2020. }
  2021. /**
  2022. * Endless lives in brawls
  2023. * Бесконечные жизни в потасовках
  2024. */
  2025. if (getSaveVal('autoBrawls') && call.ident == callsIdent['brawl_getInfo']) {
  2026. brawl = call.result.response;
  2027. if (brawl) {
  2028. brawl.boughtEndlessLivesToday = 1;
  2029. isChange = true;
  2030. }
  2031. }
  2032. /**
  2033. * Hiding donation offers 1
  2034. * Скрываем предложения доната 1
  2035. */
  2036. if (call.ident == callsIdent['billingGetAll'] && getSaveVal('noOfferDonat')) {
  2037. const billings = call.result.response?.billings;
  2038. const bundle = call.result.response?.bundle;
  2039. if (billings && bundle) {
  2040. call.result.response.billings = [];
  2041. call.result.response.bundle = [];
  2042. isChange = true;
  2043. }
  2044. }
  2045. /**
  2046. * Hiding donation offers 2
  2047. * Скрываем предложения доната 2
  2048. */
  2049. if (getSaveVal('noOfferDonat') &&
  2050. (call.ident == callsIdent['offerGetAll'] ||
  2051. call.ident == callsIdent['specialOffer_getAll'])) {
  2052. let offers = call.result.response;
  2053. if (offers) {
  2054. call.result.response = offers.filter(e => !['addBilling', 'bundleCarousel'].includes(e.type));
  2055. isChange = true;
  2056. }
  2057. }
  2058. /**
  2059. * Hiding donation offers 3
  2060. * Скрываем предложения доната 3
  2061. */
  2062. if (getSaveVal('noOfferDonat') && call.result?.bundleUpdate) {
  2063. delete call.result.bundleUpdate;
  2064. isChange = true;
  2065. }
  2066. /**
  2067. * Copies a quiz question to the clipboard
  2068. * Копирует вопрос викторины в буфер обмена и получает на него ответ если есть
  2069. */
  2070. if (call.ident == callsIdent['quizGetNewQuestion']) {
  2071. let quest = call.result.response;
  2072. console.log(quest.question);
  2073. copyText(quest.question);
  2074. setProgress(I18N('QUESTION_COPY'), true);
  2075. quest.lang = null;
  2076. if (typeof NXFlashVars !== 'undefined') {
  2077. quest.lang = NXFlashVars.interface_lang;
  2078. }
  2079. lastQuestion = quest;
  2080. if (isChecked('getAnswer')) {
  2081. const answer = await getAnswer(lastQuestion);
  2082. if (answer) {
  2083. lastAnswer = answer;
  2084. console.log(answer);
  2085. setProgress(`${I18N('ANSWER_KNOWN')}: ${answer}`, true);
  2086. } else {
  2087. setProgress(I18N('ANSWER_NOT_KNOWN'), true);
  2088. }
  2089. }
  2090. }
  2091. /**
  2092. * Submits a question with an answer to the database
  2093. * Отправляет вопрос с ответом в базу данных
  2094. */
  2095. if (call.ident == callsIdent['quizAnswer']) {
  2096. const answer = call.result.response;
  2097. if (lastQuestion) {
  2098. const answerInfo = {
  2099. answer,
  2100. question: lastQuestion,
  2101. lang: null,
  2102. }
  2103. if (typeof NXFlashVars !== 'undefined') {
  2104. answerInfo.lang = NXFlashVars.interface_lang;
  2105. }
  2106. lastQuestion = null;
  2107. setTimeout(sendAnswerInfo, 0, answerInfo);
  2108. }
  2109. }
  2110. /**
  2111. * Get user data
  2112. * Получить даныне пользователя
  2113. */
  2114. if (call.ident == callsIdent['userGetInfo']) {
  2115. let user = call.result.response;
  2116. userInfo = Object.assign({}, user);
  2117. delete userInfo.refillable;
  2118. if (!questsInfo['userGetInfo']) {
  2119. questsInfo['userGetInfo'] = user;
  2120. }
  2121. }
  2122. /**
  2123. * Start of the battle for recalculation
  2124. * Начало боя для прерасчета
  2125. */
  2126. if ((call.ident == callsIdent['clanWarAttack'] ||
  2127. call.ident == callsIdent['crossClanWar_startBattle'] ||
  2128. call.ident == callsIdent['battleGetReplay'] ||
  2129. call.ident == callsIdent['adventureSolo_turnStartBattle'] ||
  2130. call.ident == callsIdent['adventure_turnStartBattle']) &&
  2131. isChecked('preCalcBattle')) {
  2132. setProgress('Идет прерасчет боя');
  2133. let battle = call.result.response.battle || call.result.response.replay;
  2134. lastBattleInfo = battle;
  2135. console.log(battle.type);
  2136. function getBattleInfo(battle, isRandSeed) {
  2137. return new Promise(function (resolve) {
  2138. if (isRandSeed) {
  2139. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  2140. }
  2141. BattleCalc(battle, getBattleType(battle.type), e => resolve(e.result.win));
  2142. });
  2143. }
  2144. let actions = [getBattleInfo(battle, false)]
  2145. const countTestBattle = getInput('countTestBattle');
  2146. if (call.ident == callsIdent['battleGetReplay']) {
  2147. battle.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  2148. }
  2149. for (let i = 0; i < countTestBattle; i++) {
  2150. actions.push(getBattleInfo(battle, true));
  2151. }
  2152. Promise.all(actions)
  2153. .then(e => {
  2154. let firstBattle = e.shift();
  2155. let countWin = e.reduce((w, s) => w + s);
  2156. setProgress(`${I18N('THIS_TIME')} ${(firstBattle ? I18N('VICTORY') : I18N('DEFEAT'))} ${I18N('CHANCE_TO_WIN')}: ${Math.floor(countWin / e.length * 100)}% (${e.length})`, false, hideProgress)
  2157. });
  2158. }
  2159. /**
  2160. * Start of the Asgard boss fight
  2161. * Начало боя с боссом Асгарда
  2162. */
  2163. if (call.ident == callsIdent['clanRaid_startBossBattle']) {
  2164. lastBossBattleInfo = call.result.response.battle;
  2165. if (isChecked('preCalcBattle')) {
  2166. const result = await Calc(lastBossBattleInfo).then(e => e.progress[0].defenders.heroes[1].extra);
  2167. const bossDamage = result.damageTaken + result.damageTakenNextLevel;
  2168. setProgress(I18N('BOSS_DAMAGE') + bossDamage.toLocaleString(), false, hideProgress);
  2169. }
  2170. }
  2171. /**
  2172. * Cancel tutorial
  2173. * Отмена туториала
  2174. */
  2175. if (isCanceledTutorial && call.ident == callsIdent['tutorialGetInfo']) {
  2176. let chains = call.result.response.chains;
  2177. for (let n in chains) {
  2178. chains[n] = 9999;
  2179. }
  2180. isChange = true;
  2181. }
  2182. /**
  2183. * Opening keys and spheres of titan artifacts
  2184. * Открытие ключей и сфер артефактов титанов
  2185. */
  2186. if (artifactChestOpen &&
  2187. (call.ident == callsIdent[artifactChestOpenCallName] ||
  2188. (callsIdent[artifactChestOpenCallName] && callsIdent[artifactChestOpenCallName].includes(call.ident)))) {
  2189. let reward = call.result.response[artifactChestOpenCallName == 'artifactChestOpen' ? 'chestReward' : 'reward'];
  2190.  
  2191. reward.forEach(e => {
  2192. for (let f in e) {
  2193. if (!allReward[f]) {
  2194. allReward[f] = {};
  2195. }
  2196. for (let o in e[f]) {
  2197. if (!allReward[f][o]) {
  2198. allReward[f][o] = e[f][o];
  2199. } else {
  2200. allReward[f][o] += e[f][o];
  2201. }
  2202. }
  2203. }
  2204. });
  2205.  
  2206. if (!call.ident.includes(artifactChestOpenCallName)) {
  2207. mainReward = call.result.response;
  2208. }
  2209. }
  2210. /**
  2211. * Sum the result of opening Pet Eggs
  2212. * Суммирование результата открытия яиц питомцев
  2213. */
  2214. if (isChecked('countControl') && call.ident == callsIdent['pet_chestOpen']) {
  2215. const rewards = call.result.response.rewards;
  2216. rewards.forEach(e => {
  2217. for (let f in e) {
  2218. if (!allReward[f]) {
  2219. allReward[f] = {};
  2220. }
  2221. for (let o in e[f]) {
  2222. if (!allReward[f][o]) {
  2223. allReward[f][o] = e[f][o];
  2224. } else {
  2225. allReward[f][o] += e[f][o];
  2226. }
  2227. }
  2228. }
  2229. });
  2230. call.result.response.rewards = [allReward];
  2231. isChange = true;
  2232. }
  2233. /**
  2234. * Auto-repeat opening matryoshkas
  2235. * АвтоПовтор открытия матрешек
  2236. */
  2237. if (isChecked('countControl') && call.ident == callsIdent['consumableUseLootBox']) {
  2238. let lootBox = call.result.response;
  2239. let newCount = 0;
  2240. for (let n of lootBox) {
  2241. if (n?.consumable && n.consumable[lastRussianDollId]) {
  2242. newCount += n.consumable[lastRussianDollId]
  2243. }
  2244. }
  2245. if (newCount && await popup.confirm(`${I18N('BTN_OPEN')} ${newCount} ${I18N('OPEN_DOLLS')}?`, [
  2246. { msg: I18N('BTN_OPEN'), result: true},
  2247. { msg: I18N('BTN_NO'), result: false},
  2248. ])) {
  2249. openRussianDoll(lastRussianDollId, newCount);
  2250. }
  2251. }
  2252. /**
  2253. * Dungeon recalculation (fix endless cards)
  2254. * Прерасчет подземки (исправление бесконечных карт)
  2255. */
  2256. if (call.ident == callsIdent['dungeonStartBattle']) {
  2257. lastDungeonBattleData = call.result.response;
  2258. lastDungeonBattleStart = Date.now();
  2259. }
  2260. /**
  2261. * Adding 26 store to other stores
  2262. * Добавление 26 магазина к остальным магазинам
  2263. */
  2264. if (call.ident == callsIdent['shopGetAll']) {
  2265. const shop26 = respond.results.find(e => e.ident == callsIdent['shopGet']);
  2266. if (shop26) {
  2267. call.result.response[26] = shop26.result.response;
  2268. isChange = true;
  2269. }
  2270. }
  2271. /**
  2272. * Getting subscription status
  2273. * Получение состояния подписки
  2274. */
  2275. if (call.ident == callsIdent['subscriptionGetInfo']) {
  2276. if (call.result.response.subscription) {
  2277. const now = Math.round(Date.now() / 1000);
  2278. const endTime = call.result.response.subscription.endTime;
  2279. if (endTime > now) {
  2280. timerDiv = 5;
  2281. }
  2282. }
  2283. }
  2284. }
  2285.  
  2286. if (mainReward && artifactChestOpen) {
  2287. console.log(allReward);
  2288. mainReward[artifactChestOpenCallName == 'artifactChestOpen' ? 'chestReward' : 'reward'] = [allReward];
  2289. artifactChestOpen = false;
  2290. artifactChestOpenCallName = '';
  2291. isChange = true;
  2292. }
  2293. } catch(err) {
  2294. console.log("Request(response, " + this.uniqid + "):\n", "Error:\n", response, err);
  2295. }
  2296.  
  2297. if (isChange) {
  2298. Object.defineProperty(this, 'responseText', {
  2299. writable: true
  2300. });
  2301. this.responseText = JSON.stringify(respond);
  2302. }
  2303. }
  2304.  
  2305. /**
  2306. * Request an answer to a question
  2307. *
  2308. * Запрос ответа на вопрос
  2309. */
  2310. async function getAnswer(question) {
  2311. return new Promise((resolve, reject) => {
  2312. fetch('https://zingery.ru/heroes/getAnswer.php', {
  2313. method: 'POST',
  2314. body: JSON.stringify(question)
  2315. }).then(
  2316. response => response.json()
  2317. ).then(
  2318. data => {
  2319. if (data.result) {
  2320. resolve(data.result);
  2321. } else {
  2322. resolve(false);
  2323. }
  2324. }
  2325. ).catch((error) => {
  2326. console.error(error);
  2327. resolve(false);
  2328. });
  2329. })
  2330. }
  2331.  
  2332. /**
  2333. * Submitting a question and answer to a database
  2334. *
  2335. * Отправка вопроса и ответа в базу данных
  2336. */
  2337. function sendAnswerInfo(answerInfo) {
  2338. fetch('https://zingery.ru/heroes/setAnswer.php', {
  2339. method: 'POST',
  2340. body: JSON.stringify(answerInfo)
  2341. }).then(
  2342. response => response.json()
  2343. ).then(
  2344. data => {
  2345. if (data.result) {
  2346. console.log(I18N('SENT_QUESTION'));
  2347. }
  2348. }
  2349. )
  2350. }
  2351.  
  2352. /**
  2353. * Returns the battle type by preset type
  2354. *
  2355. * Возвращает тип боя по типу пресета
  2356. */
  2357. function getBattleType(strBattleType) {
  2358. switch (strBattleType) {
  2359. case "invasion":
  2360. return "get_invasion";
  2361. case "titan_pvp_manual":
  2362. return "get_titanPvpManual";
  2363. case "titan_pvp":
  2364. return "get_titanPvp";
  2365. case "titan_clan_pvp":
  2366. case "clan_pvp_titan":
  2367. case "clan_global_pvp_titan":
  2368. case "brawl_titan":
  2369. case "challenge_titan":
  2370. return "get_titanClanPvp";
  2371. case "clan_raid": // Asgard Boss // Босс асгарда
  2372. case "adventure": // Adventures // Приключения
  2373. case "clan_global_pvp":
  2374. case "clan_pvp":
  2375. case "challenge":
  2376. return "get_clanPvp";
  2377. case "dungeon_titan":
  2378. case "titan_tower":
  2379. return "get_titan";
  2380. case "tower":
  2381. case "clan_dungeon":
  2382. return "get_tower";
  2383. case "pve":
  2384. return "get_pve";
  2385. case "pvp_manual":
  2386. return "get_pvpManual";
  2387. case "grand":
  2388. case "arena":
  2389. case "pvp":
  2390. return "get_pvp";
  2391. case "core":
  2392. return "get_core";
  2393. case "boss_10":
  2394. case "boss_11":
  2395. case "boss_12":
  2396. return "get_boss";
  2397. default:
  2398. return "get_clanPvp";
  2399. }
  2400. }
  2401. /**
  2402. * Returns the class name of the passed object
  2403. *
  2404. * Возвращает название класса переданного объекта
  2405. */
  2406. function getClass(obj) {
  2407. return {}.toString.call(obj).slice(8, -1);
  2408. }
  2409. /**
  2410. * Calculates the request signature
  2411. *
  2412. * Расчитывает сигнатуру запроса
  2413. */
  2414. this.getSignature = function(headers, data) {
  2415. const sign = {
  2416. signature: '',
  2417. length: 0,
  2418. add: function (text) {
  2419. this.signature += text;
  2420. if (this.length < this.signature.length) {
  2421. this.length = 3 * (this.signature.length + 1) >> 1;
  2422. }
  2423. },
  2424. }
  2425. sign.add(headers["X-Request-Id"]);
  2426. sign.add(':');
  2427. sign.add(headers["X-Auth-Token"]);
  2428. sign.add(':');
  2429. sign.add(headers["X-Auth-Session-Id"]);
  2430. sign.add(':');
  2431. sign.add(data);
  2432. sign.add(':');
  2433. sign.add('LIBRARY-VERSION=1');
  2434. sign.add('UNIQUE-SESSION-ID=' + headers["X-Env-Unique-Session-Id"]);
  2435.  
  2436. return md5(sign.signature);
  2437. }
  2438. /**
  2439. * Creates an interface
  2440. *
  2441. * Создает интерфейс
  2442. */
  2443. function createInterface() {
  2444. scriptMenu.init({
  2445. showMenu: true
  2446. });
  2447. scriptMenu.addHeader(GM_info.script.name, justInfo);
  2448. scriptMenu.addHeader('v' + GM_info.script.version);
  2449. }
  2450.  
  2451. function addControls() {
  2452. const checkboxDetails = scriptMenu.addDetails(I18N('SETTINGS'));
  2453. for (let name in checkboxes) {
  2454. checkboxes[name].cbox = scriptMenu.addCheckbox(checkboxes[name].label, checkboxes[name].title, checkboxDetails);
  2455. /**
  2456. * Getting the state of checkboxes from storage
  2457. * Получаем состояние чекбоксов из storage
  2458. */
  2459. let val = storage.get(name, null);
  2460. if (val != null) {
  2461. checkboxes[name].cbox.checked = val;
  2462. } else {
  2463. storage.set(name, checkboxes[name].default);
  2464. checkboxes[name].cbox.checked = checkboxes[name].default;
  2465. }
  2466. /**
  2467. * Tracing the change event of the checkbox for writing to storage
  2468. * Отсеживание события изменения чекбокса для записи в storage
  2469. */
  2470. checkboxes[name].cbox.dataset['name'] = name;
  2471. checkboxes[name].cbox.addEventListener('change', async function (event) {
  2472. const nameCheckbox = this.dataset['name'];
  2473. /*
  2474. if (this.checked && nameCheckbox == 'cancelBattle') {
  2475. this.checked = false;
  2476. if (await popup.confirm(I18N('MSG_BAN_ATTENTION'), [
  2477. { msg: I18N('BTN_NO_I_AM_AGAINST'), result: true },
  2478. { msg: I18N('BTN_YES_I_AGREE'), result: false },
  2479. ])) {
  2480. return;
  2481. }
  2482. this.checked = true;
  2483. }
  2484. */
  2485. storage.set(nameCheckbox, this.checked);
  2486. })
  2487. }
  2488.  
  2489. const inputDetails = scriptMenu.addDetails(I18N('VALUES'));
  2490. for (let name in inputs) {
  2491. inputs[name].input = scriptMenu.addInputText(inputs[name].title, false, inputDetails);
  2492. /**
  2493. * Get inputText state from storage
  2494. * Получаем состояние inputText из storage
  2495. */
  2496. let val = storage.get(name, null);
  2497. if (val != null) {
  2498. inputs[name].input.value = val;
  2499. } else {
  2500. storage.set(name, inputs[name].default);
  2501. inputs[name].input.value = inputs[name].default;
  2502. }
  2503. /**
  2504. * Tracing a field change event for a record in storage
  2505. * Отсеживание события изменения поля для записи в storage
  2506. */
  2507. inputs[name].input.dataset['name'] = name;
  2508. inputs[name].input.addEventListener('input', function () {
  2509. const inputName = this.dataset['name'];
  2510. let value = +this.value;
  2511. if (!value || Number.isNaN(value)) {
  2512. value = storage.get(inputName, inputs[inputName].default);
  2513. inputs[name].input.value = value;
  2514. }
  2515. storage.set(inputName, value);
  2516. })
  2517. }
  2518. }
  2519.  
  2520. /**
  2521. * Sending a request
  2522. *
  2523. * Отправка запроса
  2524. */
  2525. function send(json, callback, pr) {
  2526. if (typeof json == 'string') {
  2527. json = JSON.parse(json);
  2528. }
  2529. for (const call of json.calls) {
  2530. if (!call?.context?.actionTs) {
  2531. call.context = {
  2532. actionTs: performance.now()
  2533. }
  2534. }
  2535. }
  2536. json = JSON.stringify(json);
  2537. /**
  2538. * We get the headlines of the previous intercepted request
  2539. * Получаем заголовки предыдущего перехваченого запроса
  2540. */
  2541. let headers = lastHeaders;
  2542. /**
  2543. * We increase the header of the query Certifier by 1
  2544. * Увеличиваем заголовок идетификатора запроса на 1
  2545. */
  2546. headers["X-Request-Id"]++;
  2547. /**
  2548. * We calculate the title with the signature
  2549. * Расчитываем заголовок с сигнатурой
  2550. */
  2551. headers["X-Auth-Signature"] = getSignature(headers, json);
  2552. /**
  2553. * Create a new ajax request
  2554. * Создаем новый AJAX запрос
  2555. */
  2556. let xhr = new XMLHttpRequest;
  2557. /**
  2558. * Indicate the previously saved URL for API queries
  2559. * Указываем ранее сохраненный URL для API запросов
  2560. */
  2561. xhr.open('POST', apiUrl, true);
  2562. /**
  2563. * Add the function to the event change event
  2564. * Добавляем функцию к событию смены статуса запроса
  2565. */
  2566. xhr.onreadystatechange = function() {
  2567. /**
  2568. * If the result of the request is obtained, we call the flask function
  2569. * Если результат запроса получен вызываем колбек функцию
  2570. */
  2571. if(xhr.readyState == 4) {
  2572. let randTimeout = Math.random() * 200 + 200;
  2573. setTimeout(callback, randTimeout, xhr.response, pr);
  2574. }
  2575. };
  2576. /**
  2577. * Indicate the type of request
  2578. * Указываем тип запроса
  2579. */
  2580. xhr.responseType = 'json';
  2581. /**
  2582. * We set the request headers
  2583. * Задаем заголовки запроса
  2584. */
  2585. for(let nameHeader in headers) {
  2586. let head = headers[nameHeader];
  2587. xhr.setRequestHeader(nameHeader, head);
  2588. }
  2589. /**
  2590. * Sending a request
  2591. * Отправляем запрос
  2592. */
  2593. xhr.send(json);
  2594. }
  2595.  
  2596. let hideTimeoutProgress = 0;
  2597. /**
  2598. * Hide progress
  2599. *
  2600. * Скрыть прогресс
  2601. */
  2602. function hideProgress(timeout) {
  2603. timeout = timeout || 0;
  2604. clearTimeout(hideTimeoutProgress);
  2605. hideTimeoutProgress = setTimeout(function () {
  2606. scriptMenu.setStatus('');
  2607. }, timeout);
  2608. }
  2609. /**
  2610. * Progress display
  2611. *
  2612. * Отображение прогресса
  2613. */
  2614. function setProgress(text, hide, onclick) {
  2615. scriptMenu.setStatus(text, onclick);
  2616. hide = hide || false;
  2617. if (hide) {
  2618. hideProgress(3000);
  2619. }
  2620. }
  2621.  
  2622. /**
  2623. * Calculates HASH MD5 from string
  2624. *
  2625. * Расчитывает HASH MD5 из строки
  2626. *
  2627. * [js-md5]{@link https://github.com/emn178/js-md5}
  2628. *
  2629. * @namespace md5
  2630. * @version 0.7.3
  2631. * @author Chen, Yi-Cyuan [emn178@gmail.com]
  2632. * @copyright Chen, Yi-Cyuan 2014-2017
  2633. * @license MIT
  2634. */
  2635. !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 _}))}();
  2636.  
  2637. /**
  2638. * Script for beautiful dialog boxes
  2639. *
  2640. * Скрипт для красивых диалоговых окошек
  2641. */
  2642. const popup = new (function () {
  2643. this.popUp,
  2644. this.downer,
  2645. this.middle,
  2646. this.msgText,
  2647. this.buttons = [];
  2648. this.checkboxes = [];
  2649.  
  2650. function init() {
  2651. addStyle();
  2652. addBlocks();
  2653. }
  2654.  
  2655. const addStyle = () => {
  2656. let style = document.createElement('style');
  2657. style.innerText = `
  2658. .PopUp_ {
  2659. position: absolute;
  2660. min-width: 300px;
  2661. max-width: 500px;
  2662. max-height: 500px;
  2663. background-color: #190e08e6;
  2664. z-index: 10001;
  2665. top: 169px;
  2666. left: 345px;
  2667. border: 3px #ce9767 solid;
  2668. border-radius: 10px;
  2669. display: flex;
  2670. flex-direction: column;
  2671. justify-content: space-around;
  2672. padding: 15px 12px;
  2673. }
  2674.  
  2675. .PopUp_back {
  2676. position: absolute;
  2677. background-color: #00000066;
  2678. width: 100%;
  2679. height: 100%;
  2680. z-index: 10000;
  2681. top: 0;
  2682. left: 0;
  2683. }
  2684.  
  2685. .PopUp_close {
  2686. width: 40px;
  2687. height: 40px;
  2688. position: absolute;
  2689. right: -18px;
  2690. top: -18px;
  2691. border: 3px solid #c18550;
  2692. border-radius: 20px;
  2693. background: radial-gradient(circle, rgba(190,30,35,1) 0%, rgba(0,0,0,1) 100%);
  2694. background-position-y: 3px;
  2695. box-shadow: -1px 1px 3px black;
  2696. cursor: pointer;
  2697. box-sizing: border-box;
  2698. }
  2699.  
  2700. .PopUp_close:hover {
  2701. filter: brightness(1.2);
  2702. }
  2703.  
  2704. .PopUp_crossClose {
  2705. width: 100%;
  2706. height: 100%;
  2707. background-size: 65%;
  2708. background-position: center;
  2709. background-repeat: no-repeat;
  2710. 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")
  2711. }
  2712.  
  2713. .PopUp_blocks {
  2714. width: 100%;
  2715. height: 50%;
  2716. display: flex;
  2717. justify-content: space-evenly;
  2718. align-items: center;
  2719. flex-wrap: wrap;
  2720. justify-content: center;
  2721. }
  2722.  
  2723. .PopUp_blocks:last-child {
  2724. margin-top: 25px;
  2725. }
  2726.  
  2727. .PopUp_buttons {
  2728. display: flex;
  2729. margin: 10px 12px;
  2730. flex-direction: column;
  2731. }
  2732.  
  2733. .PopUp_button {
  2734. background-color: #52A81C;
  2735. border-radius: 5px;
  2736. box-shadow: inset 0px -4px 10px, inset 0px 3px 2px #99fe20, 0px 0px 4px, 0px -3px 1px #d7b275, 0px 0px 0px 3px #ce9767;
  2737. cursor: pointer;
  2738. padding: 5px 15px 7px;
  2739. }
  2740.  
  2741. .PopUp_input {
  2742. text-align: center;
  2743. font-size: 16px;
  2744. height: 27px;
  2745. border: 1px solid #cf9250;
  2746. border-radius: 9px 9px 0px 0px;
  2747. background: transparent;
  2748. color: #fce1ac;
  2749. padding: 1px 10px;
  2750. box-sizing: border-box;
  2751. box-shadow: 0px 0px 4px, 0px 0px 0px 3px #ce9767;
  2752. }
  2753.  
  2754. .PopUp_checkboxes {
  2755. display: flex;
  2756. flex-direction: column;
  2757. margin: 15px 15px -5px 15px;
  2758. align-items: flex-start;
  2759. }
  2760.  
  2761. .PopUp_ContCheckbox {
  2762. margin: 2px 0px;
  2763. }
  2764.  
  2765. .PopUp_checkbox {
  2766. position: absolute;
  2767. z-index: -1;
  2768. opacity: 0;
  2769. }
  2770. .PopUp_checkbox+label {
  2771. display: inline-flex;
  2772. align-items: center;
  2773. user-select: none;
  2774.  
  2775. font-size: 15px;
  2776. font-family: sans-serif;
  2777. font-weight: 600;
  2778. font-stretch: condensed;
  2779. letter-spacing: 1px;
  2780. color: #fce1ac;
  2781. text-shadow: 0px 0px 1px;
  2782. }
  2783. .PopUp_checkbox+label::before {
  2784. content: '';
  2785. display: inline-block;
  2786. width: 20px;
  2787. height: 20px;
  2788. border: 1px solid #cf9250;
  2789. border-radius: 7px;
  2790. margin-right: 7px;
  2791. }
  2792. .PopUp_checkbox:checked+label::before {
  2793. 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");
  2794. }
  2795.  
  2796. .PopUp_input::placeholder {
  2797. color: #fce1ac75;
  2798. }
  2799.  
  2800. .PopUp_input:focus {
  2801. outline: 0;
  2802. }
  2803.  
  2804. .PopUp_input + .PopUp_button {
  2805. border-radius: 0px 0px 5px 5px;
  2806. padding: 2px 18px 5px;
  2807. }
  2808.  
  2809. .PopUp_button:hover {
  2810. filter: brightness(1.2);
  2811. }
  2812.  
  2813. .PopUp_text {
  2814. font-size: 22px;
  2815. font-family: sans-serif;
  2816. font-weight: 600;
  2817. font-stretch: condensed;
  2818. letter-spacing: 1px;
  2819. text-align: center;
  2820. }
  2821.  
  2822. .PopUp_buttonText {
  2823. color: #E4FF4C;
  2824. text-shadow: 0px 1px 2px black;
  2825. }
  2826.  
  2827. .PopUp_msgText {
  2828. color: #FDE5B6;
  2829. text-shadow: 0px 0px 2px;
  2830. }
  2831.  
  2832. .PopUp_hideBlock {
  2833. display: none;
  2834. }
  2835. `;
  2836. document.head.appendChild(style);
  2837. }
  2838.  
  2839. const addBlocks = () => {
  2840. this.back = document.createElement('div');
  2841. this.back.classList.add('PopUp_back');
  2842. this.back.classList.add('PopUp_hideBlock');
  2843. document.body.append(this.back);
  2844.  
  2845. this.popUp = document.createElement('div');
  2846. this.popUp.classList.add('PopUp_');
  2847. this.back.append(this.popUp);
  2848.  
  2849. let upper = document.createElement('div')
  2850. upper.classList.add('PopUp_blocks');
  2851. this.popUp.append(upper);
  2852.  
  2853. this.middle = document.createElement('div')
  2854. this.middle.classList.add('PopUp_blocks');
  2855. this.middle.classList.add('PopUp_checkboxes');
  2856. this.popUp.append(this.middle);
  2857.  
  2858. this.downer = document.createElement('div')
  2859. this.downer.classList.add('PopUp_blocks');
  2860. this.popUp.append(this.downer);
  2861.  
  2862. this.msgText = document.createElement('div');
  2863. this.msgText.classList.add('PopUp_text', 'PopUp_msgText');
  2864. upper.append(this.msgText);
  2865. }
  2866.  
  2867. this.showBack = function () {
  2868. this.back.classList.remove('PopUp_hideBlock');
  2869. }
  2870.  
  2871. this.hideBack = function () {
  2872. this.back.classList.add('PopUp_hideBlock');
  2873. }
  2874.  
  2875. this.show = function () {
  2876. if (this.checkboxes.length) {
  2877. this.middle.classList.remove('PopUp_hideBlock');
  2878. }
  2879. this.showBack();
  2880. this.popUp.classList.remove('PopUp_hideBlock');
  2881. this.popUp.style.left = (window.innerWidth - this.popUp.offsetWidth) / 2 + 'px';
  2882. this.popUp.style.top = (window.innerHeight - this.popUp.offsetHeight) / 3 + 'px';
  2883. }
  2884.  
  2885. this.hide = function () {
  2886. this.hideBack();
  2887. this.popUp.classList.add('PopUp_hideBlock');
  2888. }
  2889.  
  2890. this.addAnyButton = (option) => {
  2891. const contButton = document.createElement('div');
  2892. contButton.classList.add('PopUp_buttons');
  2893. this.downer.append(contButton);
  2894.  
  2895. let inputField = {
  2896. value: option.result || option.default
  2897. }
  2898. if (option.isInput) {
  2899. inputField = document.createElement('input');
  2900. inputField.type = 'text';
  2901. if (option.placeholder) {
  2902. inputField.placeholder = option.placeholder;
  2903. }
  2904. if (option.default) {
  2905. inputField.value = option.default;
  2906. }
  2907. inputField.classList.add('PopUp_input');
  2908. contButton.append(inputField);
  2909. }
  2910.  
  2911. const button = document.createElement('div');
  2912. button.classList.add('PopUp_button');
  2913. button.title = option.title || '';
  2914. contButton.append(button);
  2915.  
  2916. const buttonText = document.createElement('div');
  2917. buttonText.classList.add('PopUp_text', 'PopUp_buttonText');
  2918. buttonText.innerText = option.msg;
  2919. button.append(buttonText);
  2920.  
  2921. return { button, contButton, inputField };
  2922. }
  2923.  
  2924. this.addCloseButton = () => {
  2925. let button = document.createElement('div')
  2926. button.classList.add('PopUp_close');
  2927. this.popUp.append(button);
  2928.  
  2929. let crossClose = document.createElement('div')
  2930. crossClose.classList.add('PopUp_crossClose');
  2931. button.append(crossClose);
  2932.  
  2933. return { button, contButton: button };
  2934. }
  2935.  
  2936. this.addButton = (option, buttonClick) => {
  2937.  
  2938. const { button, contButton, inputField } = option.isClose ? this.addCloseButton() : this.addAnyButton(option);
  2939.  
  2940. button.addEventListener('click', () => {
  2941. let result = '';
  2942. if (option.isInput) {
  2943. result = inputField.value;
  2944. }
  2945. buttonClick(result);
  2946. });
  2947.  
  2948. this.buttons.push(contButton);
  2949. }
  2950.  
  2951. this.clearButtons = () => {
  2952. while (this.buttons.length) {
  2953. this.buttons.pop().remove();
  2954. }
  2955. }
  2956.  
  2957. this.addCheckBox = (checkBox) => {
  2958. const contCheckbox = document.createElement('div');
  2959. contCheckbox.classList.add('PopUp_ContCheckbox');
  2960. this.middle.append(contCheckbox);
  2961.  
  2962. const checkbox = document.createElement('input');
  2963. checkbox.type = 'checkbox';
  2964. checkbox.id = 'PopUpCheckbox' + this.checkboxes.length;
  2965. checkbox.dataset.name = checkBox.name;
  2966. checkbox.checked = checkBox.checked;
  2967. checkbox.label = checkBox.label;
  2968. checkbox.title = checkBox.title || '';
  2969. checkbox.classList.add('PopUp_checkbox');
  2970. contCheckbox.appendChild(checkbox)
  2971.  
  2972. const checkboxLabel = document.createElement('label');
  2973. checkboxLabel.innerText = checkBox.label;
  2974. checkboxLabel.title = checkBox.title || '';
  2975. checkboxLabel.setAttribute('for', checkbox.id);
  2976. contCheckbox.appendChild(checkboxLabel);
  2977.  
  2978. this.checkboxes.push(checkbox);
  2979. }
  2980.  
  2981. this.clearCheckBox = () => {
  2982. this.middle.classList.add('PopUp_hideBlock');
  2983. while (this.checkboxes.length) {
  2984. this.checkboxes.pop().parentNode.remove();
  2985. }
  2986. }
  2987.  
  2988. this.setMsgText = (text) => {
  2989. this.msgText.innerHTML = text;
  2990. }
  2991.  
  2992. this.getCheckBoxes = () => {
  2993. const checkBoxes = [];
  2994.  
  2995. for (const checkBox of this.checkboxes) {
  2996. checkBoxes.push({
  2997. name: checkBox.dataset.name,
  2998. label: checkBox.label,
  2999. checked: checkBox.checked
  3000. });
  3001. }
  3002.  
  3003. return checkBoxes;
  3004. }
  3005.  
  3006. this.confirm = async (msg, buttOpt, checkBoxes = []) => {
  3007. this.clearButtons();
  3008. this.clearCheckBox();
  3009. return new Promise((complete, failed) => {
  3010. this.setMsgText(msg);
  3011. if (!buttOpt) {
  3012. buttOpt = [{ msg: 'Ok', result: true, isInput: false }];
  3013. }
  3014. for (const checkBox of checkBoxes) {
  3015. this.addCheckBox(checkBox);
  3016. }
  3017. for (let butt of buttOpt) {
  3018. this.addButton(butt, (result) => {
  3019. result = result || butt.result;
  3020. complete(result);
  3021. popup.hide();
  3022. });
  3023. }
  3024. this.show();
  3025. });
  3026. }
  3027.  
  3028. document.addEventListener('DOMContentLoaded', init);
  3029. });
  3030. /**
  3031. * Script control panel
  3032. *
  3033. * Панель управления скриптом
  3034. */
  3035. const scriptMenu = new (function () {
  3036.  
  3037. this.mainMenu,
  3038. this.buttons = [],
  3039. this.checkboxes = [];
  3040. this.option = {
  3041. showMenu: false,
  3042. showDetails: {}
  3043. };
  3044.  
  3045. this.init = function (option = {}) {
  3046. this.option = Object.assign(this.option, option);
  3047. this.option.showDetails = this.loadShowDetails();
  3048. addStyle();
  3049. addBlocks();
  3050. }
  3051.  
  3052. const addStyle = () => {
  3053. style = document.createElement('style');
  3054. style.innerText = `
  3055. .scriptMenu_status {
  3056. position: absolute;
  3057. z-index: 10001;
  3058. /* max-height: 30px; */
  3059. top: -1px;
  3060. left: 30%;
  3061. cursor: pointer;
  3062. border-radius: 0px 0px 10px 10px;
  3063. background: #190e08e6;
  3064. border: 1px #ce9767 solid;
  3065. font-size: 18px;
  3066. font-family: sans-serif;
  3067. font-weight: 600;
  3068. font-stretch: condensed;
  3069. letter-spacing: 1px;
  3070. color: #fce1ac;
  3071. text-shadow: 0px 0px 1px;
  3072. transition: 0.5s;
  3073. padding: 2px 10px 3px;
  3074. }
  3075. .scriptMenu_statusHide {
  3076. top: -35px;
  3077. height: 30px;
  3078. overflow: hidden;
  3079. }
  3080. .scriptMenu_label {
  3081. position: absolute;
  3082. top: 30%;
  3083. left: -4px;
  3084. z-index: 9999;
  3085. cursor: pointer;
  3086. width: 30px;
  3087. height: 30px;
  3088. background: radial-gradient(circle, #47a41b 0%, #1a2f04 100%);
  3089. border: 1px solid #1a2f04;
  3090. border-radius: 5px;
  3091. box-shadow:
  3092. inset 0px 2px 4px #83ce26,
  3093. inset 0px -4px 6px #1a2f04,
  3094. 0px 0px 2px black,
  3095. 0px 0px 0px 2px #ce9767;
  3096. }
  3097. .scriptMenu_label:hover {
  3098. filter: brightness(1.2);
  3099. }
  3100. .scriptMenu_arrowLabel {
  3101. width: 100%;
  3102. height: 100%;
  3103. background-size: 75%;
  3104. background-position: center;
  3105. background-repeat: no-repeat;
  3106. 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");
  3107. box-shadow: 0px 1px 2px #000;
  3108. border-radius: 5px;
  3109. filter: drop-shadow(0px 1px 2px #000D);
  3110. }
  3111. .scriptMenu_main {
  3112. position: absolute;
  3113. max-width: 285px;
  3114. z-index: 9999;
  3115. top: 50%;
  3116. transform: translateY(-50%);
  3117. background: #190e08e6;
  3118. border: 1px #ce9767 solid;
  3119. border-radius: 0px 10px 10px 0px;
  3120. border-left: none;
  3121. padding: 5px 10px 5px 5px;
  3122. box-sizing: border-box;
  3123. font-size: 15px;
  3124. font-family: sans-serif;
  3125. font-weight: 600;
  3126. font-stretch: condensed;
  3127. letter-spacing: 1px;
  3128. color: #fce1ac;
  3129. text-shadow: 0px 0px 1px;
  3130. transition: 1s;
  3131. display: flex;
  3132. flex-direction: column;
  3133. flex-wrap: nowrap;
  3134. }
  3135. .scriptMenu_showMenu {
  3136. display: none;
  3137. }
  3138. .scriptMenu_showMenu:checked~.scriptMenu_main {
  3139. left: 0px;
  3140. }
  3141. .scriptMenu_showMenu:not(:checked)~.scriptMenu_main {
  3142. left: -300px;
  3143. }
  3144. .scriptMenu_divInput {
  3145. margin: 2px;
  3146. }
  3147. .scriptMenu_divInputText {
  3148. margin: 2px;
  3149. align-self: center;
  3150. display: flex;
  3151. }
  3152. .scriptMenu_checkbox {
  3153. position: absolute;
  3154. z-index: -1;
  3155. opacity: 0;
  3156. }
  3157. .scriptMenu_checkbox+label {
  3158. display: inline-flex;
  3159. align-items: center;
  3160. user-select: none;
  3161. }
  3162. .scriptMenu_checkbox+label::before {
  3163. content: '';
  3164. display: inline-block;
  3165. width: 20px;
  3166. height: 20px;
  3167. border: 1px solid #cf9250;
  3168. border-radius: 7px;
  3169. margin-right: 7px;
  3170. }
  3171. .scriptMenu_checkbox:checked+label::before {
  3172. 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");
  3173. }
  3174. .scriptMenu_close {
  3175. width: 40px;
  3176. height: 40px;
  3177. position: absolute;
  3178. right: -18px;
  3179. top: -18px;
  3180. border: 3px solid #c18550;
  3181. border-radius: 20px;
  3182. background: radial-gradient(circle, rgba(190,30,35,1) 0%, rgba(0,0,0,1) 100%);
  3183. background-position-y: 3px;
  3184. box-shadow: -1px 1px 3px black;
  3185. cursor: pointer;
  3186. box-sizing: border-box;
  3187. }
  3188. .scriptMenu_close:hover {
  3189. filter: brightness(1.2);
  3190. }
  3191. .scriptMenu_crossClose {
  3192. width: 100%;
  3193. height: 100%;
  3194. background-size: 65%;
  3195. background-position: center;
  3196. background-repeat: no-repeat;
  3197. 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")
  3198. }
  3199. .scriptMenu_button {
  3200. user-select: none;
  3201. border-radius: 5px;
  3202. cursor: pointer;
  3203. padding: 5px 14px 8px;
  3204. margin: 4px;
  3205. background: radial-gradient(circle, rgba(165,120,56,1) 80%, rgba(0,0,0,1) 110%);
  3206. box-shadow: inset 0px -4px 6px #442901, inset 0px 1px 6px #442901, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 2px #ce9767;
  3207. }
  3208. .scriptMenu_button:hover {
  3209. filter: brightness(1.2);
  3210. }
  3211. .scriptMenu_buttonText {
  3212. color: #fce5b7;
  3213. text-shadow: 0px 1px 2px black;
  3214. text-align: center;
  3215. }
  3216. .scriptMenu_header {
  3217. text-align: center;
  3218. align-self: center;
  3219. font-size: 15px;
  3220. margin: 0px 15px;
  3221. }
  3222. .scriptMenu_header a {
  3223. color: #fce5b7;
  3224. text-decoration: none;
  3225. }
  3226. .scriptMenu_InputText {
  3227. text-align: center;
  3228. width: 130px;
  3229. height: 24px;
  3230. border: 1px solid #cf9250;
  3231. border-radius: 9px;
  3232. background: transparent;
  3233. color: #fce1ac;
  3234. padding: 0px 10px;
  3235. box-sizing: border-box;
  3236. }
  3237. .scriptMenu_InputText:focus {
  3238. filter: brightness(1.2);
  3239. outline: 0;
  3240. }
  3241. .scriptMenu_InputText::placeholder {
  3242. color: #fce1ac75;
  3243. }
  3244. .scriptMenu_Summary {
  3245. cursor: pointer;
  3246. margin-left: 7px;
  3247. }
  3248. .scriptMenu_Details {
  3249. align-self: center;
  3250. }
  3251. `;
  3252. document.head.appendChild(style);
  3253. }
  3254.  
  3255. const addBlocks = () => {
  3256. const main = document.createElement('div');
  3257. document.body.appendChild(main);
  3258.  
  3259. this.status = document.createElement('div');
  3260. this.status.classList.add('scriptMenu_status');
  3261. this.setStatus('');
  3262. main.appendChild(this.status);
  3263.  
  3264. const label = document.createElement('label');
  3265. label.classList.add('scriptMenu_label');
  3266. label.setAttribute('for', 'checkbox_showMenu');
  3267. main.appendChild(label);
  3268.  
  3269. const arrowLabel = document.createElement('div');
  3270. arrowLabel.classList.add('scriptMenu_arrowLabel');
  3271. label.appendChild(arrowLabel);
  3272.  
  3273. const checkbox = document.createElement('input');
  3274. checkbox.type = 'checkbox';
  3275. checkbox.id = 'checkbox_showMenu';
  3276. checkbox.checked = this.option.showMenu;
  3277. checkbox.classList.add('scriptMenu_showMenu');
  3278. main.appendChild(checkbox);
  3279.  
  3280. this.mainMenu = document.createElement('div');
  3281. this.mainMenu.classList.add('scriptMenu_main');
  3282. main.appendChild(this.mainMenu);
  3283.  
  3284. const closeButton = document.createElement('label');
  3285. closeButton.classList.add('scriptMenu_close');
  3286. closeButton.setAttribute('for', 'checkbox_showMenu');
  3287. this.mainMenu.appendChild(closeButton);
  3288.  
  3289. const crossClose = document.createElement('div');
  3290. crossClose.classList.add('scriptMenu_crossClose');
  3291. closeButton.appendChild(crossClose);
  3292. }
  3293.  
  3294. this.setStatus = (text, onclick) => {
  3295. if (!text) {
  3296. this.status.classList.add('scriptMenu_statusHide');
  3297. } else {
  3298. this.status.classList.remove('scriptMenu_statusHide');
  3299. this.status.innerHTML = text;
  3300. }
  3301.  
  3302. if (typeof onclick == 'function') {
  3303. this.status.addEventListener("click", onclick, {
  3304. once: true
  3305. });
  3306. }
  3307. }
  3308.  
  3309. /**
  3310. * Adding a text element
  3311. *
  3312. * Добавление текстового элемента
  3313. * @param {String} text text // текст
  3314. * @param {Function} func Click function // функция по клику
  3315. * @param {HTMLDivElement} main parent // родитель
  3316. */
  3317. this.addHeader = (text, func, main) => {
  3318. main = main || this.mainMenu;
  3319. const header = document.createElement('div');
  3320. header.classList.add('scriptMenu_header');
  3321. header.innerHTML = text;
  3322. if (typeof func == 'function') {
  3323. header.addEventListener('click', func);
  3324. }
  3325. main.appendChild(header);
  3326. }
  3327.  
  3328. /**
  3329. * Adding a button
  3330. *
  3331. * Добавление кнопки
  3332. * @param {String} text
  3333. * @param {Function} func
  3334. * @param {String} title
  3335. * @param {HTMLDivElement} main parent // родитель
  3336. */
  3337. this.addButton = (text, func, title, main) => {
  3338. main = main || this.mainMenu;
  3339. const button = document.createElement('div');
  3340. button.classList.add('scriptMenu_button');
  3341. button.title = title;
  3342. button.addEventListener('click', func);
  3343. main.appendChild(button);
  3344.  
  3345. const buttonText = document.createElement('div');
  3346. buttonText.classList.add('scriptMenu_buttonText');
  3347. buttonText.innerText = text;
  3348. button.appendChild(buttonText);
  3349. this.buttons.push(button);
  3350.  
  3351. return button;
  3352. }
  3353.  
  3354. /**
  3355. * Adding checkbox
  3356. *
  3357. * Добавление чекбокса
  3358. * @param {String} label
  3359. * @param {String} title
  3360. * @param {HTMLDivElement} main parent // родитель
  3361. * @returns
  3362. */
  3363. this.addCheckbox = (label, title, main) => {
  3364. main = main || this.mainMenu;
  3365. const divCheckbox = document.createElement('div');
  3366. divCheckbox.classList.add('scriptMenu_divInput');
  3367. divCheckbox.title = title;
  3368. main.appendChild(divCheckbox);
  3369.  
  3370. const checkbox = document.createElement('input');
  3371. checkbox.type = 'checkbox';
  3372. checkbox.id = 'scriptMenuCheckbox' + this.checkboxes.length;
  3373. checkbox.classList.add('scriptMenu_checkbox');
  3374. divCheckbox.appendChild(checkbox)
  3375.  
  3376. const checkboxLabel = document.createElement('label');
  3377. checkboxLabel.innerText = label;
  3378. checkboxLabel.setAttribute('for', checkbox.id);
  3379. divCheckbox.appendChild(checkboxLabel);
  3380.  
  3381. this.checkboxes.push(checkbox);
  3382. return checkbox;
  3383. }
  3384.  
  3385. /**
  3386. * Adding input field
  3387. *
  3388. * Добавление поля ввода
  3389. * @param {String} title
  3390. * @param {String} placeholder
  3391. * @param {HTMLDivElement} main parent // родитель
  3392. * @returns
  3393. */
  3394. this.addInputText = (title, placeholder, main) => {
  3395. main = main || this.mainMenu;
  3396. const divInputText = document.createElement('div');
  3397. divInputText.classList.add('scriptMenu_divInputText');
  3398. divInputText.title = title;
  3399. main.appendChild(divInputText);
  3400.  
  3401. const newInputText = document.createElement('input');
  3402. newInputText.type = 'text';
  3403. if (placeholder) {
  3404. newInputText.placeholder = placeholder;
  3405. }
  3406. newInputText.classList.add('scriptMenu_InputText');
  3407. divInputText.appendChild(newInputText)
  3408. return newInputText;
  3409. }
  3410.  
  3411. /**
  3412. * Adds a dropdown block
  3413. *
  3414. * Добавляет раскрывающийся блок
  3415. * @param {String} summary
  3416. * @param {String} name
  3417. * @returns
  3418. */
  3419. this.addDetails = (summaryText, name = null) => {
  3420. const details = document.createElement('details');
  3421. details.classList.add('scriptMenu_Details');
  3422. this.mainMenu.appendChild(details);
  3423.  
  3424. const summary = document.createElement('summary');
  3425. summary.classList.add('scriptMenu_Summary');
  3426. summary.innerText = summaryText;
  3427. if (name) {
  3428. const self = this;
  3429. details.open = this.option.showDetails[name];
  3430. details.dataset.name = name;
  3431. summary.addEventListener('click', () => {
  3432. self.option.showDetails[details.dataset.name] = !details.open;
  3433. self.saveShowDetails(self.option.showDetails);
  3434. });
  3435. }
  3436. details.appendChild(summary);
  3437.  
  3438. return details;
  3439. }
  3440.  
  3441. /**
  3442. * Saving the expanded state of the details blocks
  3443. *
  3444. * Сохранение состояния развенутости блоков details
  3445. * @param {*} value
  3446. */
  3447. this.saveShowDetails = (value) => {
  3448. localStorage.setItem('scriptMenu_showDetails', JSON.stringify(value));
  3449. }
  3450.  
  3451. /**
  3452. * Loading the state of expanded blocks details
  3453. *
  3454. * Загрузка состояния развенутости блоков details
  3455. * @returns
  3456. */
  3457. this.loadShowDetails = () => {
  3458. let showDetails = localStorage.getItem('scriptMenu_showDetails');
  3459.  
  3460. if (!showDetails) {
  3461. return {};
  3462. }
  3463.  
  3464. try {
  3465. showDetails = JSON.parse(showDetails);
  3466. } catch (e) {
  3467. return {};
  3468. }
  3469.  
  3470. return showDetails;
  3471. }
  3472. });
  3473. /**
  3474. * Game Library
  3475. *
  3476. * Игровая библиотека
  3477. */
  3478. class Library {
  3479. defaultLibUrl = 'https://heroesru-a.akamaihd.net/vk/v1043/lib/lib.json';
  3480.  
  3481. constructor() {
  3482. if (!Library.instance) {
  3483. Library.instance = this;
  3484. }
  3485.  
  3486. return Library.instance;
  3487. }
  3488.  
  3489. async load(data) {
  3490. if (data) {
  3491. this.data = data;
  3492. return;
  3493. }
  3494. try {
  3495. this.data = await fetch(this.defaultLibUrl).then(e => e.json())
  3496. } catch (error) {
  3497. console.error('Не удалось загрузить библиотеку')
  3498. }
  3499. }
  3500.  
  3501. getData(id) {
  3502. return this.data[id];
  3503. }
  3504. }
  3505.  
  3506. this.lib = new Library();
  3507. /**
  3508. * Database
  3509. *
  3510. * База данных
  3511. */
  3512. class Database {
  3513. constructor(dbName, storeName) {
  3514. this.dbName = dbName;
  3515. this.storeName = storeName;
  3516. this.db = null;
  3517. }
  3518.  
  3519. async open() {
  3520. return new Promise((resolve, reject) => {
  3521. const request = indexedDB.open(this.dbName);
  3522.  
  3523. request.onerror = () => {
  3524. reject(new Error(`Failed to open database ${this.dbName}`));
  3525. };
  3526.  
  3527. request.onsuccess = () => {
  3528. this.db = request.result;
  3529. resolve();
  3530. };
  3531.  
  3532. request.onupgradeneeded = (event) => {
  3533. const db = event.target.result;
  3534. if (!db.objectStoreNames.contains(this.storeName)) {
  3535. db.createObjectStore(this.storeName);
  3536. }
  3537. };
  3538. });
  3539. }
  3540.  
  3541. async set(key, value) {
  3542. return new Promise((resolve, reject) => {
  3543. const transaction = this.db.transaction([this.storeName], 'readwrite');
  3544. const store = transaction.objectStore(this.storeName);
  3545. const request = store.put(value, key);
  3546.  
  3547. request.onerror = () => {
  3548. reject(new Error(`Failed to save value with key ${key}`));
  3549. };
  3550.  
  3551. request.onsuccess = () => {
  3552. resolve();
  3553. };
  3554. });
  3555. }
  3556.  
  3557. async get(key, def) {
  3558. return new Promise((resolve, reject) => {
  3559. const transaction = this.db.transaction([this.storeName], 'readonly');
  3560. const store = transaction.objectStore(this.storeName);
  3561. const request = store.get(key);
  3562.  
  3563. request.onerror = () => {
  3564. resolve(def);
  3565. };
  3566.  
  3567. request.onsuccess = () => {
  3568. resolve(request.result);
  3569. };
  3570. });
  3571. }
  3572.  
  3573. async delete(key) {
  3574. return new Promise((resolve, reject) => {
  3575. const transaction = this.db.transaction([this.storeName], 'readwrite');
  3576. const store = transaction.objectStore(this.storeName);
  3577. const request = store.delete(key);
  3578.  
  3579. request.onerror = () => {
  3580. reject(new Error(`Failed to delete value with key ${key}`));
  3581. };
  3582.  
  3583. request.onsuccess = () => {
  3584. resolve();
  3585. };
  3586. });
  3587. }
  3588. }
  3589.  
  3590. /**
  3591. * Returns the stored value
  3592. *
  3593. * Возвращает сохраненное значение
  3594. */
  3595. function getSaveVal(saveName, def) {
  3596. const result = storage.get(saveName, def);
  3597. return result;
  3598. }
  3599.  
  3600. /**
  3601. * Stores value
  3602. *
  3603. * Сохраняет значение
  3604. */
  3605. function setSaveVal(saveName, value) {
  3606. storage.set(saveName, value);
  3607. }
  3608.  
  3609. /**
  3610. * Database initialization
  3611. *
  3612. * Инициализация базы данных
  3613. */
  3614. const db = new Database(GM_info.script.name, 'settings');
  3615.  
  3616. /**
  3617. * Data store
  3618. *
  3619. * Хранилище данных
  3620. */
  3621. const storage = {
  3622. userId: 0,
  3623. /**
  3624. * Default values
  3625. *
  3626. * Значения по умолчанию
  3627. */
  3628. values: [
  3629. ...Object.entries(checkboxes).map(e => ({ [e[0]]: e[1].default })),
  3630. ...Object.entries(inputs).map(e => ({ [e[0]]: e[1].default })),
  3631. ].reduce((acc, obj) => ({ ...acc, ...obj }), {}),
  3632. name: GM_info.script.name,
  3633. get: function (key, def) {
  3634. if (key in this.values) {
  3635. return this.values[key];
  3636. }
  3637. return def;
  3638. },
  3639. set: function (key, value) {
  3640. this.values[key] = value;
  3641. db.set(this.userId, this.values).catch(
  3642. e => null
  3643. );
  3644. localStorage[this.name + ':' + key] = value;
  3645. },
  3646. delete: function (key) {
  3647. delete this.values[key];
  3648. db.set(this.userId, this.values);
  3649. delete localStorage[this.name + ':' + key];
  3650. }
  3651. }
  3652.  
  3653. /**
  3654. * Returns all keys from localStorage that start with prefix (for migration)
  3655. *
  3656. * Возвращает все ключи из localStorage которые начинаются с prefix (для миграции)
  3657. */
  3658. function getAllValuesStartingWith(prefix) {
  3659. const values = [];
  3660. for (let i = 0; i < localStorage.length; i++) {
  3661. const key = localStorage.key(i);
  3662. if (key.startsWith(prefix)) {
  3663. const val = localStorage.getItem(key);
  3664. const keyValue = key.split(':')[1];
  3665. values.push({ key: keyValue, val });
  3666. }
  3667. }
  3668. return values;
  3669. }
  3670.  
  3671. /**
  3672. * Opens or migrates to a database
  3673. *
  3674. * Открывает или мигрирует в базу данных
  3675. */
  3676. async function openOrMigrateDatabase(userId) {
  3677. storage.userId = userId;
  3678. try {
  3679. await db.open();
  3680. } catch(e) {
  3681. return;
  3682. }
  3683. let settings = await db.get(userId, false);
  3684.  
  3685. if (settings) {
  3686. storage.values = settings;
  3687. return;
  3688. }
  3689.  
  3690. const values = getAllValuesStartingWith(GM_info.script.name);
  3691. for (const value of values) {
  3692. let val = null;
  3693. try {
  3694. val = JSON.parse(value.val);
  3695. } catch {
  3696. break;
  3697. }
  3698. storage.values[value.key] = val;
  3699. }
  3700. await db.set(userId, storage.values);
  3701. }
  3702. /**
  3703. * Sending expeditions
  3704. *
  3705. * Отправка экспедиций
  3706. */
  3707. function checkExpedition() {
  3708. return new Promise((resolve, reject) => {
  3709. const expedition = new Expedition(resolve, reject);
  3710. expedition.start();
  3711. });
  3712. }
  3713.  
  3714. class Expedition {
  3715. checkExpedInfo = {
  3716. calls: [{
  3717. name: "expeditionGet",
  3718. args: {},
  3719. ident: "expeditionGet"
  3720. }, {
  3721. name: "heroGetAll",
  3722. args: {},
  3723. ident: "heroGetAll"
  3724. }]
  3725. }
  3726.  
  3727. constructor(resolve, reject) {
  3728. this.resolve = resolve;
  3729. this.reject = reject;
  3730. }
  3731.  
  3732. async start() {
  3733. const data = await Send(JSON.stringify(this.checkExpedInfo));
  3734.  
  3735. const expedInfo = data.results[0].result.response;
  3736. const dataHeroes = data.results[1].result.response;
  3737. const dataExped = { useHeroes: [], exped: [] };
  3738. const calls = [];
  3739.  
  3740. /**
  3741. * Adding expeditions to collect
  3742. * Добавляем экспедиции для сбора
  3743. */
  3744. for (var n in expedInfo) {
  3745. const exped = expedInfo[n];
  3746. const dateNow = (Date.now() / 1000);
  3747. if (exped.status == 2 && exped.endTime != 0 && dateNow > exped.endTime) {
  3748. calls.push({
  3749. name: "expeditionFarm",
  3750. args: { expeditionId: exped.id },
  3751. ident: "expeditionFarm_" + exped.id
  3752. });
  3753. } else {
  3754. dataExped.useHeroes = dataExped.useHeroes.concat(exped.heroes);
  3755. }
  3756. if (exped.status == 1) {
  3757. dataExped.exped.push({ id: exped.id, power: exped.power });
  3758. }
  3759. }
  3760. dataExped.exped = dataExped.exped.sort((a, b) => (b.power - a.power));
  3761.  
  3762. /**
  3763. * Putting together a list of heroes
  3764. * Собираем список героев
  3765. */
  3766. const heroesArr = [];
  3767. for (let n in dataHeroes) {
  3768. const hero = dataHeroes[n];
  3769. if (hero.xp > 0 && !dataExped.useHeroes.includes(hero.id)) {
  3770. heroesArr.push({ id: hero.id, power: hero.power })
  3771. }
  3772. }
  3773.  
  3774. /**
  3775. * Adding expeditions to send
  3776. * Добавляем экспедиции для отправки
  3777. */
  3778. heroesArr.sort((a, b) => (a.power - b.power));
  3779. for (const exped of dataExped.exped) {
  3780. let heroesIds = this.selectionHeroes(heroesArr, exped.power);
  3781. if (heroesIds && heroesIds.length > 4) {
  3782. for (let q in heroesArr) {
  3783. if (heroesIds.includes(heroesArr[q].id)) {
  3784. delete heroesArr[q];
  3785. }
  3786. }
  3787. calls.push({
  3788. name: "expeditionSendHeroes",
  3789. args: {
  3790. expeditionId: exped.id,
  3791. heroes: heroesIds
  3792. },
  3793. ident: "expeditionSendHeroes_" + exped.id
  3794. });
  3795. }
  3796. }
  3797.  
  3798. await Send(JSON.stringify({ calls }));
  3799. this.end();
  3800. }
  3801.  
  3802. /**
  3803. * Selection of heroes for expeditions
  3804. *
  3805. * Подбор героев для экспедиций
  3806. */
  3807. selectionHeroes(heroes, power) {
  3808. const resultHeroers = [];
  3809. const heroesIds = [];
  3810. for (let q = 0; q < 5; q++) {
  3811. for (let i in heroes) {
  3812. let hero = heroes[i];
  3813. if (heroesIds.includes(hero.id)) {
  3814. continue;
  3815. }
  3816.  
  3817. const summ = resultHeroers.reduce((acc, hero) => acc + hero.power, 0);
  3818. const need = Math.round((power - summ) / (5 - resultHeroers.length));
  3819. if (hero.power > need) {
  3820. resultHeroers.push(hero);
  3821. heroesIds.push(hero.id);
  3822. break;
  3823. }
  3824. }
  3825. }
  3826.  
  3827. const summ = resultHeroers.reduce((acc, hero) => acc + hero.power, 0);
  3828. if (summ < power) {
  3829. return false;
  3830. }
  3831. return heroesIds;
  3832. }
  3833.  
  3834. /**
  3835. * Ends expedition script
  3836. *
  3837. * Завершает скрипт экспедиции
  3838. */
  3839. end() {
  3840. setProgress(I18N('EXPEDITIONS_SENT'), true);
  3841. this.resolve()
  3842. }
  3843. }
  3844.  
  3845. /**
  3846. * Walkthrough of the dungeon
  3847. *
  3848. * Прохождение подземелья
  3849. */
  3850. function testDungeon() {
  3851. return new Promise((resolve, reject) => {
  3852. const dung = new executeDungeon(resolve, reject);
  3853. const titanit = getInput('countTitanit');
  3854. dung.start(titanit);
  3855. });
  3856. }
  3857.  
  3858. /**
  3859. * Walkthrough of the dungeon
  3860. *
  3861. * Прохождение подземелья
  3862. */
  3863. function executeDungeon(resolve, reject) {
  3864. dungeonActivity = 0;
  3865. maxDungeonActivity = 150;
  3866. countCard = 0;
  3867.  
  3868. titanGetAll = [];
  3869.  
  3870. teams = {
  3871. heroes: [],
  3872. earth: [],
  3873. fire: [],
  3874. neutral: [],
  3875. water: [],
  3876. }
  3877.  
  3878. titanStats = [];
  3879.  
  3880. titansStates = {};
  3881.  
  3882. callsExecuteDungeon = {
  3883. calls: [{
  3884. name: "dungeonGetInfo",
  3885. args: {},
  3886. ident: "dungeonGetInfo"
  3887. }, {
  3888. name: "teamGetAll",
  3889. args: {},
  3890. ident: "teamGetAll"
  3891. }, {
  3892. name: "teamGetFavor",
  3893. args: {},
  3894. ident: "teamGetFavor"
  3895. }, {
  3896. name: "clanGetInfo",
  3897. args: {},
  3898. ident: "clanGetInfo"
  3899. }, {
  3900. name: "titanGetAll",
  3901. args: {},
  3902. ident: "titanGetAll"
  3903. }, {
  3904. name: "inventoryGet",
  3905. args: {},
  3906. ident: "inventoryGet"
  3907. }]
  3908. }
  3909.  
  3910. this.start = function(titanit) {
  3911. maxDungeonActivity = titanit || getInput('countTitanit');
  3912. send(JSON.stringify(callsExecuteDungeon), startDungeon);
  3913. }
  3914.  
  3915. /**
  3916. * Getting data on the dungeon
  3917. *
  3918. * Получаем данные по подземелью
  3919. */
  3920. function startDungeon(e) {
  3921. res = e.results;
  3922. dungeonGetInfo = res[0].result.response;
  3923. if (!dungeonGetInfo) {
  3924. endDungeon('noDungeon', res);
  3925. return;
  3926. }
  3927. teamGetAll = res[1].result.response;
  3928. teamGetFavor = res[2].result.response;
  3929. dungeonActivity = res[3].result.response.stat.todayDungeonActivity;
  3930. titanGetAll = Object.values(res[4].result.response);
  3931. countCard = res[5].result.response.consumable[81];
  3932.  
  3933. teams.hero = {
  3934. favor: teamGetFavor.dungeon_hero,
  3935. heroes: teamGetAll.dungeon_hero.filter(id => id < 6000),
  3936. teamNum: 0,
  3937. }
  3938. heroPet = teamGetAll.dungeon_hero.filter(id => id >= 6000).pop();
  3939. if (heroPet) {
  3940. teams.hero.pet = heroPet;
  3941. }
  3942.  
  3943. teams.neutral = {
  3944. favor: {},
  3945. heroes: getTitanTeam(titanGetAll, 'neutral'),
  3946. teamNum: 0,
  3947. };
  3948. teams.water = {
  3949. favor: {},
  3950. heroes: getTitanTeam(titanGetAll, 'water'),
  3951. teamNum: 0,
  3952. };
  3953. teams.fire = {
  3954. favor: {},
  3955. heroes: getTitanTeam(titanGetAll, 'fire'),
  3956. teamNum: 0,
  3957. };
  3958. teams.earth = {
  3959. favor: {},
  3960. heroes: getTitanTeam(titanGetAll, 'earth'),
  3961. teamNum: 0,
  3962. };
  3963.  
  3964.  
  3965. checkFloor(dungeonGetInfo);
  3966. }
  3967.  
  3968. function getTitanTeam(titans, type) {
  3969. switch (type) {
  3970. case 'neutral':
  3971. return titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  3972. case 'water':
  3973. return titans.filter(e => e.id.toString().slice(2, 3) == '0').map(e => e.id);
  3974. case 'fire':
  3975. return titans.filter(e => e.id.toString().slice(2, 3) == '1').map(e => e.id);
  3976. case 'earth':
  3977. return titans.filter(e => e.id.toString().slice(2, 3) == '2').map(e => e.id);
  3978. }
  3979. }
  3980.  
  3981. function fixTitanTeam(titans) {
  3982. titans.heroes = titans.heroes.filter(e => !titansStates[e]?.isDead);
  3983. return titans;
  3984. }
  3985.  
  3986. /**
  3987. * Checking the floor
  3988. *
  3989. * Проверяем этаж
  3990. */
  3991. async function checkFloor(dungeonInfo) {
  3992. if (!('floor' in dungeonInfo) || dungeonInfo.floor?.state == 2) {
  3993. saveProgress();
  3994. return;
  3995. }
  3996. // console.log(dungeonInfo, dungeonActivity);
  3997. setProgress(`${I18N('DUNGEON')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity}`);
  3998. if (dungeonActivity >= maxDungeonActivity) {
  3999. endDungeon('endDungeon', 'maxActive ' + dungeonActivity + '/' + maxDungeonActivity);
  4000. return;
  4001. }
  4002. titansStates = dungeonInfo.states.titans;
  4003. titanStats = titanObjToArray(titansStates);
  4004. const floorChoices = dungeonInfo.floor.userData;
  4005. const floorType = dungeonInfo.floorType;
  4006. //const primeElement = dungeonInfo.elements.prime;
  4007. if (floorType == "battle") {
  4008. const calls = [];
  4009. for (let teamNum in floorChoices) {
  4010. attackerType = floorChoices[teamNum].attackerType;
  4011. const args = fixTitanTeam(teams[attackerType]);
  4012. if (!args.heroes.length) {
  4013. continue;
  4014. }
  4015. args.teamNum = teamNum;
  4016. calls.push({
  4017. name: "dungeonStartBattle",
  4018. args,
  4019. ident: "body_" + teamNum
  4020. })
  4021. }
  4022. if (!calls.length) {
  4023. endDungeon('endDungeon', 'All Dead');
  4024. return;
  4025. }
  4026. const battleDatas = await Send(JSON.stringify({ calls }))
  4027. .then(e => e.results.map(n => n.result.response))
  4028. const battleResults = [];
  4029. for (n in battleDatas) {
  4030. battleData = battleDatas[n]
  4031. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  4032. battleResults.push(await Calc(battleData).then(result => {
  4033. result.teamNum = n;
  4034. result.attackerType = floorChoices[n].attackerType;
  4035. return result;
  4036. }));
  4037. }
  4038. processingPromises(battleResults)
  4039. }
  4040. }
  4041.  
  4042. function processingPromises(results) {
  4043. let selectBattle = results[0];
  4044. if (results.length < 2) {
  4045. // console.log(selectBattle);
  4046. if (!selectBattle.result.win) {
  4047. endDungeon('dungeonEndBattle\n', selectBattle);
  4048. return;
  4049. }
  4050. endBattle(selectBattle);
  4051. return;
  4052. }
  4053.  
  4054. selectBattle = false;
  4055. let bestState = -1000;
  4056. for (const result of results) {
  4057. const recovery = getState(result);
  4058. if (recovery > bestState) {
  4059. bestState = recovery;
  4060. selectBattle = result
  4061. }
  4062. }
  4063. // console.log(selectBattle.teamNum, results);
  4064. if (!selectBattle || bestState <= -1000) {
  4065. endDungeon('dungeonEndBattle\n', results);
  4066. return;
  4067. }
  4068.  
  4069. startBattle(selectBattle.teamNum, selectBattle.attackerType)
  4070. .then(endBattle);
  4071. }
  4072.  
  4073. /**
  4074. * Let's start the fight
  4075. *
  4076. * Начинаем бой
  4077. */
  4078. function startBattle(teamNum, attackerType) {
  4079. return new Promise(function (resolve, reject) {
  4080. args = fixTitanTeam(teams[attackerType]);
  4081. args.teamNum = teamNum;
  4082. if (attackerType == 'neutral') {
  4083. const titans = titanGetAll.filter(e => !titansStates[e.id]?.isDead)
  4084. args.heroes = titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  4085. }
  4086. startBattleCall = {
  4087. calls: [{
  4088. name: "dungeonStartBattle",
  4089. args,
  4090. ident: "body"
  4091. }]
  4092. }
  4093. send(JSON.stringify(startBattleCall), resultBattle, {
  4094. resolve,
  4095. teamNum,
  4096. attackerType
  4097. });
  4098. });
  4099. }
  4100. /**
  4101. * Returns the result of the battle in a promise
  4102. *
  4103. * Возращает резульат боя в промис
  4104. */
  4105. function resultBattle(resultBattles, args) {
  4106. battleData = resultBattles.results[0].result.response;
  4107. battleType = "get_tower";
  4108. if (battleData.type == "dungeon_titan") {
  4109. battleType = "get_titan";
  4110. }
  4111. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  4112. BattleCalc(battleData, battleType, function (result) {
  4113. result.teamNum = args.teamNum;
  4114. result.attackerType = args.attackerType;
  4115. args.resolve(result);
  4116. });
  4117. }
  4118. /**
  4119. * Finishing the fight
  4120. *
  4121. * Заканчиваем бой
  4122. */
  4123. async function endBattle(battleInfo) {
  4124. if (battleInfo.result.win) {
  4125. const args = {
  4126. result: battleInfo.result,
  4127. progress: battleInfo.progress,
  4128. }
  4129. if (countCard && !isChecked('endlessCards')) {
  4130. args.isRaid = true;
  4131. countCard--;
  4132. } else {
  4133. const timer = Math.max(battleInfo.battleTime / timerDiv + 1.5, 3);
  4134. console.log(timer);
  4135. await countdownTimer(timer, `${I18N('DUNGEON')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity}`);
  4136. }
  4137. const calls = [{
  4138. name: "dungeonEndBattle",
  4139. args,
  4140. ident: "body"
  4141. }];
  4142. send(JSON.stringify({ calls }), resultEndBattle);
  4143. } else {
  4144. endDungeon('dungeonEndBattle win: false\n', battleInfo);
  4145. }
  4146. }
  4147.  
  4148. /**
  4149. * Getting and processing battle results
  4150. *
  4151. * Получаем и обрабатываем результаты боя
  4152. */
  4153. function resultEndBattle(e) {
  4154. if ('error' in e) {
  4155. popup.confirm(I18N('ERROR_MSG', {
  4156. name: e.error.name,
  4157. description: e.error.description,
  4158. }));
  4159. endDungeon('errorRequest', e);
  4160. return;
  4161. }
  4162. battleResult = e.results[0].result.response;
  4163. if ('error' in battleResult) {
  4164. endDungeon('errorBattleResult', battleResult);
  4165. return;
  4166. }
  4167. dungeonGetInfo = battleResult.dungeon ?? battleResult;
  4168. dungeonActivity += battleResult.reward.dungeonActivity ?? 0;
  4169. checkFloor(dungeonGetInfo);
  4170. }
  4171.  
  4172. /**
  4173. * Returns the coefficient of condition of the
  4174. * difference in titanium before and after the battle
  4175. *
  4176. * Возвращает коэффициент состояния титанов после боя
  4177. */
  4178. function getState(result) {
  4179. if (!result.result.win) {
  4180. return -1000;
  4181. }
  4182.  
  4183. let beforeSumFactor = 0;
  4184. const beforeTitans = result.battleData.attackers;
  4185. for (let titanId in beforeTitans) {
  4186. const titan = beforeTitans[titanId];
  4187. const state = titan.state;
  4188. let factor = 1;
  4189. if (state) {
  4190. const hp = state.hp / titan.hp;
  4191. const energy = state.energy / 1e3;
  4192. factor = hp + energy / 20
  4193. }
  4194. beforeSumFactor += factor;
  4195. }
  4196.  
  4197. let afterSumFactor = 0;
  4198. const afterTitans = result.progress[0].attackers.heroes;
  4199. for (let titanId in afterTitans) {
  4200. const titan = afterTitans[titanId];
  4201. const hp = titan.hp / beforeTitans[titanId].hp;
  4202. const energy = titan.energy / 1e3;
  4203. const factor = hp + energy / 20;
  4204. afterSumFactor += factor;
  4205. }
  4206. return afterSumFactor - beforeSumFactor;
  4207. }
  4208.  
  4209. /**
  4210. * Converts an object with IDs to an array with IDs
  4211. *
  4212. * Преобразует объект с идетификаторами в массив с идетификаторами
  4213. */
  4214. function titanObjToArray(obj) {
  4215. let titans = [];
  4216. for (let id in obj) {
  4217. obj[id].id = id;
  4218. titans.push(obj[id]);
  4219. }
  4220. return titans;
  4221. }
  4222.  
  4223. function saveProgress() {
  4224. let saveProgressCall = {
  4225. calls: [{
  4226. name: "dungeonSaveProgress",
  4227. args: {},
  4228. ident: "body"
  4229. }]
  4230. }
  4231. send(JSON.stringify(saveProgressCall), resultEndBattle);
  4232. }
  4233.  
  4234. function endDungeon(reason, info) {
  4235. console.warn(reason, info);
  4236. setProgress(`${I18N('DUNGEON')} ${I18N('COMPLETED')}`, true);
  4237. resolve();
  4238. }
  4239. }
  4240.  
  4241. /**
  4242. * Passing the tower
  4243. *
  4244. * Прохождение башни
  4245. */
  4246. function testTower() {
  4247. return new Promise((resolve, reject) => {
  4248. tower = new executeTower(resolve, reject);
  4249. tower.start();
  4250. });
  4251. }
  4252.  
  4253. /**
  4254. * Passing the tower
  4255. *
  4256. * Прохождение башни
  4257. */
  4258. function executeTower(resolve, reject) {
  4259. lastTowerInfo = {};
  4260.  
  4261. scullCoin = 0;
  4262.  
  4263. heroGetAll = [];
  4264.  
  4265. heroesStates = {};
  4266.  
  4267. argsBattle = {
  4268. heroes: [],
  4269. favor: {},
  4270. };
  4271.  
  4272. callsExecuteTower = {
  4273. calls: [{
  4274. name: "towerGetInfo",
  4275. args: {},
  4276. ident: "towerGetInfo"
  4277. }, {
  4278. name: "teamGetAll",
  4279. args: {},
  4280. ident: "teamGetAll"
  4281. }, {
  4282. name: "teamGetFavor",
  4283. args: {},
  4284. ident: "teamGetFavor"
  4285. }, {
  4286. name: "inventoryGet",
  4287. args: {},
  4288. ident: "inventoryGet"
  4289. }, {
  4290. name: "heroGetAll",
  4291. args: {},
  4292. ident: "heroGetAll"
  4293. }]
  4294. }
  4295.  
  4296. buffIds = [
  4297. {id: 0, cost: 0, isBuy: false}, // plug // заглушка
  4298. {id: 1, cost: 1, isBuy: true}, // 3% attack // 3% атака
  4299. {id: 2, cost: 6, isBuy: true}, // 2% attack // 2% атака
  4300. {id: 3, cost: 16, isBuy: true}, // 4% attack // 4% атака
  4301. {id: 4, cost: 40, isBuy: true}, // 8% attack // 8% атака
  4302. {id: 5, cost: 1, isBuy: true}, // 10% armor // 10% броня
  4303. {id: 6, cost: 6, isBuy: true}, // 5% armor // 5% броня
  4304. {id: 7, cost: 16, isBuy: true}, // 10% armor // 10% броня
  4305. {id: 8, cost: 40, isBuy: true}, // 20% armor // 20% броня
  4306. { id: 9, cost: 1, isBuy: true }, // 10% protection from magic // 10% защита от магии
  4307. { id: 10, cost: 6, isBuy: true }, // 5% protection from magic // 5% защита от магии
  4308. { id: 11, cost: 16, isBuy: true }, // 10% protection from magic // 10% защита от магии
  4309. { id: 12, cost: 40, isBuy: true }, // 20% protection from magic // 20% защита от магии
  4310. { id: 13, cost: 1, isBuy: false }, // 40% health hero // 40% здоровья герою
  4311. { id: 14, cost: 6, isBuy: false }, // 40% health hero // 40% здоровья герою
  4312. { id: 15, cost: 16, isBuy: false }, // 80% health hero // 80% здоровья герою
  4313. { id: 16, cost: 40, isBuy: false }, // 40% health to all heroes // 40% здоровья всем героям
  4314. { id: 17, cost: 1, isBuy: false }, // 40% energy to the hero // 40% энергии герою
  4315. { id: 18, cost: 3, isBuy: false }, // 40% energy to the hero // 40% энергии герою
  4316. { id: 19, cost: 8, isBuy: false }, // 80% energy to the hero // 80% энергии герою
  4317. { id: 20, cost: 20, isBuy: false }, // 40% energy to all heroes // 40% энергии всем героям
  4318. { id: 21, cost: 40, isBuy: false }, // Hero Resurrection // Воскрешение героя
  4319. ]
  4320.  
  4321. this.start = function () {
  4322. send(JSON.stringify(callsExecuteTower), startTower);
  4323. }
  4324.  
  4325. /**
  4326. * Getting data on the Tower
  4327. *
  4328. * Получаем данные по башне
  4329. */
  4330. function startTower(e) {
  4331. res = e.results;
  4332. towerGetInfo = res[0].result.response;
  4333. if (!towerGetInfo) {
  4334. endTower('noTower', res);
  4335. return;
  4336. }
  4337. teamGetAll = res[1].result.response;
  4338. teamGetFavor = res[2].result.response;
  4339. inventoryGet = res[3].result.response;
  4340. heroGetAll = Object.values(res[4].result.response);
  4341.  
  4342. scullCoin = inventoryGet.coin[7] ?? 0;
  4343.  
  4344. argsBattle.favor = teamGetFavor.tower;
  4345. argsBattle.heroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  4346. pet = teamGetAll.tower.filter(id => id >= 6000).pop();
  4347. if (pet) {
  4348. argsBattle.pet = pet;
  4349. }
  4350.  
  4351. checkFloor(towerGetInfo);
  4352. }
  4353.  
  4354. function fixHeroesTeam(argsBattle) {
  4355. let fixHeroes = argsBattle.heroes.filter(e => !heroesStates[e]?.isDead);
  4356. if (fixHeroes.length < 5) {
  4357. heroGetAll = heroGetAll.filter(e => !heroesStates[e.id]?.isDead);
  4358. fixHeroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  4359. Object.keys(argsBattle.favor).forEach(e => {
  4360. if (!fixHeroes.includes(+e)) {
  4361. delete argsBattle.favor[e];
  4362. }
  4363. })
  4364. }
  4365. argsBattle.heroes = fixHeroes;
  4366. return argsBattle;
  4367. }
  4368.  
  4369. /**
  4370. * Check the floor
  4371. *
  4372. * Проверяем этаж
  4373. */
  4374. function checkFloor(towerInfo) {
  4375. lastTowerInfo = towerInfo;
  4376. maySkipFloor = +towerInfo.maySkipFloor;
  4377. floorNumber = +towerInfo.floorNumber;
  4378. heroesStates = towerInfo.states.heroes;
  4379. floorInfo = towerInfo.floor;
  4380.  
  4381. /**
  4382. * Is there at least one chest open on the floor
  4383. * Открыт ли на этаже хоть один сундук
  4384. */
  4385. isOpenChest = false;
  4386. if (towerInfo.floorType == "chest") {
  4387. isOpenChest = towerInfo.floor.chests.reduce((n, e) => n + e.opened, 0);
  4388. }
  4389.  
  4390. setProgress(`${I18N('TOWER')}: ${I18N('FLOOR')} ${floorNumber}`);
  4391. if (floorNumber > 49) {
  4392. if (isOpenChest) {
  4393. endTower('alreadyOpenChest 50 floor', floorNumber);
  4394. return;
  4395. }
  4396. }
  4397. /**
  4398. * If the chest is open and you can skip floors, then move on
  4399. * Если сундук открыт и можно скипать этажи, то переходим дальше
  4400. */
  4401. if (towerInfo.mayFullSkip && +towerInfo.teamLevel == 130) {
  4402. if (isOpenChest) {
  4403. nextOpenChest(floorNumber);
  4404. } else {
  4405. nextChestOpen(floorNumber);
  4406. }
  4407. return;
  4408. }
  4409.  
  4410. // console.log(towerInfo, scullCoin);
  4411. switch (towerInfo.floorType) {
  4412. case "battle":
  4413. if (floorNumber <= maySkipFloor) {
  4414. skipFloor();
  4415. return;
  4416. }
  4417. if (floorInfo.state == 2) {
  4418. nextFloor();
  4419. return;
  4420. }
  4421. startBattle().then(endBattle);
  4422. return;
  4423. case "buff":
  4424. checkBuff(towerInfo);
  4425. return;
  4426. case "chest":
  4427. openChest(floorNumber);
  4428. return;
  4429. default:
  4430. console.log('!', towerInfo.floorType, towerInfo);
  4431. break;
  4432. }
  4433. }
  4434.  
  4435. /**
  4436. * Let's start the fight
  4437. *
  4438. * Начинаем бой
  4439. */
  4440. function startBattle() {
  4441. return new Promise(function (resolve, reject) {
  4442. towerStartBattle = {
  4443. calls: [{
  4444. name: "towerStartBattle",
  4445. args: fixHeroesTeam(argsBattle),
  4446. ident: "body"
  4447. }]
  4448. }
  4449. send(JSON.stringify(towerStartBattle), resultBattle, resolve);
  4450. });
  4451. }
  4452. /**
  4453. * Returns the result of the battle in a promise
  4454. *
  4455. * Возращает резульат боя в промис
  4456. */
  4457. function resultBattle(resultBattles, resolve) {
  4458. battleData = resultBattles.results[0].result.response;
  4459. battleType = "get_tower";
  4460. BattleCalc(battleData, battleType, function (result) {
  4461. resolve(result);
  4462. });
  4463. }
  4464. /**
  4465. * Finishing the fight
  4466. *
  4467. * Заканчиваем бой
  4468. */
  4469. function endBattle(battleInfo) {
  4470. if (battleInfo.result.stars >= 3) {
  4471. endBattleCall = {
  4472. calls: [{
  4473. name: "towerEndBattle",
  4474. args: {
  4475. result: battleInfo.result,
  4476. progress: battleInfo.progress,
  4477. },
  4478. ident: "body"
  4479. }]
  4480. }
  4481. send(JSON.stringify(endBattleCall), resultEndBattle);
  4482. } else {
  4483. endTower('towerEndBattle win: false\n', battleInfo);
  4484. }
  4485. }
  4486.  
  4487. /**
  4488. * Getting and processing battle results
  4489. *
  4490. * Получаем и обрабатываем результаты боя
  4491. */
  4492. function resultEndBattle(e) {
  4493. battleResult = e.results[0].result.response;
  4494. if ('error' in battleResult) {
  4495. endTower('errorBattleResult', battleResult);
  4496. return;
  4497. }
  4498. if ('reward' in battleResult) {
  4499. scullCoin += battleResult.reward?.coin[7] ?? 0;
  4500. }
  4501. nextFloor();
  4502. }
  4503.  
  4504. function nextFloor() {
  4505. nextFloorCall = {
  4506. calls: [{
  4507. name: "towerNextFloor",
  4508. args: {},
  4509. ident: "body"
  4510. }]
  4511. }
  4512. send(JSON.stringify(nextFloorCall), checkDataFloor);
  4513. }
  4514.  
  4515. function openChest(floorNumber) {
  4516. floorNumber = floorNumber || 0;
  4517. openChestCall = {
  4518. calls: [{
  4519. name: "towerOpenChest",
  4520. args: {
  4521. num: 2
  4522. },
  4523. ident: "body"
  4524. }]
  4525. }
  4526. send(JSON.stringify(openChestCall), floorNumber < 50 ? nextFloor : lastChest);
  4527. }
  4528.  
  4529. function lastChest() {
  4530. endTower('openChest 50 floor', floorNumber);
  4531. }
  4532.  
  4533. function skipFloor() {
  4534. skipFloorCall = {
  4535. calls: [{
  4536. name: "towerSkipFloor",
  4537. args: {},
  4538. ident: "body"
  4539. }]
  4540. }
  4541. send(JSON.stringify(skipFloorCall), checkDataFloor);
  4542. }
  4543.  
  4544. function checkBuff(towerInfo) {
  4545. buffArr = towerInfo.floor;
  4546. promises = [];
  4547. for (let buff of buffArr) {
  4548. buffInfo = buffIds[buff.id];
  4549. if (buffInfo.isBuy && buffInfo.cost <= scullCoin) {
  4550. scullCoin -= buffInfo.cost;
  4551. promises.push(buyBuff(buff.id));
  4552. }
  4553. }
  4554. Promise.all(promises).then(nextFloor);
  4555. }
  4556.  
  4557. function buyBuff(buffId) {
  4558. return new Promise(function (resolve, reject) {
  4559. buyBuffCall = {
  4560. calls: [{
  4561. name: "towerBuyBuff",
  4562. args: {
  4563. buffId
  4564. },
  4565. ident: "body"
  4566. }]
  4567. }
  4568. send(JSON.stringify(buyBuffCall), resolve);
  4569. });
  4570. }
  4571.  
  4572. function checkDataFloor(result) {
  4573. towerInfo = result.results[0].result.response;
  4574. if ('reward' in towerInfo && towerInfo.reward?.coin) {
  4575. scullCoin += towerInfo.reward?.coin[7] ?? 0;
  4576. }
  4577. if ('tower' in towerInfo) {
  4578. towerInfo = towerInfo.tower;
  4579. }
  4580. if ('skullReward' in towerInfo) {
  4581. scullCoin += towerInfo.skullReward?.coin[7] ?? 0;
  4582. }
  4583. checkFloor(towerInfo);
  4584. }
  4585. /**
  4586. * Getting tower rewards
  4587. *
  4588. * Получаем награды башни
  4589. */
  4590. function farmTowerRewards(reason) {
  4591. let { pointRewards, points } = lastTowerInfo;
  4592. let pointsAll = Object.getOwnPropertyNames(pointRewards);
  4593. let farmPoints = pointsAll.filter(e => +e <= +points && !pointRewards[e]);
  4594. if (!farmPoints.length) {
  4595. return;
  4596. }
  4597. let farmTowerRewardsCall = {
  4598. calls: [{
  4599. name: "tower_farmPointRewards",
  4600. args: {
  4601. points: farmPoints
  4602. },
  4603. ident: "tower_farmPointRewards"
  4604. }]
  4605. }
  4606.  
  4607. if (scullCoin > 0 && reason == 'openChest 50 floor') {
  4608. farmTowerRewardsCall.calls.push({
  4609. name: "tower_farmSkullReward",
  4610. args: {},
  4611. ident: "tower_farmSkullReward"
  4612. });
  4613. }
  4614.  
  4615. send(JSON.stringify(farmTowerRewardsCall), () => { });
  4616. }
  4617.  
  4618. function fullSkipTower() {
  4619. /**
  4620. * Next chest
  4621. *
  4622. * Следующий сундук
  4623. */
  4624. function nextChest(n) {
  4625. return {
  4626. name: "towerNextChest",
  4627. args: {},
  4628. ident: "group_" + n + "_body"
  4629. }
  4630. }
  4631. /**
  4632. * Open chest
  4633. *
  4634. * Открыть сундук
  4635. */
  4636. function openChest(n) {
  4637. return {
  4638. name: "towerOpenChest",
  4639. args: {
  4640. "num": 2
  4641. },
  4642. ident: "group_" + n + "_body"
  4643. }
  4644. }
  4645.  
  4646. const fullSkipTowerCall = {
  4647. calls: []
  4648. }
  4649.  
  4650. let n = 0;
  4651. for (let i = 0; i < 15; i++) {
  4652. fullSkipTowerCall.calls.push(nextChest(++n));
  4653. fullSkipTowerCall.calls.push(openChest(++n));
  4654. }
  4655.  
  4656. send(JSON.stringify(fullSkipTowerCall), data => {
  4657. data.results[0] = data.results[28];
  4658. checkDataFloor(data);
  4659. });
  4660. }
  4661.  
  4662. function nextChestOpen(floorNumber) {
  4663. const calls = [{
  4664. name: "towerOpenChest",
  4665. args: {
  4666. num: 2
  4667. },
  4668. ident: "towerOpenChest"
  4669. }];
  4670.  
  4671. Send(JSON.stringify({ calls })).then(e => {
  4672. nextOpenChest(floorNumber);
  4673. });
  4674. }
  4675.  
  4676. function nextOpenChest(floorNumber) {
  4677. if (floorNumber > 49) {
  4678. endTower('openChest 50 floor', floorNumber);
  4679. return;
  4680. }
  4681. if (floorNumber == 1) {
  4682. fullSkipTower();
  4683. return;
  4684. }
  4685.  
  4686. let nextOpenChestCall = {
  4687. calls: [{
  4688. name: "towerNextChest",
  4689. args: {},
  4690. ident: "towerNextChest"
  4691. }, {
  4692. name: "towerOpenChest",
  4693. args: {
  4694. num: 2
  4695. },
  4696. ident: "towerOpenChest"
  4697. }]
  4698. }
  4699. send(JSON.stringify(nextOpenChestCall), checkDataFloor);
  4700. }
  4701.  
  4702. function endTower(reason, info) {
  4703. console.log(reason, info);
  4704. if (reason != 'noTower') {
  4705. farmTowerRewards(reason);
  4706. }
  4707. setProgress(`${I18N('TOWER')} ${I18N('COMPLETED')}!`, true);
  4708. resolve();
  4709. }
  4710. }
  4711.  
  4712. /**
  4713. * Passage of the arena of the titans
  4714. *
  4715. * Прохождение арены титанов
  4716. */
  4717. function testTitanArena() {
  4718. return new Promise((resolve, reject) => {
  4719. titAren = new executeTitanArena(resolve, reject);
  4720. titAren.start();
  4721. });
  4722. }
  4723.  
  4724. /**
  4725. * Passage of the arena of the titans
  4726. *
  4727. * Прохождение арены титанов
  4728. */
  4729. function executeTitanArena(resolve, reject) {
  4730. let titan_arena = [];
  4731. let finishListBattle = [];
  4732. /**
  4733. * ID of the current batch
  4734. *
  4735. * Идетификатор текущей пачки
  4736. */
  4737. let currentRival = 0;
  4738. /**
  4739. * Number of attempts to finish off the pack
  4740. *
  4741. * Количество попыток добития пачки
  4742. */
  4743. let attempts = 0;
  4744. /**
  4745. * Was there an attempt to finish off the current shooting range
  4746. *
  4747. * Была ли попытка добития текущего тира
  4748. */
  4749. let isCheckCurrentTier = false;
  4750. /**
  4751. * Current shooting range
  4752. *
  4753. * Текущий тир
  4754. */
  4755. let currTier = 0;
  4756. /**
  4757. * Number of battles on the current dash
  4758. *
  4759. * Количество битв на текущем тире
  4760. */
  4761. let countRivalsTier = 0;
  4762.  
  4763. let callsStart = {
  4764. calls: [{
  4765. name: "titanArenaGetStatus",
  4766. args: {},
  4767. ident: "titanArenaGetStatus"
  4768. }, {
  4769. name: "teamGetAll",
  4770. args: {},
  4771. ident: "teamGetAll"
  4772. }]
  4773. }
  4774.  
  4775. this.start = function () {
  4776. send(JSON.stringify(callsStart), startTitanArena);
  4777. }
  4778.  
  4779. function startTitanArena(data) {
  4780. let titanArena = data.results[0].result.response;
  4781. if (titanArena.status == 'disabled') {
  4782. endTitanArena('disabled', titanArena);
  4783. return;
  4784. }
  4785.  
  4786. let teamGetAll = data.results[1].result.response;
  4787. titan_arena = teamGetAll.titan_arena;
  4788.  
  4789. checkTier(titanArena)
  4790. }
  4791.  
  4792. function checkTier(titanArena) {
  4793. if (titanArena.status == "peace_time") {
  4794. endTitanArena('Peace_time', titanArena);
  4795. return;
  4796. }
  4797. currTier = titanArena.tier;
  4798. if (currTier) {
  4799. setProgress(`${I18N('TITAN_ARENA')}: ${I18N('LEVEL')} ${currTier}`);
  4800. }
  4801.  
  4802. if (titanArena.status == "completed_tier") {
  4803. titanArenaCompleteTier();
  4804. return;
  4805. }
  4806. /**
  4807. * Checking for the possibility of a raid
  4808. * Проверка на возможность рейда
  4809. */
  4810. if (titanArena.canRaid) {
  4811. titanArenaStartRaid();
  4812. return;
  4813. }
  4814. /**
  4815. * Check was an attempt to achieve the current shooting range
  4816. * Проверка была ли попытка добития текущего тира
  4817. */
  4818. if (!isCheckCurrentTier) {
  4819. checkRivals(titanArena.rivals);
  4820. return;
  4821. }
  4822.  
  4823. endTitanArena('Done or not canRaid', titanArena);
  4824. }
  4825. /**
  4826. * Submit dash information for verification
  4827. *
  4828. * Отправка информации о тире на проверку
  4829. */
  4830. function checkResultInfo(data) {
  4831. let titanArena = data.results[0].result.response;
  4832. checkTier(titanArena);
  4833. }
  4834. /**
  4835. * Finish the current tier
  4836. *
  4837. * Завершить текущий тир
  4838. */
  4839. function titanArenaCompleteTier() {
  4840. isCheckCurrentTier = false;
  4841. let calls = [{
  4842. name: "titanArenaCompleteTier",
  4843. args: {},
  4844. ident: "body"
  4845. }];
  4846. send(JSON.stringify({calls}), checkResultInfo);
  4847. }
  4848. /**
  4849. * Gathering points to be completed
  4850. *
  4851. * Собираем точки которые нужно добить
  4852. */
  4853. function checkRivals(rivals) {
  4854. finishListBattle = [];
  4855. for (let n in rivals) {
  4856. if (rivals[n].attackScore < 250) {
  4857. finishListBattle.push(n);
  4858. }
  4859. }
  4860. console.log('checkRivals', finishListBattle);
  4861. countRivalsTier = finishListBattle.length;
  4862. roundRivals();
  4863. }
  4864. /**
  4865. * Selecting the next point to finish off
  4866. *
  4867. * Выбор следующей точки для добития
  4868. */
  4869. function roundRivals() {
  4870. let countRivals = finishListBattle.length;
  4871. if (!countRivals) {
  4872. /**
  4873. * Whole range checked
  4874. *
  4875. * Весь тир проверен
  4876. */
  4877. isCheckCurrentTier = true;
  4878. titanArenaGetStatus();
  4879. return;
  4880. }
  4881. // setProgress('TitanArena: Уровень ' + currTier + ' Бои: ' + (countRivalsTier - countRivals + 1) + '/' + countRivalsTier);
  4882. currentRival = finishListBattle.pop();
  4883. attempts = +currentRival;
  4884. // console.log('roundRivals', currentRival);
  4885. titanArenaStartBattle(currentRival);
  4886. }
  4887. /**
  4888. * The start of a solo battle
  4889. *
  4890. * Начало одиночной битвы
  4891. */
  4892. function titanArenaStartBattle(rivalId) {
  4893. let calls = [{
  4894. name: "titanArenaStartBattle",
  4895. args: {
  4896. rivalId: rivalId,
  4897. titans: titan_arena
  4898. },
  4899. ident: "body"
  4900. }];
  4901. send(JSON.stringify({calls}), calcResult);
  4902. }
  4903. /**
  4904. * Calculation of the results of the battle
  4905. *
  4906. * Расчет результатов боя
  4907. */
  4908. function calcResult(data) {
  4909. let battlesInfo = data.results[0].result.response.battle;
  4910. /**
  4911. * If attempts are equal to the current battle number we make
  4912. * Если попытки равны номеру текущего боя делаем прерасчет
  4913. */
  4914. if (attempts == currentRival) {
  4915. preCalcBattle(battlesInfo);
  4916. return;
  4917. }
  4918. /**
  4919. * If there are still attempts, we calculate a new battle
  4920. * Если попытки еще есть делаем расчет нового боя
  4921. */
  4922. if (attempts > 0) {
  4923. attempts--;
  4924. calcBattleResult(battlesInfo)
  4925. .then(resultCalcBattle);
  4926. return;
  4927. }
  4928. /**
  4929. * Otherwise, go to the next opponent
  4930. * Иначе переходим к следующему сопернику
  4931. */
  4932. roundRivals();
  4933. }
  4934. /**
  4935. * Processing the results of the battle calculation
  4936. *
  4937. * Обработка результатов расчета битвы
  4938. */
  4939. function resultCalcBattle(resultBattle) {
  4940. // console.log('resultCalcBattle', currentRival, attempts, resultBattle.result.win);
  4941. /**
  4942. * If the current calculation of victory is not a chance or the attempt ended with the finish the battle
  4943. * Если текущий расчет победа или шансов нет или попытки кончились завершаем бой
  4944. */
  4945. if (resultBattle.result.win || !attempts) {
  4946. titanArenaEndBattle({
  4947. progress: resultBattle.progress,
  4948. result: resultBattle.result,
  4949. rivalId: resultBattle.battleData.typeId
  4950. });
  4951. return;
  4952. }
  4953. /**
  4954. * If not victory and there are attempts we start a new battle
  4955. * Если не победа и есть попытки начинаем новый бой
  4956. */
  4957. titanArenaStartBattle(resultBattle.battleData.typeId);
  4958. }
  4959. /**
  4960. * Returns the promise of calculating the results of the battle
  4961. *
  4962. * Возращает промис расчета результатов битвы
  4963. */
  4964. function getBattleInfo(battle, isRandSeed) {
  4965. return new Promise(function (resolve) {
  4966. if (isRandSeed) {
  4967. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  4968. }
  4969. // console.log(battle.seed);
  4970. BattleCalc(battle, "get_titanClanPvp", e => resolve(e));
  4971. });
  4972. }
  4973. /**
  4974. * Recalculate battles
  4975. *
  4976. * Прерасчтет битвы
  4977. */
  4978. function preCalcBattle(battle) {
  4979. let actions = [getBattleInfo(battle, false)];
  4980. const countTestBattle = getInput('countTestBattle');
  4981. for (let i = 0; i < countTestBattle; i++) {
  4982. actions.push(getBattleInfo(battle, true));
  4983. }
  4984. Promise.all(actions)
  4985. .then(resultPreCalcBattle);
  4986. }
  4987. /**
  4988. * Processing the results of the battle recalculation
  4989. *
  4990. * Обработка результатов прерасчета битвы
  4991. */
  4992. function resultPreCalcBattle(e) {
  4993. let wins = e.map(n => n.result.win);
  4994. let firstBattle = e.shift();
  4995. let countWin = wins.reduce((w, s) => w + s);
  4996. let numReval = countRivalsTier - finishListBattle.length;
  4997. // setProgress('TitanArena: Уровень ' + currTier + ' Бои: ' + numReval + '/' + countRivalsTier + ' - ' + countWin + '/11');
  4998. console.log('resultPreCalcBattle', countWin + '/11' )
  4999. if (countWin > 0) {
  5000. attempts = getInput('countAutoBattle');
  5001. } else {
  5002. attempts = 0;
  5003. }
  5004. resultCalcBattle(firstBattle);
  5005. }
  5006.  
  5007. /**
  5008. * Complete an arena battle
  5009. *
  5010. * Завершить битву на арене
  5011. */
  5012. function titanArenaEndBattle(args) {
  5013. let calls = [{
  5014. name: "titanArenaEndBattle",
  5015. args,
  5016. ident: "body"
  5017. }];
  5018. send(JSON.stringify({calls}), resultTitanArenaEndBattle);
  5019. }
  5020.  
  5021. function resultTitanArenaEndBattle(e) {
  5022. let attackScore = e.results[0].result.response.attackScore;
  5023. let numReval = countRivalsTier - finishListBattle.length;
  5024. setProgress(`${I18N('TITAN_ARENA')}: ${I18N('LEVEL')} ${currTier} </br>${I18N('BATTLES')}: ${numReval}/${countRivalsTier} - ${attackScore}`);
  5025. /**
  5026. * TODO: Might need to improve the results.
  5027. * TODO: Возможно стоит сделать улучшение результатов
  5028. */
  5029. // console.log('resultTitanArenaEndBattle', e)
  5030. console.log('resultTitanArenaEndBattle', numReval + '/' + countRivalsTier, attempts)
  5031. roundRivals();
  5032. }
  5033. /**
  5034. * Arena State
  5035. *
  5036. * Состояние арены
  5037. */
  5038. function titanArenaGetStatus() {
  5039. let calls = [{
  5040. name: "titanArenaGetStatus",
  5041. args: {},
  5042. ident: "body"
  5043. }];
  5044. send(JSON.stringify({calls}), checkResultInfo);
  5045. }
  5046. /**
  5047. * Arena Raid Request
  5048. *
  5049. * Запрос рейда арены
  5050. */
  5051. function titanArenaStartRaid() {
  5052. let calls = [{
  5053. name: "titanArenaStartRaid",
  5054. args: {
  5055. titans: titan_arena
  5056. },
  5057. ident: "body"
  5058. }];
  5059. send(JSON.stringify({calls}), calcResults);
  5060. }
  5061.  
  5062. function calcResults(data) {
  5063. let battlesInfo = data.results[0].result.response;
  5064. let {attackers, rivals} = battlesInfo;
  5065.  
  5066. let promises = [];
  5067. for (let n in rivals) {
  5068. rival = rivals[n];
  5069. promises.push(calcBattleResult({
  5070. attackers: attackers,
  5071. defenders: [rival.team],
  5072. seed: rival.seed,
  5073. typeId: n,
  5074. }));
  5075. }
  5076.  
  5077. Promise.all(promises)
  5078. .then(results => {
  5079. const endResults = {};
  5080. for (let info of results) {
  5081. let id = info.battleData.typeId;
  5082. endResults[id] = {
  5083. progress: info.progress,
  5084. result: info.result,
  5085. }
  5086. }
  5087. titanArenaEndRaid(endResults);
  5088. });
  5089. }
  5090.  
  5091. function calcBattleResult(battleData) {
  5092. return new Promise(function (resolve, reject) {
  5093. BattleCalc(battleData, "get_titanClanPvp", resolve);
  5094. });
  5095. }
  5096.  
  5097. /**
  5098. * Sending Raid Results
  5099. *
  5100. * Отправка результатов рейда
  5101. */
  5102. function titanArenaEndRaid(results) {
  5103. titanArenaEndRaidCall = {
  5104. calls: [{
  5105. name: "titanArenaEndRaid",
  5106. args: {
  5107. results
  5108. },
  5109. ident: "body"
  5110. }]
  5111. }
  5112. send(JSON.stringify(titanArenaEndRaidCall), checkRaidResults);
  5113. }
  5114.  
  5115. function checkRaidResults(data) {
  5116. results = data.results[0].result.response.results;
  5117. isSucsesRaid = true;
  5118. for (let i in results) {
  5119. isSucsesRaid &&= (results[i].attackScore >= 250);
  5120. }
  5121.  
  5122. if (isSucsesRaid) {
  5123. titanArenaCompleteTier();
  5124. } else {
  5125. titanArenaGetStatus();
  5126. }
  5127. }
  5128.  
  5129. function titanArenaFarmDailyReward() {
  5130. titanArenaFarmDailyRewardCall = {
  5131. calls: [{
  5132. name: "titanArenaFarmDailyReward",
  5133. args: {},
  5134. ident: "body"
  5135. }]
  5136. }
  5137. send(JSON.stringify(titanArenaFarmDailyRewardCall), () => {console.log('Done farm daily reward')});
  5138. }
  5139.  
  5140. function endTitanArena(reason, info) {
  5141. if (!['Peace_time', 'disabled'].includes(reason)) {
  5142. titanArenaFarmDailyReward();
  5143. }
  5144. console.log(reason, info);
  5145. setProgress(`${I18N('TITAN_ARENA')} ${I18N('COMPLETED')}!`, true);
  5146. resolve();
  5147. }
  5148. }
  5149.  
  5150. function hackGame() {
  5151. self = this;
  5152. selfGame = null;
  5153. bindId = 1e9;
  5154. this.libGame = null;
  5155.  
  5156. /**
  5157. * List of correspondence of used classes to their names
  5158. *
  5159. * Список соответствия используемых классов их названиям
  5160. */
  5161. ObjectsList = [
  5162. {name:"BattlePresets", prop:"game.battle.controller.thread.BattlePresets"},
  5163. {name:"DataStorage", prop:"game.data.storage.DataStorage"},
  5164. {name:"BattleConfigStorage", prop:"game.data.storage.battle.BattleConfigStorage"},
  5165. {name:"BattleInstantPlay", prop:"game.battle.controller.instant.BattleInstantPlay"},
  5166. {name:"MultiBattleResult", prop:"game.battle.controller.MultiBattleResult"},
  5167.  
  5168. {name:"PlayerMissionData", prop:"game.model.user.mission.PlayerMissionData"},
  5169. {name:"PlayerMissionBattle", prop:"game.model.user.mission.PlayerMissionBattle"},
  5170. {name:"GameModel", prop:"game.model.GameModel"},
  5171. {name:"CommandManager", prop:"game.command.CommandManager"},
  5172. {name:"MissionCommandList", prop:"game.command.rpc.mission.MissionCommandList"},
  5173. {name:"RPCCommandBase", prop:"game.command.rpc.RPCCommandBase"},
  5174. {name:"PlayerTowerData", prop:"game.model.user.tower.PlayerTowerData"},
  5175. {name:"TowerCommandList", prop:"game.command.tower.TowerCommandList"},
  5176. {name:"PlayerHeroTeamResolver", prop:"game.model.user.hero.PlayerHeroTeamResolver"},
  5177. {name:"BattlePausePopup", prop:"game.view.popup.battle.BattlePausePopup"},
  5178. {name:"BattlePopup", prop:"game.view.popup.battle.BattlePopup"},
  5179. {name:"DisplayObjectContainer", prop:"starling.display.DisplayObjectContainer"},
  5180. {name:"GuiClipContainer", prop:"engine.core.clipgui.GuiClipContainer"},
  5181. {name:"BattlePausePopupClip", prop:"game.view.popup.battle.BattlePausePopupClip"},
  5182. {name:"ClipLabel", prop:"game.view.gui.components.ClipLabel"},
  5183. {name:"ClipLabelBase", prop:"game.view.gui.components.ClipLabelBase"},
  5184. {name:"Translate", prop:"com.progrestar.common.lang.Translate"},
  5185. {name:"ClipButtonLabeledCentered", prop:"game.view.gui.components.ClipButtonLabeledCentered"},
  5186. {name:"BattlePausePopupMediator", prop:"game.mediator.gui.popup.battle.BattlePausePopupMediator"},
  5187. {name:"SettingToggleButton", prop:"game.mechanics.settings.popup.view.SettingToggleButton"},
  5188. {name:"PlayerDungeonData", prop:"game.mechanics.dungeon.model.PlayerDungeonData"},
  5189. {name:"NextDayUpdatedManager", prop:"game.model.user.NextDayUpdatedManager"},
  5190. {name:"BattleController", prop:"game.battle.controller.BattleController"},
  5191. {name:"BattleSettingsModel", prop:"game.battle.controller.BattleSettingsModel"},
  5192. {name:"BooleanProperty", prop:"engine.core.utils.property.BooleanProperty"},
  5193. {name:"RuleStorage", prop:"game.data.storage.rule.RuleStorage"},
  5194. {name:"BattleConfig", prop:"battle.BattleConfig"},
  5195. {name:"SpecialShopModel", prop:"game.model.user.shop.SpecialShopModel"},
  5196. {name:"BattleGuiMediator", prop:"game.battle.gui.BattleGuiMediator"},
  5197. {name:"BooleanPropertyWriteable", prop:"engine.core.utils.property.BooleanPropertyWriteable"},
  5198. { name: "BattleLogEncoder", prop: "battle.log.BattleLogEncoder" },
  5199. { name: "BattleLogReader", prop: "battle.log.BattleLogReader" },
  5200. ];
  5201.  
  5202. /**
  5203. * Contains the game classes needed to write and override game methods
  5204. *
  5205. * Содержит классы игры необходимые для написания и подмены методов игры
  5206. */
  5207. Game = {
  5208. /**
  5209. * Function 'e'
  5210. * Функция 'e'
  5211. */
  5212. bindFunc: function (a, b) {
  5213. if (null == b)
  5214. return null;
  5215. null == b.__id__ && (b.__id__ = bindId++);
  5216. var c;
  5217. null == a.hx__closures__ ? a.hx__closures__ = {} :
  5218. c = a.hx__closures__[b.__id__];
  5219. null == c && (c = b.bind(a), a.hx__closures__[b.__id__] = c);
  5220. return c
  5221. },
  5222. };
  5223.  
  5224. /**
  5225. * Connects to game objects via the object creation event
  5226. *
  5227. * Подключается к объектам игры через событие создания объекта
  5228. */
  5229. function connectGame() {
  5230. for (let obj of ObjectsList) {
  5231. /**
  5232. * https: //stackoverflow.com/questions/42611719/how-to-intercept-and-modify-a-specific-property-for-any-object
  5233. */
  5234. Object.defineProperty(Object.prototype, obj.prop, {
  5235. set: function (value) {
  5236. if (!selfGame) {
  5237. selfGame = this;
  5238. }
  5239. if (!Game[obj.name]) {
  5240. Game[obj.name] = value;
  5241. }
  5242. // console.log('set ' + obj.prop, this, value);
  5243. this[obj.prop + '_'] = value;
  5244. },
  5245. get: function () {
  5246. // console.log('get ' + obj.prop, this);
  5247. return this[obj.prop + '_'];
  5248. }
  5249. });
  5250. }
  5251. }
  5252.  
  5253. /**
  5254. * Game.BattlePresets
  5255. * @param {bool} a isReplay
  5256. * @param {bool} b autoToggleable
  5257. * @param {bool} c auto On Start
  5258. * @param {object} d config
  5259. * @param {bool} f showBothTeams
  5260. */
  5261. /**
  5262. * Returns the results of the battle to the callback function
  5263. * Возвращает в функцию callback результаты боя
  5264. * @param {*} battleData battle data данные боя
  5265. * @param {*} battleConfig combat configuration type options:
  5266. *
  5267. * тип конфигурации боя варианты:
  5268. *
  5269. * "get_invasion", "get_titanPvpManual", "get_titanPvp",
  5270. * "get_titanClanPvp","get_clanPvp","get_titan","get_boss",
  5271. * "get_tower","get_pve","get_pvpManual","get_pvp","get_core"
  5272. *
  5273. * You can specify the xYc function in the game.assets.storage.BattleAssetStorage class
  5274. *
  5275. * Можно уточнить в классе game.assets.storage.BattleAssetStorage функция xYc
  5276. * @param {*} callback функция в которую вернуться результаты боя
  5277. */
  5278. this.BattleCalc = function (battleData, battleConfig, callback) {
  5279. // battleConfig = battleConfig || getBattleType(battleData.type)
  5280. if (!Game.BattlePresets) throw Error('Use connectGame');
  5281. battlePresets = new Game.BattlePresets(!!battleData.progress, !1, !0, Game.DataStorage[getFn(Game.DataStorage, 22)][getF(Game.BattleConfigStorage, battleConfig)](), !1);
  5282. battleInstantPlay = new Game.BattleInstantPlay(battleData, battlePresets);
  5283. battleInstantPlay[getProtoFn(Game.BattleInstantPlay, 8)].add((battleInstant) => {
  5284. const battleResult = battleInstant[getF(Game.BattleInstantPlay, 'get_result')]();
  5285. const battleData = battleInstant[getF(Game.BattleInstantPlay, 'get_rawBattleInfo')]();
  5286. const battleLog = Game.BattleLogEncoder.read(new Game.BattleLogReader(battleResult[getProtoFn(Game.MultiBattleResult, 2)][0]));
  5287. const timeLimit = battlePresets[getF(Game.BattlePresets, 'get_timeLimit')]();
  5288. const battleTime = Math.max(...battleLog.map(e => e.time < timeLimit ? e.time : 0));
  5289. callback({
  5290. battleTime,
  5291. battleData,
  5292. progress: battleResult[getF(Game.MultiBattleResult, 'get_progress')](),
  5293. result: battleResult[getF(Game.MultiBattleResult, 'get_result')]()
  5294. })
  5295. });
  5296. battleInstantPlay.start();
  5297. }
  5298.  
  5299. /**
  5300. * Returns a function with the specified name from the class
  5301. *
  5302. * Возвращает из класса функцию с указанным именем
  5303. * @param {Object} classF Class // класс
  5304. * @param {String} nameF function name // имя функции
  5305. * @param {String} pos name and alias order // порядок имени и псевдонима
  5306. * @returns
  5307. */
  5308. function getF(classF, nameF, pos) {
  5309. pos = pos || false;
  5310. let prop = Object.entries(classF.prototype.__properties__)
  5311. if (!pos) {
  5312. return prop.filter((e) => e[1] == nameF).pop()[0];
  5313. } else {
  5314. return prop.filter((e) => e[0] == nameF).pop()[1];
  5315. }
  5316. }
  5317.  
  5318. /**
  5319. * Returns a function with the specified name from the class
  5320. *
  5321. * Возвращает из класса функцию с указанным именем
  5322. * @param {Object} classF Class // класс
  5323. * @param {String} nameF function name // имя функции
  5324. * @returns
  5325. */
  5326. function getFnP(classF, nameF) {
  5327. let prop = Object.entries(classF.__properties__)
  5328. return prop.filter((e) => e[1] == nameF).pop()[0];
  5329. }
  5330.  
  5331. /**
  5332. * Returns the function name with the specified ordinal from the class
  5333. *
  5334. * Возвращает имя функции с указаным порядковым номером из класса
  5335. * @param {Object} classF Class // класс
  5336. * @param {Number} nF Order number of function // порядковый номер функции
  5337. * @returns
  5338. */
  5339. function getFn(classF, nF) {
  5340. let prop = Object.keys(classF);
  5341. return prop[nF];
  5342. }
  5343.  
  5344. /**
  5345. * Returns the name of the function with the specified serial number from the prototype of the class
  5346. *
  5347. * Возвращает имя функции с указаным порядковым номером из прототипа класса
  5348. * @param {Object} classF Class // класс
  5349. * @param {Number} nF Order number of function // порядковый номер функции
  5350. * @returns
  5351. */
  5352. function getProtoFn(classF, nF) {
  5353. let prop = Object.keys(classF.prototype);
  5354. return prop[nF];
  5355. }
  5356. /**
  5357. * Description of replaced functions
  5358. *
  5359. * Описание подменяемых функций
  5360. */
  5361. replaceFunction = {
  5362. company: function() {
  5363. let PMD_12 = getProtoFn(Game.PlayerMissionData, 12);
  5364. let oldSkipMisson = Game.PlayerMissionData.prototype[PMD_12];
  5365. Game.PlayerMissionData.prototype[PMD_12] = function (a, b, c) {
  5366. if (isChecked('passBattle')) {
  5367. this[getProtoFn(Game.PlayerMissionData, 9)] = new Game.PlayerMissionBattle(a, b, c);
  5368.  
  5369. var a = new Game.BattlePresets(!1, !1, !0, Game.DataStorage[getFn(Game.DataStorage, 22)][getProtoFn(Game.BattleConfigStorage, 17)](), !1);
  5370. a = new Game.BattleInstantPlay(c, a);
  5371. a[getProtoFn(Game.BattleInstantPlay, 8)].add(Game.bindFunc(this, this.P$h));
  5372. a.start()
  5373. } else {
  5374. oldSkipMisson.call(this, a, b, c);
  5375. }
  5376. }
  5377.  
  5378. Game.PlayerMissionData.prototype.P$h = function (a) {
  5379. let GM_2 = getFn(Game.GameModel, 2);
  5380. let GM_P2 = getProtoFn(Game.GameModel, 2);
  5381. let CM_20 = getProtoFn(Game.CommandManager, 20);
  5382. let MCL_2 = getProtoFn(Game.MissionCommandList, 2);
  5383. let MBR_15 = getProtoFn(Game.MultiBattleResult, 15);
  5384. let RPCCB_15 = getProtoFn(Game.RPCCommandBase, 15);
  5385. let PMD_32 = getProtoFn(Game.PlayerMissionData, 32);
  5386. Game.GameModel[GM_2]()[GM_P2][CM_20][MCL_2](a[MBR_15]())[RPCCB_15](Game.bindFunc(this, this[PMD_32]))
  5387. }
  5388. },
  5389. tower: function() {
  5390. let PTD_67 = getProtoFn(Game.PlayerTowerData, 67);
  5391. let oldSkipTower = Game.PlayerTowerData.prototype[PTD_67];
  5392. Game.PlayerTowerData.prototype[PTD_67] = function (a) {
  5393. if (isChecked('passBattle')) {
  5394. var p = new Game.BattlePresets(!1, !1, !0, Game.DataStorage[getFn(Game.DataStorage, 22)][getProtoFn(Game.BattleConfigStorage,17)](), !1);
  5395. a = new Game.BattleInstantPlay(a, p);
  5396. a[getProtoFn(Game.BattleInstantPlay,8)].add(Game.bindFunc(this, this.P$h));
  5397. a.start()
  5398. } else {
  5399. oldSkipTower.call(this, a);;
  5400. }
  5401. }
  5402.  
  5403. Game.PlayerTowerData.prototype.P$h = function (a) {
  5404. const GM_2 = getFnP(Game.GameModel, "get_instance");
  5405. const GM_P2 = getProtoFn(Game.GameModel, 2);
  5406. const CM_29 = getProtoFn(Game.CommandManager, 29);
  5407. const TCL_5 = getProtoFn(Game.TowerCommandList, 5);
  5408. const MBR_15 = getF(Game.MultiBattleResult, "get_result");
  5409. const RPCCB_15 = getProtoFn(Game.RPCCommandBase, 16);
  5410. const PTD_78 = getProtoFn(Game.PlayerTowerData, 78);
  5411. Game.GameModel[GM_2]()[GM_P2][CM_29][TCL_5](a[MBR_15]())[RPCCB_15](Game.bindFunc(this, this[PTD_78]));
  5412. }
  5413. },
  5414. // skipSelectHero: function() {
  5415. // if (!HOST) throw Error('Use connectGame');
  5416. // Game.PlayerHeroTeamResolver.prototype[getProtoFn(Game.PlayerHeroTeamResolver, 3)] = () => false;
  5417. // },
  5418. passBattle: function() {
  5419. let BPP_4 = getProtoFn(Game.BattlePausePopup, 4);
  5420. let oldPassBattle = Game.BattlePausePopup.prototype[BPP_4];
  5421. Game.BattlePausePopup.prototype[BPP_4] = function (a) {
  5422. if (isChecked('passBattle')) {
  5423. Game.BattlePopup.prototype[getProtoFn(Game.BattlePausePopup, 4)].call(this, a);
  5424. this[getProtoFn(Game.BattlePausePopup, 3)]();
  5425. this[getProtoFn(Game.DisplayObjectContainer, 3)](this.clip[getProtoFn(Game.GuiClipContainer, 2)]());
  5426. this.clip[getProtoFn(Game.BattlePausePopupClip, 1)][getProtoFn(Game.ClipLabelBase, 9)](Game.Translate.translate("UI_POPUP_BATTLE_PAUSE"));
  5427.  
  5428. this.clip[getProtoFn(Game.BattlePausePopupClip, 2)][getProtoFn(Game.ClipButtonLabeledCentered, 2)](Game.Translate.translate("UI_POPUP_BATTLE_RETREAT"), (q = this[getProtoFn(Game.BattlePausePopup, 1)], Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 17)])));
  5429. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 2)](
  5430. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 14)](),
  5431. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 13)]() ?
  5432. (q = this[getProtoFn(Game.BattlePausePopup, 1)], Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 18)])) :
  5433. (q = this[getProtoFn(Game.BattlePausePopup, 1)], Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 18)]))
  5434. );
  5435.  
  5436. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 0)][getProtoFn(Game.ClipLabelBase, 24)]();
  5437. this.clip[getProtoFn(Game.BattlePausePopupClip, 3)][getProtoFn(Game.SettingToggleButton, 3)](this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 9)]());
  5438. this.clip[getProtoFn(Game.BattlePausePopupClip, 4)][getProtoFn(Game.SettingToggleButton, 3)](this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 10)]());
  5439. this.clip[getProtoFn(Game.BattlePausePopupClip, 6)][getProtoFn(Game.SettingToggleButton, 3)](this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 11)]());
  5440. /*
  5441. Какая-то ненужная фигня
  5442. if (!HC.lSb()) {
  5443. this.clip.r6b.g().B(!1);
  5444. a = this.clip.r6b.g().X() + 7;
  5445. var b = this.clip.ba.g();
  5446. b.$(b.X() - a);
  5447. b = this.clip.IS.g();
  5448. b.sa(b.Fa() - a)
  5449. }
  5450. */
  5451. } else {
  5452. oldPassBattle.call(this, a);
  5453. }
  5454. }
  5455.  
  5456. let retreatButtonLabel = getF(Game.BattlePausePopupMediator, "get_retreatButtonLabel");
  5457. let oldFunc = Game.BattlePausePopupMediator.prototype[retreatButtonLabel];
  5458. Game.BattlePausePopupMediator.prototype[retreatButtonLabel] = function () {
  5459. if (isChecked('passBattle')) {
  5460. return I18N('BTN_PASS');
  5461. } else {
  5462. return oldFunc.call(this);
  5463. }
  5464. }
  5465. },
  5466. endlessCards: function() {
  5467. let PDD_15 = getProtoFn(Game.PlayerDungeonData, 15);
  5468. let oldEndlessCards = Game.PlayerDungeonData.prototype[PDD_15];
  5469. Game.PlayerDungeonData.prototype[PDD_15] = function () {
  5470. if (isChecked('endlessCards')) {
  5471. return true;
  5472. } else {
  5473. return oldEndlessCards.call(this);
  5474. }
  5475. }
  5476. },
  5477. speedBattle: function () {
  5478. const get_timeScale = getF(Game.BattleController, "get_timeScale");
  5479. const oldSpeedBattle = Game.BattleController.prototype[get_timeScale];
  5480. Game.BattleController.prototype[get_timeScale] = function () {
  5481. const speedBattle = Number.parseFloat(getInput('speedBattle'));
  5482. if (speedBattle) {
  5483. const BC_11 = getProtoFn(Game.BattleController, 11);
  5484. const BSM_11 = getProtoFn(Game.BattleSettingsModel, 11);
  5485. const BP_get_value = getF(Game.BooleanProperty, "get_value");
  5486. if (this[BC_11][BSM_11][BP_get_value]()) {
  5487. return 0;
  5488. }
  5489. const BSM_2 = getProtoFn(Game.BattleSettingsModel, 2);
  5490. const BC_44 = getProtoFn(Game.BattleController, 44);
  5491. const BSM_1 = getProtoFn(Game.BattleSettingsModel, 1);
  5492. const BC_13 = getProtoFn(Game.BattleController, 13);
  5493. const BC_3 = getFn(Game.BattleController, 3);
  5494. if (this[BC_11][BSM_2][BP_get_value]()) {
  5495. var a = speedBattle * this[BC_44]();
  5496. } else {
  5497. a = this[BC_11][BSM_1][BP_get_value]();
  5498. //const multiple = a == 1 ? speedBattle : this[BC_13][a];
  5499. a = this[BC_13][a] * Game.BattleController[BC_3][BP_get_value]() * this[BC_44]();
  5500. }
  5501. const BSM_22 = getProtoFn(Game.BattleSettingsModel, 22);
  5502. a > this[BC_11][BSM_22][BP_get_value]() && (a = this[BC_11][BSM_22][BP_get_value]());
  5503. const DS_21 = getFn(Game.DataStorage, 21);
  5504. const get_battleSpeedMultiplier = getF(Game.RuleStorage, "get_battleSpeedMultiplier", true);
  5505. // const RS_167 = getProtoFn(Game.RuleStorage, 167); // get_battleSpeedMultiplier
  5506. var b = Game.DataStorage[DS_21][get_battleSpeedMultiplier]();
  5507. const R_1 = getFn(selfGame.Reflect, 1);
  5508. const BC_1 = getFn(Game.BattleController, 1);
  5509. const get_config = getF(Game.BattlePresets, "get_config");
  5510. // const BC_0 = getProtoFn(Game.BattleConfig, 0); // .ident
  5511. null != b && (a = selfGame.Reflect[R_1](b, this[BC_1][get_config]().ident) ? a * selfGame.Reflect[R_1](b, this[BC_1][get_config]().ident) : a * selfGame.Reflect[R_1](b, "default"));
  5512. return a
  5513. } else {
  5514. return oldSpeedBattle.call(this);
  5515. }
  5516. }
  5517. },
  5518.  
  5519. /**
  5520. * Remove the rare shop
  5521. *
  5522. * Удаление торговца редкими товарами
  5523. */
  5524. /*
  5525. removeWelcomeShop: function () {
  5526. let SSM_3 = getProtoFn(Game.SpecialShopModel, 3);
  5527. const oldWelcomeShop = Game.SpecialShopModel.prototype[SSM_3];
  5528. Game.SpecialShopModel.prototype[SSM_3] = function () {
  5529. if (isChecked('noOfferDonat')) {
  5530. return null;
  5531. } else {
  5532. return oldWelcomeShop.call(this);
  5533. }
  5534. }
  5535. },
  5536. */
  5537.  
  5538. /**
  5539. * Acceleration button without Valkyries favor
  5540. *
  5541. * Кнопка ускорения без Покровительства Валькирий
  5542. */
  5543. battleFastKey: function () {
  5544. const BGM_39 = getProtoFn(Game.BattleGuiMediator, 39);
  5545. const oldBattleFastKey = Game.BattleGuiMediator.prototype[BGM_39];
  5546. Game.BattleGuiMediator.prototype[BGM_39] = function () {
  5547. if (true) {
  5548. const BGM_8 = getProtoFn(Game.BattleGuiMediator, 8);
  5549. const BGM_9 = getProtoFn(Game.BattleGuiMediator, 9);
  5550. const BPW_0 = getProtoFn(Game.BooleanPropertyWriteable, 0);
  5551. this[BGM_8][BPW_0](true);
  5552. this[BGM_9][BPW_0](true);
  5553. } else {
  5554. return oldBattleFastKey.call(this);
  5555. }
  5556. }
  5557. }
  5558. }
  5559.  
  5560. /**
  5561. * Starts replacing recorded functions
  5562. *
  5563. * Запускает замену записанных функций
  5564. */
  5565. this.activateHacks = function () {
  5566. if (!selfGame) throw Error('Use connectGame');
  5567. for (let func in replaceFunction) {
  5568. replaceFunction[func]();
  5569. }
  5570. }
  5571.  
  5572. /**
  5573. * Returns the game object
  5574. *
  5575. * Возвращает объект игры
  5576. */
  5577. this.getSelfGame = function () {
  5578. return selfGame;
  5579. }
  5580.  
  5581. /**
  5582. * Updates game data
  5583. *
  5584. * Обновляет данные игры
  5585. */
  5586. this.refreshGame = function () {
  5587. (new Game.NextDayUpdatedManager)[getProtoFn(Game.NextDayUpdatedManager, 5)]();
  5588. }
  5589.  
  5590. /**
  5591. * Change the play screen on windowName
  5592. *
  5593. * Сменить экран игры на windowName
  5594. *
  5595. * Possible options:
  5596. *
  5597. * Возможные варианты:
  5598. *
  5599. * 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
  5600. */
  5601. this.goNavigtor = function (windowName) {
  5602. let mechanicStorage = selfGame["game.data.storage.mechanic.MechanicStorage"];
  5603. let window = mechanicStorage[windowName];
  5604. let event = new selfGame["game.mediator.gui.popup.PopupStashEventParams"];
  5605. let Game = selfGame['Game'];
  5606. let navigator = getF(Game, "get_navigator")
  5607. let navigate = getProtoFn(selfGame["game.screen.navigator.GameNavigator"], 17)
  5608. let instance = getFnP(Game, 'get_instance');
  5609. Game[instance]()[navigator]()[navigate](window, event);
  5610. }
  5611.  
  5612. /**
  5613. * Move to the sanctuary cheats.goSanctuary()
  5614. *
  5615. * Переместиться в святилище cheats.goSanctuary()
  5616. */
  5617. this.goSanctuary = () => {
  5618. this.goNavigtor("SANCTUARY");
  5619. }
  5620.  
  5621. /**
  5622. * Go to Guild War
  5623. *
  5624. * Перейти к Войне Гильдий
  5625. */
  5626. this.goClanWar = function() {
  5627. let instance = getFnP(selfGame["game.model.GameModel"], 'get_instance')
  5628. let player = selfGame["game.model.GameModel"][instance]().A;
  5629. let clanWarSelect = selfGame["game.mechanics.cross_clan_war.popup.selectMode.CrossClanWarSelectModeMediator"];
  5630. new clanWarSelect(player).open();
  5631. }
  5632.  
  5633. /**
  5634. * Go to BrawlShop
  5635. *
  5636. * Переместиться в BrawlShop
  5637. */
  5638. this.goBrawlShop = () => {
  5639. const instance = getFnP(selfGame["game.model.GameModel"], 'get_instance')
  5640. const P_36 = getProtoFn(selfGame["game.model.user.Player"], 36);
  5641. const PSD_0 = getProtoFn(selfGame["game.model.user.shop.PlayerShopData"], 0);
  5642. const IM_0 = getProtoFn(selfGame["haxe.ds.IntMap"], 0);
  5643. const PSDE_4 = getProtoFn(selfGame["game.model.user.shop.PlayerShopDataEntry"], 4);
  5644.  
  5645. const player = selfGame["game.model.GameModel"][instance]().A;
  5646. const shop = player[P_36][PSD_0][IM_0][1038][PSDE_4];
  5647. const shopPopup = new selfGame["game.mechanics.brawl.mediator.BrawlShopPopupMediator"](player, shop)
  5648. shopPopup.open(new selfGame["game.mediator.gui.popup.PopupStashEventParams"])
  5649. }
  5650.  
  5651. /**
  5652. * Game library availability tracker
  5653. *
  5654. * Отслеживание доступности игровой библиотеки
  5655. */
  5656. function checkLibLoad() {
  5657. timeout = setTimeout(() => {
  5658. if (Game.GameModel) {
  5659. changeLib();
  5660. } else {
  5661. checkLibLoad();
  5662. }
  5663. }, 100)
  5664. }
  5665.  
  5666. /**
  5667. * Game library data spoofing
  5668. *
  5669. * Подмена данных игровой библиотеки
  5670. */
  5671. function changeLib() {
  5672. console.log('lib connect');
  5673. const originalStartFunc = Game.GameModel.prototype.start;
  5674. Game.GameModel.prototype.start = function (a, b, c) {
  5675. self.libGame = b.raw;
  5676. try {
  5677. b.raw.shop[26].requirements = null;
  5678. } catch (e) {
  5679. console.warn(e);
  5680. }
  5681. originalStartFunc.call(this, a, b, c);
  5682. }
  5683. }
  5684.  
  5685. /**
  5686. * Returns the value of a language constant
  5687. *
  5688. * Возвращает значение языковой константы
  5689. * @param {*} langConst language constant // языковая константа
  5690. * @returns
  5691. */
  5692. this.translate = function (langConst) {
  5693. return Game.Translate.translate(langConst);
  5694. }
  5695.  
  5696. connectGame();
  5697. checkLibLoad();
  5698. }
  5699.  
  5700. /**
  5701. * Auto collection of gifts
  5702. *
  5703. * Автосбор подарков
  5704. */
  5705. function getAutoGifts() {
  5706. let valName = 'giftSendIds_' + userInfo.id;
  5707.  
  5708. if (!localStorage['clearGift' + userInfo.id]) {
  5709. localStorage[valName] = '';
  5710. localStorage['clearGift' + userInfo.id] = '+';
  5711. }
  5712.  
  5713. if (!localStorage[valName]) {
  5714. localStorage[valName] = '';
  5715. }
  5716.  
  5717. /**
  5718. * Submit a request to receive gift codes
  5719. *
  5720. * Отправка запроса для получения кодов подарков
  5721. */
  5722. fetch('https://zingery.ru/heroes/getGifts.php', {
  5723. method: 'POST',
  5724. body: JSON.stringify({scriptInfo, userInfo})
  5725. }).then(
  5726. response => response.json()
  5727. ).then(
  5728. data => {
  5729. let freebieCheckCalls = {
  5730. calls: []
  5731. }
  5732. data.forEach((giftId, n) => {
  5733. if (localStorage[valName].includes(giftId)) return;
  5734. //localStorage[valName] += ';' + giftId;
  5735. freebieCheckCalls.calls.push({
  5736. name: "freebieCheck",
  5737. args: {
  5738. giftId
  5739. },
  5740. ident: giftId
  5741. });
  5742. });
  5743.  
  5744. if (!freebieCheckCalls.calls.length) {
  5745. return;
  5746. }
  5747.  
  5748. send(JSON.stringify(freebieCheckCalls), e => {
  5749. let countGetGifts = 0;
  5750. const gifts = [];
  5751. for (check of e.results) {
  5752. gifts.push(check.ident);
  5753. if (check.result.response != null) {
  5754. countGetGifts++;
  5755. }
  5756. }
  5757. const saveGifts = localStorage[valName].split(';');
  5758. localStorage[valName] = [...saveGifts, ...gifts].slice(-50).join(';');
  5759. console.log(`${I18N('GIFTS')}: ${countGetGifts}`);
  5760. });
  5761. }
  5762. )
  5763. }
  5764.  
  5765. /**
  5766. * To fill the kills in the Forge of Souls
  5767. *
  5768. * Набить килов в горниле душ
  5769. */
  5770. async function bossRatingEvent() {
  5771. const topGet = await Send(JSON.stringify({ calls: [{ name: "topGet", args: { type: "bossRatingTop", extraId: 0 }, ident: "body" }] }));
  5772. if (!topGet) {
  5773. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  5774. return;
  5775. }
  5776. const replayId = topGet.results[0].result.response[0].userData.replayId;
  5777. const result = await Send(JSON.stringify({
  5778. calls: [
  5779. { name: "battleGetReplay", args: { id: replayId }, ident: "battleGetReplay" },
  5780. { name: "heroGetAll", args: {}, ident: "heroGetAll" },
  5781. { name: "pet_getAll", args: {}, ident: "pet_getAll" },
  5782. { name: "offerGetAll", args: {}, ident: "offerGetAll" }
  5783. ]
  5784. }));
  5785. const bossEventInfo = result.results[3].result.response.find(e => e.offerType == "bossEvent");
  5786. if (!bossEventInfo) {
  5787. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  5788. return;
  5789. }
  5790. const usedHeroes = bossEventInfo.progress.usedHeroes;
  5791. const party = Object.values(result.results[0].result.response.replay.attackers);
  5792. const availableHeroes = Object.values(result.results[1].result.response).map(e => e.id);
  5793. const availablePets = Object.values(result.results[2].result.response).map(e => e.id);
  5794. const calls = [];
  5795. /**
  5796. * First pack
  5797. *
  5798. * Первая пачка
  5799. */
  5800. const args = {
  5801. heroes: [],
  5802. favor: {}
  5803. }
  5804. for (let hero of party) {
  5805. if (hero.id >= 6000 && availablePets.includes(hero.id)) {
  5806. args.pet = hero.id;
  5807. continue;
  5808. }
  5809. if (!availableHeroes.includes(hero.id) || usedHeroes.includes(hero.id)) {
  5810. continue;
  5811. }
  5812. args.heroes.push(hero.id);
  5813. if (hero.favorPetId) {
  5814. args.favor[hero.id] = hero.favorPetId;
  5815. }
  5816. }
  5817. if (args.heroes.length) {
  5818. calls.push({
  5819. name: "bossRatingEvent_startBattle",
  5820. args,
  5821. ident: "body_0"
  5822. });
  5823. }
  5824. /**
  5825. * Other packs
  5826. *
  5827. * Другие пачки
  5828. */
  5829. let heroes = [];
  5830. let count = 1;
  5831. while (heroId = availableHeroes.pop()) {
  5832. if (args.heroes.includes(heroId) || usedHeroes.includes(heroId)) {
  5833. continue;
  5834. }
  5835. heroes.push(heroId);
  5836. if (heroes.length == 5) {
  5837. calls.push({
  5838. name: "bossRatingEvent_startBattle",
  5839. args: {
  5840. heroes: [...heroes],
  5841. pet: availablePets[Math.floor(Math.random() * availablePets.length)]
  5842. },
  5843. ident: "body_" + count
  5844. });
  5845. heroes = [];
  5846. count++;
  5847. }
  5848. }
  5849.  
  5850. if (!calls.length) {
  5851. setProgress(`${I18N('NO_HEROES')}`, true);
  5852. return;
  5853. }
  5854.  
  5855. const resultBattles = await Send(JSON.stringify({ calls }));
  5856. console.log(resultBattles);
  5857. rewardBossRatingEvent();
  5858. }
  5859.  
  5860. /**
  5861. * Collecting Rewards from the Forge of Souls
  5862. *
  5863. * Сбор награды из Горнила Душ
  5864. */
  5865. function rewardBossRatingEvent() {
  5866. let rewardBossRatingCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  5867. send(rewardBossRatingCall, function (data) {
  5868. let bossEventInfo = data.results[0].result.response.find(e => e.offerType == "bossEvent");
  5869. if (!bossEventInfo) {
  5870. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  5871. return;
  5872. }
  5873.  
  5874. let farmedChests = bossEventInfo.progress.farmedChests;
  5875. let score = bossEventInfo.progress.score;
  5876. setProgress(`${I18N('DAMAGE_AMOUNT')}: ${score}`);
  5877. let revard = bossEventInfo.reward;
  5878.  
  5879. let getRewardCall = {
  5880. calls: []
  5881. }
  5882.  
  5883. let count = 0;
  5884. for (let i = 1; i < 10; i++) {
  5885. if (farmedChests.includes(i)) {
  5886. continue;
  5887. }
  5888. if (score < revard[i].score) {
  5889. break;
  5890. }
  5891. getRewardCall.calls.push({
  5892. name: "bossRatingEvent_getReward",
  5893. args: {
  5894. rewardId: i
  5895. },
  5896. ident: "body_" + i
  5897. });
  5898. count++;
  5899. }
  5900. if (!count) {
  5901. setProgress(`${I18N('NOTHING_TO_COLLECT')}`, true);
  5902. return;
  5903. }
  5904.  
  5905. send(JSON.stringify(getRewardCall), e => {
  5906. console.log(e);
  5907. setProgress(`${I18N('COLLECTED')} ${e?.results?.length} ${I18N('REWARD')}`, true);
  5908. });
  5909. });
  5910. }
  5911.  
  5912. /**
  5913. * Collect Easter eggs and event rewards
  5914. *
  5915. * Собрать пасхалки и награды событий
  5916. */
  5917. function offerFarmAllReward() {
  5918. const offerGetAllCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  5919. return Send(offerGetAllCall).then((data) => {
  5920. const offerGetAll = data.results[0].result.response.filter(e => e.type == "reward" && !e?.freeRewardObtained && e.reward);
  5921. if (!offerGetAll.length) {
  5922. setProgress(`${I18N('NOTHING_TO_COLLECT')}`, true);
  5923. return;
  5924. }
  5925.  
  5926. const calls = [];
  5927. for (let reward of offerGetAll) {
  5928. calls.push({
  5929. name: "offerFarmReward",
  5930. args: {
  5931. offerId: reward.id
  5932. },
  5933. ident: "offerFarmReward_" + reward.id
  5934. });
  5935. }
  5936.  
  5937. return Send(JSON.stringify({ calls })).then(e => {
  5938. console.log(e);
  5939. setProgress(`${I18N('COLLECTED')} ${e?.results?.length} ${I18N('REWARD')}`, true);
  5940. });
  5941. });
  5942. }
  5943.  
  5944. /**
  5945. * Assemble Outland
  5946. *
  5947. * Собрать запределье
  5948. */
  5949. function getOutland() {
  5950. return new Promise(function (resolve, reject) {
  5951. send('{"calls":[{"name":"bossGetAll","args":{},"ident":"bossGetAll"}]}', e => {
  5952. let bosses = e.results[0].result.response;
  5953.  
  5954. let bossRaidOpenChestCall = {
  5955. calls: []
  5956. };
  5957.  
  5958. for (let boss of bosses) {
  5959. if (boss.mayRaid) {
  5960. bossRaidOpenChestCall.calls.push({
  5961. name: "bossRaid",
  5962. args: {
  5963. bossId: boss.id
  5964. },
  5965. ident: "bossRaid_" + boss.id
  5966. });
  5967. bossRaidOpenChestCall.calls.push({
  5968. name: "bossOpenChest",
  5969. args: {
  5970. bossId: boss.id,
  5971. amount: 1,
  5972. starmoney: 0
  5973. },
  5974. ident: "bossOpenChest_" + boss.id
  5975. });
  5976. } else if (boss.chestId == 1) {
  5977. bossRaidOpenChestCall.calls.push({
  5978. name: "bossOpenChest",
  5979. args: {
  5980. bossId: boss.id,
  5981. amount: 1,
  5982. starmoney: 0
  5983. },
  5984. ident: "bossOpenChest_" + boss.id
  5985. });
  5986. }
  5987. }
  5988.  
  5989. if (!bossRaidOpenChestCall.calls.length) {
  5990. setProgress(`${I18N('OUTLAND')} ${I18N('NOTHING_TO_COLLECT')}`, true);
  5991. resolve();
  5992. return;
  5993. }
  5994.  
  5995. send(JSON.stringify(bossRaidOpenChestCall), e => {
  5996. setProgress(`${I18N('OUTLAND')} ${I18N('COLLECTED')}`, true);
  5997. resolve();
  5998. });
  5999. });
  6000. });
  6001. }
  6002.  
  6003. /**
  6004. * Collect all rewards
  6005. *
  6006. * Собрать все награды
  6007. */
  6008. function questAllFarm() {
  6009. return new Promise(function (resolve, reject) {
  6010. let questGetAllCall = {
  6011. calls: [{
  6012. name: "questGetAll",
  6013. args: {},
  6014. ident: "body"
  6015. }]
  6016. }
  6017. send(JSON.stringify(questGetAllCall), function (data) {
  6018. let questGetAll = data.results[0].result.response;
  6019. const questAllFarmCall = {
  6020. calls: []
  6021. }
  6022. let number = 0;
  6023. for (let quest of questGetAll) {
  6024. if (quest.id < 1e6 && quest.state == 2) {
  6025. questAllFarmCall.calls.push({
  6026. name: "questFarm",
  6027. args: {
  6028. questId: quest.id
  6029. },
  6030. ident: `group_${number}_body`
  6031. });
  6032. number++;
  6033. }
  6034. }
  6035.  
  6036. if (!questAllFarmCall.calls.length) {
  6037. setProgress(`${I18N('COLLECTED')} ${number} ${I18N('REWARD')}`, true);
  6038. resolve();
  6039. return;
  6040. }
  6041.  
  6042. send(JSON.stringify(questAllFarmCall), function (res) {
  6043. console.log(res);
  6044. setProgress(`${I18N('COLLECTED')} ${number} ${I18N('REWARD')}`, true);
  6045. resolve();
  6046. });
  6047. });
  6048. })
  6049. }
  6050.  
  6051. /**
  6052. * Mission auto repeat
  6053. *
  6054. * Автоповтор миссии
  6055. * isStopSendMission = false;
  6056. * isSendsMission = true;
  6057. **/
  6058. this.sendsMission = async function (param) {
  6059. if (isStopSendMission) {
  6060. isSendsMission = false;
  6061. console.log(I18N('STOPPED'));
  6062. setProgress('');
  6063. await popup.confirm(`${I18N('STOPPED')}<br>${I18N('REPETITIONS')}: ${param.count}`, [{
  6064. msg: 'Ok',
  6065. result: true
  6066. }, ])
  6067. return;
  6068. }
  6069.  
  6070. let missionStartCall = {
  6071. "calls": [{
  6072. "name": "missionStart",
  6073. "args": lastMissionStart,
  6074. "ident": "body"
  6075. }]
  6076. }
  6077. /**
  6078. * Mission Request
  6079. *
  6080. * Запрос на выполнение мисии
  6081. */
  6082. SendRequest(JSON.stringify(missionStartCall), async e => {
  6083. if (e['error']) {
  6084. isSendsMission = false;
  6085. console.log(e['error']);
  6086. setProgress('');
  6087. let msg = e['error'].name + ' ' + e['error'].description + `<br>${I18N('REPETITIONS')}: ${param.count}`;
  6088. await popup.confirm(msg, [
  6089. {msg: 'Ok', result: true},
  6090. ])
  6091. return;
  6092. }
  6093. /**
  6094. * Mission data calculation
  6095. *
  6096. * Расчет данных мисии
  6097. */
  6098. BattleCalc(e.results[0].result.response, 'get_tower', async r => {
  6099.  
  6100. let missionEndCall = {
  6101. "calls": [{
  6102. "name": "missionEnd",
  6103. "args": {
  6104. "id": param.id,
  6105. "result": r.result,
  6106. "progress": r.progress
  6107. },
  6108. "ident": "body"
  6109. }]
  6110. }
  6111. /**
  6112. * Mission Completion Request
  6113. *
  6114. * Запрос на завершение миссии
  6115. */
  6116. SendRequest(JSON.stringify(missionEndCall), async (e) => {
  6117. if (e['error']) {
  6118. isSendsMission = false;
  6119. console.log(e['error']);
  6120. setProgress('');
  6121. let msg = e['error'].name + ' ' + e['error'].description + `<br>${I18N('REPETITIONS')}: ${param.count}`;
  6122. await popup.confirm(msg, [
  6123. {msg: 'Ok', result: true},
  6124. ])
  6125. return;
  6126. }
  6127. r = e.results[0].result.response;
  6128. if (r['error']) {
  6129. isSendsMission = false;
  6130. console.log(r['error']);
  6131. setProgress('');
  6132. await popup.confirm(`<br>${I18N('REPETITIONS')}: ${param.count}` + ' 3 ' + r['error'], [
  6133. {msg: 'Ok', result: true},
  6134. ])
  6135. return;
  6136. }
  6137.  
  6138. param.count++;
  6139. setProgress(`${I18N('MISSIONS_PASSED')}: ${param.count} (${I18N('STOP')})`, false, () => {
  6140. isStopSendMission = true;
  6141. });
  6142. setTimeout(sendsMission, 1, param);
  6143. });
  6144. })
  6145. });
  6146. }
  6147.  
  6148. /**
  6149. * Recursive opening of matryoshka dolls
  6150. *
  6151. * Рекурсивное открытие матрешек
  6152. */
  6153. function openRussianDoll(id, count, sum) {
  6154. sum = sum || 0;
  6155. sum += count;
  6156. send('{"calls":[{"name":"consumableUseLootBox","args":{"libId":'+id+',"amount":'+count+'},"ident":"body"}]}', e => {
  6157. setProgress(`${I18N('OPEN')} ${count}`, true);
  6158. let result = e.results[0].result.response;
  6159. let newCount = 0;
  6160. for(let n of result) {
  6161. if (n?.consumable && n.consumable[id]) {
  6162. newCount += n.consumable[id]
  6163. }
  6164. }
  6165. if (newCount) {
  6166. openRussianDoll(id, newCount, sum);
  6167. } else {
  6168. popup.confirm(`${I18N('TOTAL_OPEN')} ${sum}`);
  6169. }
  6170. })
  6171. }
  6172.  
  6173. /**
  6174. * Collect all mail, except letters with energy and charges of the portal
  6175. *
  6176. * Собрать всю почту, кроме писем с энергией и зарядами портала
  6177. */
  6178. function mailGetAll() {
  6179. const getMailInfo = '{"calls":[{"name":"mailGetAll","args":{},"ident":"body"}]}';
  6180.  
  6181. return Send(getMailInfo).then(dataMail => {
  6182. const letters = dataMail.results[0].result.response.letters;
  6183. const letterIds = lettersFilter(letters);
  6184. if (!letterIds.length) {
  6185. setProgress(I18N('NOTHING_TO_COLLECT'), true);
  6186. return;
  6187. }
  6188.  
  6189. const calls = [
  6190. { name: "mailFarm", args: { letterIds }, ident: "body" }
  6191. ];
  6192.  
  6193. return Send(JSON.stringify({ calls })).then(res => {
  6194. const lettersIds = res.results[0].result.response;
  6195. if (lettersIds) {
  6196. const countLetters = Object.keys(lettersIds).length;
  6197. setProgress(`${I18N('RECEIVED')} ${countLetters} ${I18N('LETTERS')}`, true);
  6198. }
  6199. });
  6200. });
  6201. }
  6202.  
  6203. /**
  6204. * Filters received emails
  6205. *
  6206. * Фильтрует получаемые письма
  6207. */
  6208. function lettersFilter(letters) {
  6209. const lettersIds = [];
  6210. for (let l in letters) {
  6211. letter = letters[l];
  6212. const reward = letter.reward;
  6213. /**
  6214. * Mail Collection Exceptions
  6215. *
  6216. * Исключения на сбор писем
  6217. */
  6218. const isFarmLetter = !(
  6219. /** Portals // сферы портала */
  6220. (reward?.refillable ? reward.refillable[45] : false) ||
  6221. /** Energy // энергия */
  6222. (reward?.stamina ? reward.stamina : false) ||
  6223. /** accelerating energy gain // ускорение набора энергии */
  6224. (reward?.buff ? true : false) ||
  6225. /** VIP Points // вип очки */
  6226. (reward?.vipPoints ? reward.vipPoints : false) ||
  6227. /** souls of heroes // душы героев */
  6228. (reward?.fragmentHero ? true : false) ||
  6229. /** heroes // герои */
  6230. (reward?.bundleHeroReward ? true : false)
  6231. );
  6232. if (isFarmLetter) {
  6233. lettersIds.push(~~letter.id);
  6234. }
  6235. }
  6236. return lettersIds;
  6237. }
  6238.  
  6239. /**
  6240. * Displaying information about the areas of the portal and attempts on the VG
  6241. *
  6242. * Отображение информации о сферах портала и попытках на ВГ
  6243. */
  6244. async function justInfo() {
  6245. return new Promise(async (resolve, reject) => {
  6246. const calls = [{
  6247. name: "userGetInfo",
  6248. args: {},
  6249. ident: "userGetInfo"
  6250. },
  6251. {
  6252. name: "clanWarGetInfo",
  6253. args: {},
  6254. ident: "clanWarGetInfo"
  6255. }];
  6256. const result = await Send(JSON.stringify({ calls }));
  6257. const infos = result.results;
  6258. const portalSphere = infos[0].result.response.refillable.find(n => n.id == 45);
  6259. const clanWarMyTries = infos[1].result.response?.myTries ?? 0;
  6260. const sanctuaryButton = buttons['goToSanctuary'].button;
  6261. const clanWarButton = buttons['goToClanWar'].button;
  6262. if (portalSphere.amount) {
  6263. sanctuaryButton.style.color = portalSphere.amount >= 3 ? 'red' : 'brown';
  6264. sanctuaryButton.title = `${I18N('SANCTUARY_TITLE')}\n${portalSphere.amount} ${I18N('PORTALS')}`;
  6265. } else {
  6266. sanctuaryButton.style.color = '';
  6267. sanctuaryButton.title = I18N('SANCTUARY_TITLE');
  6268. }
  6269. if (clanWarMyTries) {
  6270. clanWarButton.style.color = 'red';
  6271. clanWarButton.title = `${I18N('GUILD_WAR_TITLE')}\n${clanWarMyTries}${I18N('ATTEMPTS')}`;
  6272. } else {
  6273. clanWarButton.style.color = '';
  6274. clanWarButton.title = I18N('GUILD_WAR_TITLE');
  6275. }
  6276. setProgress('<img src="https://zingery.ru/heroes/portal.png" style="height: 25px;position: relative;top: 5px;"> ' + `${portalSphere.amount} </br> ${I18N('GUILD_WAR')}: ${clanWarMyTries}`, true);
  6277. resolve();
  6278. });
  6279. }
  6280.  
  6281. async function buyWithPetExperience() {
  6282. const itemLib = lib.getData('inventoryItem');
  6283. const result = await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"},{"name":"shopGet","args":{"shopId":"26"},"ident":"shopGet"}]}').then(e => e.results.map(n => n.result.response));
  6284. const inventory = result[0];
  6285. const shop = result[1];
  6286. const slot = shop.slots[2];
  6287.  
  6288. const currentCount = inventory.consumable[85];
  6289. const price = slot.cost.consumable[85];
  6290.  
  6291. const typeBuyItem = Object.keys(slot.reward).pop();
  6292. const itemIdBuyItem = Object.keys(slot.reward[typeBuyItem]).pop();
  6293. const countBuyItem = slot.reward[typeBuyItem][itemIdBuyItem];
  6294. const itemName = cheats.translate(`LIB_${typeBuyItem.toUpperCase()}_NAME_${itemIdBuyItem}`);
  6295.  
  6296. if (slot.bought) {
  6297. await popup.confirm(I18N('SECRET_WEALTH_ALREADY'), [
  6298. { msg: 'Ok', result: true },
  6299. ]);
  6300. return;
  6301. }
  6302.  
  6303. const purchaseMsg = I18N('SECRET_WEALTH_BUY', { available: currentCount, countBuy: countBuyItem, name: itemName, price })
  6304. const answer = await popup.confirm(purchaseMsg, [
  6305. { msg: I18N('BTN_NO'), result: false },
  6306. { msg: I18N('BTN_YES'), result: true },
  6307. ]);
  6308.  
  6309. if (!answer) {
  6310. setProgress(I18N('SECRET_WEALTH_CANCELED'), true);
  6311. return;
  6312. }
  6313.  
  6314. if (currentCount < price) {
  6315. const msg = I18N('SECRET_WEALTH_NOT_ENOUGH', { available: currentCount, need: price });
  6316. await popup.confirm(msg, [
  6317. { msg: 'Ok', result: true },
  6318. ]);
  6319. return;
  6320. }
  6321.  
  6322. const calls = [{
  6323. name: "shopBuy",
  6324. args: {
  6325. shopId: 26,
  6326. slot: 2,
  6327. cost: slot.cost,
  6328. reward: slot.reward
  6329. },
  6330. ident: "body"
  6331. }];
  6332. const bought = await Send(JSON.stringify({ calls })).then(e => e.results[0].result.response);
  6333.  
  6334. const type = Object.keys(bought).pop();
  6335. const itemId = Object.keys(bought[type]).pop();
  6336. const count = bought[type][itemId];
  6337. const resultMsg = I18N('SECRET_WEALTH_PURCHASED', { count, name: itemName });
  6338. await popup.confirm(resultMsg, [
  6339. { msg: 'Ok', result: true },
  6340. ]);
  6341. }
  6342.  
  6343. async function buyWithPetExperienceAuto() {
  6344. const itemLib = lib.getData('inventoryItem');
  6345. const minCount = 450551;
  6346. const result = await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"},{"name":"shopGet","args":{"shopId":"26"},"ident":"shopGet"}]}').then(e => e.results.map(n => n.result.response));
  6347. const inventory = result[0];
  6348. const shop = result[1];
  6349. const slot = shop.slots[2];
  6350.  
  6351. const currentCount = inventory.consumable[85];
  6352. const price = slot.cost.consumable[85];
  6353.  
  6354. if (slot.bought) {
  6355. console.log(I18N('SECRET_WEALTH_ALREADY'));
  6356. setProgress(I18N('SECRET_WEALTH_ALREADY'), true);
  6357. return;
  6358. }
  6359.  
  6360. if (currentCount < price) {
  6361. const msg = I18N('SECRET_WEALTH_NOT_ENOUGH', { available: currentCount, need: price });
  6362. console.log(msg);
  6363. setProgress(msg, true);
  6364. return;
  6365. }
  6366.  
  6367. if ((currentCount - price) < minCount) {
  6368. console.log(I18N('SECRET_WEALTH_UPGRADE_NEW_PET'));
  6369. setProgress(I18N('SECRET_WEALTH_UPGRADE_NEW_PET'), true);
  6370. return;
  6371. }
  6372.  
  6373. const calls = [{
  6374. name: "shopBuy",
  6375. args: {
  6376. shopId: 26,
  6377. slot: 2,
  6378. cost: slot.cost,
  6379. reward: slot.reward
  6380. },
  6381. ident: "body"
  6382. }];
  6383. const bought = await Send(JSON.stringify({ calls })).then(e => e.results[0].result.response);
  6384.  
  6385. const type = Object.keys(bought).pop();
  6386. const itemId = Object.keys(bought[type]).pop();
  6387. const count = bought[type][itemId];
  6388. const itemName = itemLib[type][itemId].label;
  6389. const resultMsg = I18N('SECRET_WEALTH_PURCHASED', { count, name: itemName });
  6390. console.log(resultMsg, bought);
  6391. setProgress(resultMsg, true);
  6392. }
  6393.  
  6394. async function getDailyBonus() {
  6395. const dailyBonusInfo = await Send(JSON.stringify({
  6396. calls: [{
  6397. name: "dailyBonusGetInfo",
  6398. args: {},
  6399. ident: "body"
  6400. }]
  6401. })).then(e => e.results[0].result.response);
  6402. const { availableToday, availableVip, currentDay } = dailyBonusInfo;
  6403.  
  6404. if (!availableToday) {
  6405. console.log('Уже собрано');
  6406. return;
  6407. }
  6408.  
  6409. const currentVipPoints = +userInfo.vipPoints;
  6410. const dailyBonusStat = lib.getData('dailyBonusStatic');
  6411. const vipInfo = lib.getData('level').vip;
  6412. let currentVipLevel = 0;
  6413. for (let i in vipInfo) {
  6414. vipLvl = vipInfo[i];
  6415. if (currentVipPoints >= vipLvl.vipPoints) {
  6416. currentVipLevel = vipLvl.level;
  6417. }
  6418. }
  6419. const vipLevelDouble = dailyBonusStat[`${currentDay}_0_0`].vipLevelDouble;
  6420.  
  6421. const calls = [{
  6422. name: "dailyBonusFarm",
  6423. args: {
  6424. vip: availableVip && currentVipLevel >= vipLevelDouble ? 1 : 0
  6425. },
  6426. ident: "body"
  6427. }];
  6428.  
  6429. const result = await Send(JSON.stringify({ calls }));
  6430. if (result.error) {
  6431. console.error(result.error);
  6432. return;
  6433. }
  6434.  
  6435. const reward = result.results[0].result.response;
  6436. const type = Object.keys(reward).pop();
  6437. const itemId = Object.keys(reward[type]).pop();
  6438. const count = reward[type][itemId];
  6439. const itemName = cheats.translate(`LIB_${type.toUpperCase()}_NAME_${itemId}`);
  6440.  
  6441. console.log(`Ежедневная награда: Получено ${count} ${itemName}`, reward);
  6442. }
  6443.  
  6444. async function farmStamina() {
  6445. const lootBox = await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"}]}')
  6446. .then(e => e.results[0].result.response.consumable[148]);
  6447.  
  6448. /** Добавить другие ящики */
  6449. if (!lootBox) {
  6450. setProgress(I18N('NO_BOXES'), true);
  6451. return;
  6452. }
  6453. const isOpening = await popup.confirm(I18N('OPEN_LOOTBOX', { lootBox }), [
  6454. { result: false, isClose: true },
  6455. { msg: I18N('BTN_YES'), result: true },
  6456. ]);
  6457.  
  6458. if (!isOpening) {
  6459. return;
  6460. }
  6461.  
  6462. for (let count = lootBox; count > 0; count--) {
  6463. const result = await Send('{"calls":[{"name":"consumableUseLootBox","args":{"libId":148,"amount":1},"ident":"body"}]}')
  6464. .then(e => e.results[0].result.response[0]);
  6465. if ('stamina' in result) {
  6466. setProgress(`${I18N('OPEN')}: ${lootBox - count}/${lootBox} ${I18N('STAMINA')} +${result.stamina}`, true);
  6467. console.log('stamina +' + result.stamina);
  6468. return;
  6469. } else {
  6470. setProgress(`${I18N('OPEN')}: ${lootBox - count}/${lootBox}`, false);
  6471. console.log(result);
  6472. }
  6473. }
  6474.  
  6475. setProgress(I18N('BOXES_OVER'), true);
  6476. }
  6477.  
  6478. async function fillActive() {
  6479. const data = await Send(JSON.stringify({
  6480. calls: [{
  6481. name: "questGetAll",
  6482. args: {},
  6483. ident: "questGetAll"
  6484. }, {
  6485. name: "inventoryGet",
  6486. args: {},
  6487. ident: "inventoryGet"
  6488. }, {
  6489. name: "clanGetInfo",
  6490. args: {},
  6491. ident: "clanGetInfo"
  6492. }
  6493. ]
  6494. })).then(e => e.results.map(n => n.result.response));
  6495.  
  6496. const quests = data[0];
  6497. const inv = data[1];
  6498. const stat = data[2].stat;
  6499. const maxActive = 2000 - stat.todayItemsActivity;
  6500. if (maxActive <= 0) {
  6501. setProgress(I18N('NO_MORE_ACTIVITY'), true);
  6502. return;
  6503. }
  6504. let countGetActive = 0;
  6505. const quest = quests.find(e => e.id > 10046 && e.id < 10051);
  6506. if (quest) {
  6507. countGetActive = 1750 - quest.progress;
  6508. }
  6509. if (countGetActive <= 0) {
  6510. countGetActive = maxActive;
  6511. }
  6512. console.log(countGetActive);
  6513.  
  6514. countGetActive = +(await popup.confirm(I18N('EXCHANGE_ITEMS', { maxActive }), [
  6515. { result: false, isClose: true },
  6516. { msg: I18N('GET_ACTIVITY'), isInput: true, default: countGetActive.toString() },
  6517. ]));
  6518.  
  6519. if (!countGetActive) {
  6520. return;
  6521. }
  6522.  
  6523. if (countGetActive > maxActive) {
  6524. countGetActive = maxActive;
  6525. }
  6526.  
  6527. const items = lib.getData('inventoryItem');
  6528.  
  6529. let itemsInfo = [];
  6530. for (let type of ['gear', 'scroll']) {
  6531. for (let i in inv[type]) {
  6532. const v = items[type][i]?.enchantValue || 0;
  6533. itemsInfo.push({
  6534. id: i,
  6535. count: inv[type][i],
  6536. v,
  6537. type
  6538. })
  6539. }
  6540. const invType = 'fragment' + type.toLowerCase().charAt(0).toUpperCase() + type.slice(1);
  6541. for (let i in inv[invType]) {
  6542. const v = items[type][i]?.fragmentEnchantValue || 0;
  6543. itemsInfo.push({
  6544. id: i,
  6545. count: inv[invType][i],
  6546. v,
  6547. type: invType
  6548. })
  6549. }
  6550. }
  6551. itemsInfo = itemsInfo.filter(e => e.v < 4 && e.count > 200);
  6552. itemsInfo = itemsInfo.sort((a, b) => b.count - a.count);
  6553. console.log(itemsInfo);
  6554. const activeItem = itemsInfo.shift();
  6555. console.log(activeItem);
  6556. const countItem = Math.ceil(countGetActive / activeItem.v);
  6557. if (countItem > activeItem.count) {
  6558. setProgress(I18N('NOT_ENOUGH_ITEMS'), true);
  6559. console.log(activeItem);
  6560. return;
  6561. }
  6562.  
  6563. await Send(JSON.stringify({
  6564. calls: [{
  6565. name: "clanItemsForActivity",
  6566. args: {
  6567. items: {
  6568. [activeItem.type]: {
  6569. [activeItem.id]: countItem
  6570. }
  6571. }
  6572. },
  6573. ident: "body"
  6574. }]
  6575. })).then(e => {
  6576. /** TODO: Вывести потраченые предметы */
  6577. console.log(e);
  6578. setProgress(`${I18N('ACTIVITY_RECEIVED')}: ` + e.results[0].result.response, true);
  6579. });
  6580. }
  6581.  
  6582. async function buyHeroFragments() {
  6583. const result = await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"},{"name":"shopGetAll","args":{},"ident":"shopGetAll"}]}')
  6584. .then(e => e.results.map(n => n.result.response));
  6585. const inv = result[0];
  6586. const shops = Object.values(result[1]).filter(shop => [4, 5, 6, 8, 9, 10, 17].includes(shop.id));
  6587. const calls = [];
  6588.  
  6589. for (let shop of shops) {
  6590. const slots = Object.values(shop.slots);
  6591. for (const slot of slots) {
  6592. /* Уже куплено */
  6593. if (slot.bought) {
  6594. continue;
  6595. }
  6596. /* Не душа героя */
  6597. if (!('fragmentHero' in slot.reward)) {
  6598. continue;
  6599. }
  6600. const coin = Object.keys(slot.cost).pop();
  6601. const coinId = Object.keys(slot.cost[coin]).pop();
  6602. const stock = inv[coin][coinId] || 0;
  6603. /* Не хватает на покупку */
  6604. if (slot.cost[coin][coinId] > stock) {
  6605. continue;
  6606. }
  6607. inv[coin][coinId] -= slot.cost[coin][coinId];
  6608. calls.push({
  6609. name: "shopBuy",
  6610. args: {
  6611. shopId: shop.id,
  6612. slot: slot.id,
  6613. cost: slot.cost,
  6614. reward: slot.reward,
  6615. },
  6616. ident: `shopBuy_${shop.id}_${slot.id}`,
  6617. })
  6618. }
  6619. }
  6620.  
  6621. if (!calls.length) {
  6622. setProgress(I18N('NO_PURCHASABLE_HERO_SOULS'), true);
  6623. return;
  6624. }
  6625.  
  6626. const bought = await Send(JSON.stringify({ calls })).then(e => e.results.map(n => n.result.response));
  6627. if (!bought) {
  6628. console.log('что-то пошло не так')
  6629. return;
  6630. }
  6631.  
  6632. let countHeroSouls = 0;
  6633. for (const buy of bought) {
  6634. countHeroSouls += +Object.values(Object.values(buy).pop()).pop();
  6635. }
  6636. console.log(countHeroSouls, bought, calls);
  6637. setProgress(I18N('PURCHASED_HERO_SOULS', { countHeroSouls }), true);
  6638. }
  6639.  
  6640. /** Открыть платные сундуки в Запределье за 90 */
  6641. async function bossOpenChestPay() {
  6642. const info = await Send('{"calls":[{"name":"userGetInfo","args":{},"ident":"userGetInfo"},{"name":"bossGetAll","args":{},"ident":"bossGetAll"}]}')
  6643. .then(e => e.results.map(n => n.result.response));
  6644.  
  6645. const user = info[0];
  6646. const boses = info[1];
  6647.  
  6648. const currentStarMoney = user.starMoney;
  6649. if (currentStarMoney < 540) {
  6650. setProgress(I18N('NOT_ENOUGH_EMERALDS_540', { currentStarMoney }), true);
  6651. return;
  6652. }
  6653.  
  6654. const calls = [];
  6655.  
  6656. let n = 0;
  6657. const amount = 1;
  6658. for (let boss of boses) {
  6659. const bossId = boss.id;
  6660. if (boss.chestNum != 2) {
  6661. continue;
  6662. }
  6663. for (const starmoney of [90, 90, 0]) {
  6664. calls.push({
  6665. name: "bossOpenChest",
  6666. args: {
  6667. bossId,
  6668. amount,
  6669. starmoney
  6670. },
  6671. ident: "bossOpenChest_" + (++n)
  6672. });
  6673. }
  6674. }
  6675.  
  6676. if (!calls.length) {
  6677. setProgress(I18N('CHESTS_NOT_AVAILABLE'), true);
  6678. return;
  6679. }
  6680.  
  6681. const result = await Send(JSON.stringify({ calls }));
  6682. console.log(result);
  6683. if (result?.results) {
  6684. setProgress(`${I18N('OUTLAND_CHESTS_RECEIVED')}: ` + result.results.length, true);
  6685. } else {
  6686. setProgress(I18N('CHESTS_NOT_AVAILABLE'), true);
  6687. }
  6688. }
  6689.  
  6690. async function autoRaidAdventure() {
  6691. const calls = [
  6692. {
  6693. name: "userGetInfo",
  6694. args: {},
  6695. ident: "userGetInfo"
  6696. },
  6697. {
  6698. name: "adventure_raidGetInfo",
  6699. args: {},
  6700. ident: "adventure_raidGetInfo"
  6701. }
  6702. ];
  6703. const result = await Send(JSON.stringify({ calls }))
  6704. .then(e => e.results.map(n => n.result.response));
  6705.  
  6706. const portalSphere = result[0].refillable.find(n => n.id == 45);
  6707. const adventureRaid = Object.entries(result[1].raid).filter(e => e[1]).pop()
  6708. const adventureId = adventureRaid ? adventureRaid[0] : 0;
  6709.  
  6710. if (!portalSphere.amount || !adventureId) {
  6711. setProgress(I18N('RAID_NOT_AVAILABLE'), true);
  6712. return;
  6713. }
  6714.  
  6715. const countRaid = +(await popup.confirm(I18N('RAID_ADVENTURE', { adventureId }), [
  6716. { result: false, isClose: true },
  6717. { msg: 'Рейд', isInput: true, default: portalSphere.amount },
  6718. ]));
  6719.  
  6720. if (!countRaid) {
  6721. return;
  6722. }
  6723.  
  6724. if (countRaid > portalSphere.amount) {
  6725. countRaid = portalSphere.amount;
  6726. }
  6727.  
  6728. const resultRaid = await Send(JSON.stringify({
  6729. calls: [...Array(countRaid)].map((e, i) => ({
  6730. name: "adventure_raid",
  6731. args: {
  6732. adventureId
  6733. },
  6734. ident: `body_${i}`
  6735. }))
  6736. })).then(e => e.results.map(n => n.result.response));
  6737.  
  6738. if (!resultRaid.length) {
  6739. console.log(resultRaid);
  6740. setProgress(I18N('SOMETHING_WENT_WRONG'), true);
  6741. return;
  6742. }
  6743.  
  6744. console.log(resultRaid, adventureId, portalSphere.amount);
  6745. setProgress(I18N('ADVENTURE_COMPLETED', { adventureId, times: resultRaid.length }), true);
  6746. }
  6747.  
  6748. /** Вывести всю клановую статистику в консоль браузера */
  6749. async function clanStatistic() {
  6750. const copy = function (text) {
  6751. const copyTextarea = document.createElement("textarea");
  6752. copyTextarea.style.opacity = "0";
  6753. copyTextarea.textContent = text;
  6754. document.body.appendChild(copyTextarea);
  6755. copyTextarea.select();
  6756. document.execCommand("copy");
  6757. document.body.removeChild(copyTextarea);
  6758. delete copyTextarea;
  6759. }
  6760. const calls = [
  6761. { name: "clanGetInfo", args: {}, ident: "clanGetInfo" },
  6762. { name: "clanGetWeeklyStat", args: {}, ident: "clanGetWeeklyStat" },
  6763. { name: "clanGetLog", args: {}, ident: "clanGetLog" },
  6764. ];
  6765.  
  6766. const result = await Send(JSON.stringify({ calls }));
  6767.  
  6768. const dataClanInfo = result.results[0].result.response;
  6769. const dataClanStat = result.results[1].result.response;
  6770. const dataClanLog = result.results[2].result.response;
  6771.  
  6772. const membersStat = {};
  6773. for (let i = 0; i < dataClanStat.stat.length; i++) {
  6774. membersStat[dataClanStat.stat[i].id] = dataClanStat.stat[i];
  6775. }
  6776.  
  6777. const joinStat = {};
  6778. historyLog = dataClanLog.history;
  6779. for (let j in historyLog) {
  6780. his = historyLog[j];
  6781. if (his.event == 'join') {
  6782. joinStat[his.userId] = his.ctime;
  6783. }
  6784. }
  6785.  
  6786. const infoArr = [];
  6787. const members = dataClanInfo.clan.members;
  6788. for (let n in members) {
  6789. var member = [
  6790. n,
  6791. members[n].name,
  6792. members[n].level,
  6793. dataClanInfo.clan.warriors.includes(+n) ? 1 : 0,
  6794. (new Date(members[n].lastLoginTime * 1000)).toLocaleString().replace(',', ''),
  6795. joinStat[n] ? (new Date(joinStat[n] * 1000)).toLocaleString().replace(',', '') : '',
  6796. membersStat[n].activity.reverse().join('\t'),
  6797. membersStat[n].adventureStat.reverse().join('\t'),
  6798. membersStat[n].clanGifts.reverse().join('\t'),
  6799. membersStat[n].clanWarStat.reverse().join('\t'),
  6800. membersStat[n].dungeonActivity.reverse().join('\t'),
  6801. ];
  6802. infoArr.push(member);
  6803. }
  6804. const info = infoArr.sort((a, b) => (b[2] - a[2])).map((e) => e.join('\t')).join('\n');
  6805. console.log(info);
  6806. copy(info);
  6807. setProgress(I18N('CLAN_STAT_COPY'), true);
  6808. }
  6809.  
  6810. async function buyInStoreForGold() {
  6811. const result = await Send('{"calls":[{"name":"shopGetAll","args":{},"ident":"body"},{"name":"userGetInfo","args":{},"ident":"userGetInfo"}]}').then(e => e.results.map(n => n.result.response));
  6812. const shops = result[0];
  6813. const user = result[1];
  6814. let gold = user.gold;
  6815. const calls = [];
  6816. if (shops[17]) {
  6817. const slots = shops[17].slots;
  6818. for (let i = 1; i <= 2; i++) {
  6819. if (!slots[i].bought) {
  6820. const costGold = slots[i].cost.gold;
  6821. if ((gold - costGold) < 0) {
  6822. continue;
  6823. }
  6824. gold -= costGold;
  6825. calls.push({
  6826. name: "shopBuy",
  6827. args: {
  6828. shopId: 17,
  6829. slot: i,
  6830. cost: slots[i].cost,
  6831. reward: slots[i].reward,
  6832. },
  6833. ident: 'body_' + i,
  6834. })
  6835. }
  6836. }
  6837. }
  6838. const slots = shops[1].slots;
  6839. for (let i = 4; i <= 6; i++) {
  6840. if (!slots[i].bought && slots[i]?.cost?.gold) {
  6841. const costGold = slots[i].cost.gold;
  6842. if ((gold - costGold) < 0) {
  6843. continue;
  6844. }
  6845. gold -= costGold;
  6846. calls.push({
  6847. name: "shopBuy",
  6848. args: {
  6849. shopId: 1,
  6850. slot: i,
  6851. cost: slots[i].cost,
  6852. reward: slots[i].reward,
  6853. },
  6854. ident: 'body_' + i,
  6855. })
  6856. }
  6857. }
  6858.  
  6859. if (!calls.length) {
  6860. setProgress(I18N('NOTHING_BUY'), true);
  6861. return;
  6862. }
  6863.  
  6864. const resultBuy = await Send(JSON.stringify({ calls })).then(e => e.results.map(n => n.result.response));
  6865. console.log(resultBuy);
  6866. const countBuy = resultBuy.length;
  6867. setProgress(I18N('LOTS_BOUGHT', { countBuy }), true);
  6868. }
  6869.  
  6870. function rewardsAndMailFarm() {
  6871. return new Promise(function (resolve, reject) {
  6872. let questGetAllCall = {
  6873. calls: [{
  6874. name: "questGetAll",
  6875. args: {},
  6876. ident: "questGetAll"
  6877. }, {
  6878. name: "mailGetAll",
  6879. args: {},
  6880. ident: "mailGetAll"
  6881. }]
  6882. }
  6883. send(JSON.stringify(questGetAllCall), function (data) {
  6884. if (!data) return;
  6885. let questGetAll = data.results[0].result.response.filter(e => e.state == 2);
  6886. const questBattlePass = lib.getData('quest').battlePass;
  6887. const questChainBPass = lib.getData('battlePass').questChain;
  6888.  
  6889. const questAllFarmCall = {
  6890. calls: []
  6891. }
  6892. let number = 0;
  6893. for (let quest of questGetAll) {
  6894. if (quest.id > 1e6) {
  6895. const questInfo = questBattlePass[quest.id];
  6896. const chain = questChainBPass[questInfo.chain];
  6897. if (chain.requirement?.battlePassTicket) {
  6898. continue;
  6899. }
  6900. }
  6901. questAllFarmCall.calls.push({
  6902. name: "questFarm",
  6903. args: {
  6904. questId: quest.id
  6905. },
  6906. ident: `questFarm_${number}`
  6907. });
  6908. number++;
  6909. }
  6910.  
  6911. let letters = data?.results[1]?.result?.response?.letters;
  6912. letterIds = lettersFilter(letters);
  6913.  
  6914. if (letterIds.length) {
  6915. questAllFarmCall.calls.push({
  6916. name: "mailFarm",
  6917. args: { letterIds },
  6918. ident: "mailFarm"
  6919. })
  6920. }
  6921.  
  6922. if (!questAllFarmCall.calls.length) {
  6923. setProgress(I18N('NOTHING_TO_COLLECT'), true);
  6924. resolve();
  6925. return;
  6926. }
  6927.  
  6928. send(JSON.stringify(questAllFarmCall), function (res) {
  6929. let reSend = false;
  6930. let countQuests = 0;
  6931. let countMail = 0;
  6932. for (let call of res.results) {
  6933. if (call.ident.includes('questFarm')) {
  6934. countQuests++;
  6935. } else {
  6936. countMail = Object.keys(call.result.response).length;
  6937. }
  6938.  
  6939. /** TODO: Переписать чтоб не вызывать функцию дважды */
  6940. const newQuests = call.result.newQuests;
  6941. if (newQuests) {
  6942. for (let quest of newQuests) {
  6943. if (quest.id < 1e6 && quest.state == 2) {
  6944. reSend = true;
  6945. }
  6946. }
  6947. }
  6948. }
  6949. setProgress(I18N('COLLECT_REWARDS_AND_MAIL', { countQuests, countMail }), true);
  6950. if (reSend) {
  6951. rewardsAndMailFarm()
  6952. }
  6953. resolve();
  6954. });
  6955. });
  6956. })
  6957. }
  6958.  
  6959. class epicBrawl {
  6960. timeout = null;
  6961. time = null;
  6962.  
  6963. constructor() {
  6964. if (epicBrawl.inst) {
  6965. return epicBrawl.inst;
  6966. }
  6967. epicBrawl.inst = this;
  6968. return this;
  6969. }
  6970.  
  6971. check() {
  6972. console.log(new Date(this.time))
  6973. if (Date.now() > this.time) {
  6974. this.timeout = null;
  6975. this.start()
  6976. return;
  6977. }
  6978. this.timeout = setTimeout(this.check, 6e4);
  6979. }
  6980.  
  6981. async start() {
  6982. if (this.timeout) {
  6983. console.log(new Date(this.time))
  6984. setProgress(I18N('TIMER_ALREADY'), 3000);
  6985. return;
  6986. }
  6987. setProgress(I18N('EPIC_BRAWL'), true);
  6988. 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));
  6989. const refill = teamInfo[2].refillable.find(n => n.id == 52)
  6990. this.time = (refill.lastRefill + 3600) * 1000
  6991. const attempts = refill.amount;
  6992. if (!attempts) {
  6993. console.log(new Date(this.time));
  6994. this.check();
  6995. setProgress(I18N('NO_ATTEMPTS_TIMER_START'), 3000);
  6996. return;
  6997. }
  6998.  
  6999. const args = {
  7000. heroes: teamInfo[0].epic_brawl.filter(e => e < 1000),
  7001. pet: teamInfo[0].epic_brawl.filter(e => e > 6000).pop(),
  7002. favor: teamInfo[1].epic_brawl,
  7003. }
  7004.  
  7005. let wins = 0;
  7006. let coins = 0;
  7007. let streak = { progress: 0, nextStage: 0 };
  7008. for (let i = attempts; i > 0; i--) {
  7009. const info = await Send(JSON.stringify({
  7010. calls: [
  7011. { name: "epicBrawl_getEnemy", args: {}, ident: "epicBrawl_getEnemy" }, { name: "epicBrawl_startBattle", args, ident: "epicBrawl_startBattle" }
  7012. ]
  7013. })).then(e => e.results.map(n => n.result.response));
  7014.  
  7015. const { progress, result } = await Calc(info[1].battle);
  7016. 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));
  7017.  
  7018. const resultInfo = endResult[0].result;
  7019. streak = endResult[1];
  7020.  
  7021. wins += resultInfo.win;
  7022. coins += resultInfo.reward ? resultInfo.reward.coin[39] : 0;
  7023.  
  7024. console.log(endResult[0].result)
  7025. if (endResult[1].progress == endResult[1].nextStage) {
  7026. const farm = await Send('{"calls":[{"name":"epicBrawl_farmWinStreak","args":{},"ident":"body"}]}').then(e => e.results[0].result.response);
  7027. coins += farm.coin[39];
  7028. }
  7029.  
  7030. setProgress(I18N('EPIC_BRAWL_RESULT', {
  7031. i, wins, attempts, coins,
  7032. progress: streak.progress,
  7033. nextStage: streak.nextStage,
  7034. end: '',
  7035. }), false, hideProgress);
  7036. }
  7037.  
  7038. console.log(new Date(this.time));
  7039. this.check();
  7040. setProgress(I18N('EPIC_BRAWL_RESULT', {
  7041. wins, attempts, coins,
  7042. i: '',
  7043. progress: streak.progress,
  7044. nextStage: streak.nextStage,
  7045. end: I18N('ATTEMPT_ENDED'),
  7046. }), false, hideProgress);
  7047. }
  7048. }
  7049.  
  7050. function Sleep(ms) {
  7051. return new Promise(resolve => setTimeout(resolve, ms));
  7052. }
  7053. function countdownTimer(seconds, message) {
  7054. message = message || I18N('TIMER');
  7055. const stopTimer = Date.now() + seconds * 1e3
  7056. return new Promise(resolve => {
  7057. const interval = setInterval(async () => {
  7058. const now = Date.now();
  7059. setProgress(`${message} ${((stopTimer - now) / 1000).toFixed(2)}`, false);
  7060. if (now > stopTimer) {
  7061. clearInterval(interval);
  7062. setProgress('', 1);
  7063. resolve();
  7064. }
  7065. }, 100);
  7066. });
  7067. }
  7068.  
  7069. /**
  7070. * Attack of the minions of Asgard
  7071. *
  7072. * Атака прислужников Асгарда
  7073. */
  7074. function testRaidNodes() {
  7075. return new Promise((resolve, reject) => {
  7076. const tower = new executeRaidNodes(resolve, reject);
  7077. tower.start();
  7078. });
  7079. }
  7080.  
  7081. /**
  7082. * Attack of the minions of Asgard
  7083. *
  7084. * Атака прислужников Асгарда
  7085. */
  7086. function executeRaidNodes(resolve, reject) {
  7087. let raidData = {
  7088. teams: [],
  7089. favor: {},
  7090. nodes: [],
  7091. attempts: 0,
  7092. countExecuteBattles: 0,
  7093. cancelBattle: 0,
  7094. }
  7095.  
  7096. callsExecuteRaidNodes = {
  7097. calls: [{
  7098. name: "clanRaid_getInfo",
  7099. args: {},
  7100. ident: "clanRaid_getInfo"
  7101. }, {
  7102. name: "teamGetAll",
  7103. args: {},
  7104. ident: "teamGetAll"
  7105. }, {
  7106. name: "teamGetFavor",
  7107. args: {},
  7108. ident: "teamGetFavor"
  7109. }]
  7110. }
  7111.  
  7112. this.start = function () {
  7113. send(JSON.stringify(callsExecuteRaidNodes), startRaidNodes);
  7114. }
  7115.  
  7116. function startRaidNodes(data) {
  7117. res = data.results;
  7118. clanRaidInfo = res[0].result.response;
  7119. teamGetAll = res[1].result.response;
  7120. teamGetFavor = res[2].result.response;
  7121.  
  7122. let index = 0;
  7123. for (let team of teamGetAll.clanRaid_nodes) {
  7124. raidData.teams.push({
  7125. data: {},
  7126. heroes: team.filter(id => id < 6000),
  7127. pet: team.filter(id => id >= 6000).pop(),
  7128. battleIndex: index++
  7129. });
  7130. }
  7131. raidData.favor = teamGetFavor.clanRaid_nodes;
  7132.  
  7133. raidData.nodes = clanRaidInfo.nodes;
  7134. raidData.attempts = clanRaidInfo.attempts;
  7135. isCancalBattle = false;
  7136.  
  7137. checkNodes();
  7138. }
  7139.  
  7140. function getAttackNode() {
  7141. for (let nodeId in raidData.nodes) {
  7142. let node = raidData.nodes[nodeId];
  7143. let points = 0
  7144. for (team of node.teams) {
  7145. points += team.points;
  7146. }
  7147. let now = Date.now() / 1000;
  7148. if (!points && now > node.timestamps.start && now < node.timestamps.end) {
  7149. let countTeam = node.teams.length;
  7150. delete raidData.nodes[nodeId];
  7151. return {
  7152. nodeId,
  7153. countTeam
  7154. };
  7155. }
  7156. }
  7157. return null;
  7158. }
  7159.  
  7160. function checkNodes() {
  7161. setProgress(`${I18N('REMAINING_ATTEMPTS')}: ${raidData.attempts}`);
  7162. let nodeInfo = getAttackNode();
  7163. if (nodeInfo && raidData.attempts) {
  7164. startNodeBattles(nodeInfo);
  7165. return;
  7166. }
  7167.  
  7168. endRaidNodes('EndRaidNodes');
  7169. }
  7170.  
  7171. function startNodeBattles(nodeInfo) {
  7172. let {nodeId, countTeam} = nodeInfo;
  7173. let teams = raidData.teams.slice(0, countTeam);
  7174. let heroes = raidData.teams.map(e => e.heroes).flat();
  7175. let favor = {...raidData.favor};
  7176. for (let heroId in favor) {
  7177. if (!heroes.includes(+heroId)) {
  7178. delete favor[heroId];
  7179. }
  7180. }
  7181.  
  7182. let calls = [{
  7183. name: "clanRaid_startNodeBattles",
  7184. args: {
  7185. nodeId,
  7186. teams,
  7187. favor
  7188. },
  7189. ident: "body"
  7190. }];
  7191.  
  7192. send(JSON.stringify({calls}), resultNodeBattles);
  7193. }
  7194.  
  7195. function resultNodeBattles(e) {
  7196. if (e['error']) {
  7197. endRaidNodes('nodeBattlesError', e['error']);
  7198. return;
  7199. }
  7200.  
  7201. console.log(e);
  7202. let battles = e.results[0].result.response.battles;
  7203. let promises = [];
  7204. let battleIndex = 0;
  7205. for (let battle of battles) {
  7206. battle.battleIndex = battleIndex++;
  7207. promises.push(calcBattleResult(battle));
  7208. }
  7209.  
  7210. Promise.all(promises)
  7211. .then(results => {
  7212. const endResults = {};
  7213. let isAllWin = true;
  7214. for (let r of results) {
  7215. isAllWin &&= r.result.win;
  7216. }
  7217. if (!isAllWin) {
  7218. cancelEndNodeBattle(results[0]);
  7219. return;
  7220. }
  7221. raidData.countExecuteBattles = results.length;
  7222. let timeout = 500;
  7223. for (let r of results) {
  7224. setTimeout(endNodeBattle, timeout, r);
  7225. timeout += 500;
  7226. }
  7227. });
  7228. }
  7229. /**
  7230. * Returns the battle calculation promise
  7231. *
  7232. * Возвращает промис расчета боя
  7233. */
  7234. function calcBattleResult(battleData) {
  7235. return new Promise(function (resolve, reject) {
  7236. BattleCalc(battleData, "get_clanPvp", resolve);
  7237. });
  7238. }
  7239. /**
  7240. * Cancels the fight
  7241. *
  7242. * Отменяет бой
  7243. */
  7244. function cancelEndNodeBattle(r) {
  7245. const fixBattle = function (heroes) {
  7246. for (const ids in heroes) {
  7247. hero = heroes[ids];
  7248. hero.energy = random(1, 999);
  7249. if (hero.hp > 0) {
  7250. hero.hp = random(1, hero.hp);
  7251. }
  7252. }
  7253. }
  7254. fixBattle(r.progress[0].attackers.heroes);
  7255. fixBattle(r.progress[0].defenders.heroes);
  7256. endNodeBattle(r);
  7257. }
  7258. /**
  7259. * Ends the fight
  7260. *
  7261. * Завершает бой
  7262. */
  7263. function endNodeBattle(r) {
  7264. let nodeId = r.battleData.result.nodeId;
  7265. let battleIndex = r.battleData.battleIndex;
  7266. let calls = [{
  7267. name: "clanRaid_endNodeBattle",
  7268. args: {
  7269. nodeId,
  7270. battleIndex,
  7271. result: r.result,
  7272. progress: r.progress
  7273. },
  7274. ident: "body"
  7275. }]
  7276.  
  7277. SendRequest(JSON.stringify({calls}), battleResult);
  7278. }
  7279. /**
  7280. * Processing the results of the battle
  7281. *
  7282. * Обработка результатов боя
  7283. */
  7284. function battleResult(e) {
  7285. if (e['error']) {
  7286. endRaidNodes('missionEndError', e['error']);
  7287. return;
  7288. }
  7289. r = e.results[0].result.response;
  7290. if (r['error']) {
  7291. if (r.reason == "invalidBattle") {
  7292. raidData.cancelBattle++;
  7293. checkNodes();
  7294. } else {
  7295. endRaidNodes('missionEndError', e['error']);
  7296. }
  7297. return;
  7298. }
  7299.  
  7300. if (!(--raidData.countExecuteBattles)) {
  7301. raidData.attempts--;
  7302. checkNodes();
  7303. }
  7304. }
  7305. /**
  7306. * Completing a task
  7307. *
  7308. * Завершение задачи
  7309. */
  7310. function endRaidNodes(reason, info) {
  7311. isCancalBattle = true;
  7312. let textCancel = raidData.cancelBattle ? ` ${I18N('BATTLES_CANCELED')}: ${raidData.cancelBattle}` : '';
  7313. setProgress(`${I18N('MINION_RAID')} ${I18N('COMPLETED')}! ${textCancel}`, true);
  7314. console.log(reason, info);
  7315. resolve();
  7316. }
  7317. }
  7318.  
  7319. /**
  7320. * Asgard Boss Attack Replay
  7321. *
  7322. * Повтор атаки босса Асгарда
  7323. */
  7324. function testBossBattle() {
  7325. return new Promise((resolve, reject) => {
  7326. const bossBattle = new executeBossBattle(resolve, reject);
  7327. bossBattle.start(lastBossBattle, lastBossBattleInfo);
  7328. });
  7329. }
  7330.  
  7331. /**
  7332. * Asgard Boss Attack Replay
  7333. *
  7334. * Повтор атаки босса Асгарда
  7335. */
  7336. function executeBossBattle(resolve, reject) {
  7337. let lastBossBattleArgs = {};
  7338. let reachDamage = 0;
  7339. let countBattle = 0;
  7340. let countMaxBattle = 10;
  7341. let lastDamage = 0;
  7342.  
  7343. this.start = function (battleArg, battleInfo) {
  7344. lastBossBattleArgs = battleArg;
  7345. preCalcBattle(battleInfo);
  7346. }
  7347.  
  7348. function getBattleInfo(battle) {
  7349. return new Promise(function (resolve) {
  7350. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  7351. BattleCalc(battle, getBattleType(battle.type), e => {
  7352. let extra = e.progress[0].defenders.heroes[1].extra;
  7353. resolve(extra.damageTaken + extra.damageTakenNextLevel);
  7354. });
  7355. });
  7356. }
  7357.  
  7358. function preCalcBattle(battle) {
  7359. let actions = [];
  7360. const countTestBattle = getInput('countTestBattle');
  7361. for (let i = 0; i < countTestBattle; i++) {
  7362. actions.push(getBattleInfo(battle, true));
  7363. }
  7364. Promise.all(actions)
  7365. .then(resultPreCalcBattle);
  7366. }
  7367.  
  7368. function fixDamage(damage) {
  7369. for (let i = 1e6; i > 1; i /= 10) {
  7370. if (damage > i) {
  7371. let n = i / 10;
  7372. damage = Math.ceil(damage / n) * n;
  7373. break;
  7374. }
  7375. }
  7376. return damage;
  7377. }
  7378.  
  7379. async function resultPreCalcBattle(damages) {
  7380. let maxDamage = 0;
  7381. let minDamage = 1e10;
  7382. let avgDamage = 0;
  7383. for (let damage of damages) {
  7384. avgDamage += damage
  7385. if (damage > maxDamage) {
  7386. maxDamage = damage;
  7387. }
  7388. if (damage < minDamage) {
  7389. minDamage = damage;
  7390. }
  7391. }
  7392. avgDamage /= damages.length;
  7393. console.log(damages.map(e => e.toLocaleString()).join('\n'), avgDamage, maxDamage);
  7394.  
  7395. reachDamage = fixDamage(avgDamage);
  7396. const result = await popup.confirm(
  7397. `${I18N('ROUND_STAT')} ${damages.length} ${I18N('BATTLE')}:` +
  7398. `<br>${I18N('MINIMUM')}: ` + minDamage.toLocaleString() +
  7399. `<br>${I18N('MAXIMUM')}: ` + maxDamage.toLocaleString() +
  7400. `<br>${I18N('AVERAGE')}: ` + avgDamage.toLocaleString()
  7401. /*+ '<br>Поиск урона больше чем ' + reachDamage.toLocaleString()*/
  7402. , [
  7403. { msg: I18N('BTN_OK'), result: 0},
  7404. /* {msg: 'Погнали', isInput: true, default: reachDamage}, */
  7405. ])
  7406. if (result) {
  7407. reachDamage = result;
  7408. isCancalBossBattle = false;
  7409. startBossBattle();
  7410. return;
  7411. }
  7412. endBossBattle(I18N('BTN_CANCEL'));
  7413. }
  7414.  
  7415. function startBossBattle() {
  7416. countBattle++;
  7417. countMaxBattle = getInput('countAutoBattle');
  7418. if (countBattle > countMaxBattle) {
  7419. setProgress('Превышен лимит попыток: ' + countMaxBattle, true);
  7420. endBossBattle('Превышен лимит попыток: ' + countMaxBattle);
  7421. return;
  7422. }
  7423. let calls = [{
  7424. name: "clanRaid_startBossBattle",
  7425. args: lastBossBattleArgs,
  7426. ident: "body"
  7427. }];
  7428. send(JSON.stringify({calls}), calcResultBattle);
  7429. }
  7430.  
  7431. function calcResultBattle(e) {
  7432. BattleCalc(e.results[0].result.response.battle, "get_clanPvp", resultBattle);
  7433. }
  7434.  
  7435. async function resultBattle(e) {
  7436. let extra = e.progress[0].defenders.heroes[1].extra
  7437. resultDamage = extra.damageTaken + extra.damageTakenNextLevel
  7438. console.log(resultDamage);
  7439. scriptMenu.setStatus(countBattle + ') ' + resultDamage.toLocaleString());
  7440. lastDamage = resultDamage;
  7441. if (resultDamage > reachDamage && await popup.confirm(countBattle + ') Урон ' + resultDamage.toLocaleString(), [
  7442. {msg: 'Ок', result: true},
  7443. {msg: 'Не пойдет', result: false},
  7444. ])) {
  7445. endBattle(e, false);
  7446. return;
  7447. }
  7448. cancelEndBattle(e);
  7449. }
  7450.  
  7451. function cancelEndBattle (r) {
  7452. const fixBattle = function (heroes) {
  7453. for (const ids in heroes) {
  7454. hero = heroes[ids];
  7455. hero.energy = random(1, 999);
  7456. if (hero.hp > 0) {
  7457. hero.hp = random(1, hero.hp);
  7458. }
  7459. }
  7460. }
  7461. fixBattle(r.progress[0].attackers.heroes);
  7462. fixBattle(r.progress[0].defenders.heroes);
  7463. endBattle(r, true);
  7464. }
  7465.  
  7466. function endBattle(battleResult, isCancal) {
  7467. let calls = [{
  7468. name: "clanRaid_endBossBattle",
  7469. args: {
  7470. result: battleResult.result,
  7471. progress: battleResult.progress
  7472. },
  7473. ident: "body"
  7474. }];
  7475.  
  7476. send(JSON.stringify({calls}), e => {
  7477. console.log(e);
  7478. if (isCancal) {
  7479. startBossBattle();
  7480. return;
  7481. }
  7482. scriptMenu.setStatus('Босс пробит нанесен урон: ' + lastDamage);
  7483. setTimeout(() => {
  7484. scriptMenu.setStatus('');
  7485. }, 5000);
  7486. endBossBattle('Узпех!');
  7487. });
  7488. }
  7489.  
  7490. /**
  7491. * Completing a task
  7492. *
  7493. * Завершение задачи
  7494. */
  7495. function endBossBattle(reason, info) {
  7496. isCancalBossBattle = true;
  7497. console.log(reason, info);
  7498. resolve();
  7499. }
  7500. }
  7501.  
  7502. /**
  7503. * Auto-repeat attack
  7504. *
  7505. * Автоповтор атаки
  7506. */
  7507. function testAutoBattle() {
  7508. return new Promise((resolve, reject) => {
  7509. const bossBattle = new executeAutoBattle(resolve, reject);
  7510. bossBattle.start(lastBattleArg, lastBattleInfo);
  7511. });
  7512. }
  7513.  
  7514. /**
  7515. * Auto-repeat attack
  7516. *
  7517. * Автоповтор атаки
  7518. */
  7519. function executeAutoBattle(resolve, reject) {
  7520. let battleArg = {};
  7521. let countBattle = 0;
  7522. let findCoeff = 0;
  7523.  
  7524. this.start = function (battleArgs, battleInfo) {
  7525. battleArg = battleArgs;
  7526. preCalcBattle(battleInfo);
  7527. }
  7528. /**
  7529. * Returns a promise for combat recalculation
  7530. *
  7531. * Возвращает промис для прерасчета боя
  7532. */
  7533. function getBattleInfo(battle) {
  7534. return new Promise(function (resolve) {
  7535. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  7536. Calc(battle).then(e => {
  7537. e.coeff = calcCoeff(e, 'defenders');
  7538. resolve(e);
  7539. });
  7540. });
  7541. }
  7542. /**
  7543. * Battle recalculation
  7544. *
  7545. * Прерасчет боя
  7546. */
  7547. function preCalcBattle(battle) {
  7548. let actions = [];
  7549. const countTestBattle = getInput('countTestBattle');
  7550. for (let i = 0; i < countTestBattle; i++) {
  7551. actions.push(getBattleInfo(battle));
  7552. }
  7553. Promise.all(actions)
  7554. .then(resultPreCalcBattle);
  7555. }
  7556. /**
  7557. * Processing the results of the battle recalculation
  7558. *
  7559. * Обработка результатов прерасчета боя
  7560. */
  7561. async function resultPreCalcBattle(results) {
  7562. let countWin = results.reduce((s, w) => w.result.win + s, 0);
  7563. setProgress(`${I18N('CHANCE_TO_WIN')} ${Math.floor(countWin / results.length * 100)}% (${results.length})`, true);
  7564. if (countWin > 0) {
  7565. isCancalBattle = false;
  7566. startBattle();
  7567. return;
  7568. }
  7569.  
  7570. let minCoeff = 100;
  7571. let maxCoeff = -100;
  7572. let avgCoeff = 0;
  7573. results.forEach(e => {
  7574. if (e.coeff < minCoeff) minCoeff = e.coeff;
  7575. if (e.coeff > maxCoeff) maxCoeff = e.coeff;
  7576. avgCoeff += e.coeff;
  7577. });
  7578. avgCoeff /= results.length;
  7579.  
  7580. const result = await popup.confirm(
  7581. I18N('VICTORY_IMPOSSIBLE') +
  7582. `<br>${I18N('ROUND_STAT')} ${results.length} ${I18N('BATTLE')}:` +
  7583. `<br>${I18N('MINIMUM')}: ` + minCoeff.toLocaleString() +
  7584. `<br>${I18N('MAXIMUM')}: ` + maxCoeff.toLocaleString() +
  7585. `<br>${I18N('AVERAGE')}: ` + avgCoeff.toLocaleString() +
  7586. `<br>${I18N('FIND_COEFF')} ` + avgCoeff.toLocaleString(), [
  7587. { msg: I18N('BTN_CANCEL'), result: 0 },
  7588. { msg: I18N('BTN_GO'), isInput: true, default: Math.round(avgCoeff * 1000) / 1000 },
  7589. ])
  7590. if (result) {
  7591. findCoeff = result;
  7592. isCancalBattle = false;
  7593. startBattle();
  7594. return;
  7595. }
  7596. setProgress(I18N('NOT_THIS_TIME'), true);
  7597. endAutoBattle(I18N('NOT_THIS_TIME'));
  7598. }
  7599.  
  7600. /**
  7601. * Calculation of the combat result coefficient
  7602. *
  7603. * Расчет коэфициента результата боя
  7604. */
  7605. function calcCoeff(result, packType) {
  7606. let beforeSumFactor = 0;
  7607. const beforePack = result.battleData[packType][0];
  7608. for (let heroId in beforePack) {
  7609. const hero = beforePack[heroId];
  7610. const state = hero.state;
  7611. let factor = 1;
  7612. if (state) {
  7613. const hp = state.hp / state.maxHp;
  7614. const energy = state.energy / 1e3;
  7615. factor = hp + energy / 20;
  7616. }
  7617. beforeSumFactor += factor;
  7618. }
  7619.  
  7620. let afterSumFactor = 0;
  7621. const afterPack = result.progress[0][packType].heroes;
  7622. for (let heroId in afterPack) {
  7623. const hero = afterPack[heroId];
  7624. const hp = hero.hp / beforePack[heroId].state.hp;
  7625. const energy = hero.energy / 1e3;
  7626. const factor = hp + energy / 20;
  7627. afterSumFactor += factor;
  7628. }
  7629. const resultCoeff = -(afterSumFactor - beforeSumFactor);
  7630. return Math.round(resultCoeff * 1000) / 1000;
  7631. }
  7632. /**
  7633. * Start battle
  7634. *
  7635. * Начало боя
  7636. */
  7637. function startBattle() {
  7638. countBattle++;
  7639. const countMaxBattle = getInput('countAutoBattle');
  7640. setProgress(countBattle + '/' + countMaxBattle);
  7641. if (countBattle > countMaxBattle) {
  7642. setProgress(`${I18N('RETRY_LIMIT_EXCEEDED')}: ${countMaxBattle}`, true);
  7643. endAutoBattle(`${I18N('RETRY_LIMIT_EXCEEDED')}: ${countMaxBattle}`)
  7644. return;
  7645. }
  7646. let calls = [{
  7647. name: nameFuncStartBattle,
  7648. args: battleArg,
  7649. ident: "body"
  7650. }];
  7651. send(JSON.stringify({
  7652. calls
  7653. }), calcResultBattle);
  7654. }
  7655. /**
  7656. * Battle calculation
  7657. *
  7658. * Расчет боя
  7659. */
  7660. function calcResultBattle(e) {
  7661. let battle = e.results[0].result.response.battle
  7662. BattleCalc(battle, getBattleType(battle.type), resultBattle);
  7663. }
  7664. /**
  7665. * Processing the results of the battle
  7666. *
  7667. * Обработка результатов боя
  7668. */
  7669. function resultBattle(e) {
  7670. const isWin = e.result.win;
  7671. console.log(isWin);
  7672. if (isWin) {
  7673. endBattle(e, false);
  7674. return;
  7675. }
  7676. if (findCoeff) {
  7677. const coeff = calcCoeff(e, 'defenders');
  7678. console.log(coeff);
  7679. setProgress(coeff, true);
  7680. if (coeff > findCoeff) {
  7681. endBattle(e, false);
  7682. return;
  7683. }
  7684. }
  7685. cancelEndBattle(e);
  7686. }
  7687. /**
  7688. * Cancel fight
  7689. *
  7690. * Отмена боя
  7691. */
  7692. function cancelEndBattle(r) {
  7693. const fixBattle = function (heroes) {
  7694. for (const ids in heroes) {
  7695. hero = heroes[ids];
  7696. hero.energy = random(1, 999);
  7697. if (hero.hp > 0) {
  7698. hero.hp = random(1, hero.hp);
  7699. }
  7700. }
  7701. }
  7702. fixBattle(r.progress[0].attackers.heroes);
  7703. fixBattle(r.progress[0].defenders.heroes);
  7704. endBattle(r, true);
  7705. }
  7706. /**
  7707. * End of the fight
  7708. *
  7709. * Завершение боя */
  7710. function endBattle(battleResult, isCancal) {
  7711. let calls = [{
  7712. name: nameFuncEndBattle,
  7713. args: {
  7714. result: battleResult.result,
  7715. progress: battleResult.progress
  7716. },
  7717. ident: "body"
  7718. }];
  7719.  
  7720. send(JSON.stringify({
  7721. calls
  7722. }), e => {
  7723. console.log(e);
  7724. if (isCancal) {
  7725. startBattle();
  7726. return;
  7727. }
  7728. scriptMenu.setStatus(`${I18N('SUCCESS')}!`);
  7729. setTimeout(() => {
  7730. scriptMenu.setStatus('');
  7731. }, 5000)
  7732. endAutoBattle(`${I18N('SUCCESS')}!`)
  7733. });
  7734. }
  7735. /**
  7736. * Completing a task
  7737. *
  7738. * Завершение задачи
  7739. */
  7740. function endAutoBattle(reason, info) {
  7741. isCancalBattle = true;
  7742. console.log(reason, info);
  7743. resolve();
  7744. }
  7745. }
  7746.  
  7747. function testDailyQuests() {
  7748. return new Promise((resolve, reject) => {
  7749. const quests = new dailyQuests(resolve, reject);
  7750. quests.init(questsInfo);
  7751. quests.start();
  7752. });
  7753. }
  7754.  
  7755. /**
  7756. * Automatic completion of daily quests
  7757. *
  7758. * Автоматическое выполнение ежедневных квестов
  7759. */
  7760. class dailyQuests {
  7761. /**
  7762. * Send(' {"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}').then(e => console.log(e))
  7763. * Send(' {"calls":[{"name":"heroGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  7764. * Send(' {"calls":[{"name":"titanGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  7765. * Send(' {"calls":[{"name":"inventoryGet","args":{},"ident":"body"}]}').then(e => console.log(e))
  7766. * Send(' {"calls":[{"name":"questGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  7767. * Send(' {"calls":[{"name":"bossGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  7768. */
  7769. callsList = [
  7770. "userGetInfo",
  7771. "heroGetAll",
  7772. "titanGetAll",
  7773. "inventoryGet",
  7774. "questGetAll",
  7775. "bossGetAll",
  7776. ]
  7777.  
  7778. dataQuests = {
  7779. 10001: {
  7780. description: 'Улучши умения героев 3 раза', // ++++++++++++++++
  7781. doItCall: () => {
  7782. const upgradeSkills = this.getUpgradeSkills();
  7783. return upgradeSkills.map(({ heroId, skill }, index) => ({ name: "heroUpgradeSkill", args: { heroId, skill }, "ident": `heroUpgradeSkill_${index}` }));
  7784. },
  7785. isWeCanDo: () => {
  7786. const upgradeSkills = this.getUpgradeSkills();
  7787. let sumGold = 0;
  7788. for (const skill of upgradeSkills) {
  7789. sumGold += this.skillCost(skill.value);
  7790. if (!skill.heroId) {
  7791. return false;
  7792. }
  7793. }
  7794. return this.questInfo['userGetInfo'].gold > sumGold;
  7795. },
  7796. },
  7797. 10002: {
  7798. description: 'Пройди 10 миссий', // --------------
  7799. isWeCanDo: () => false,
  7800. },
  7801. 10003: {
  7802. description: 'Пройди 3 героические миссии', // --------------
  7803. isWeCanDo: () => false,
  7804. },
  7805. 10004: {
  7806. description: 'Сразись 3 раза на Арене или Гранд Арене', // --------------
  7807. isWeCanDo: () => false,
  7808. },
  7809. 10006: {
  7810. description: 'Используй обмен изумрудов 1 раз', // ++++++++++++++++
  7811. doItCall: () => [{
  7812. name: "refillableAlchemyUse",
  7813. args: { multi: false },
  7814. ident: "refillableAlchemyUse"
  7815. }],
  7816. isWeCanDo: () => {
  7817. const starMoney = this.questInfo['userGetInfo'].starMoney;
  7818. return starMoney >= 20;
  7819. },
  7820. },
  7821. 10007: {
  7822. description: 'Соверши 1 призыв в Атриуме Душ', // ++++++++++++++++
  7823. doItCall: () => [{ name: "gacha_open", args: { ident: "heroGacha", free: true, pack: false }, ident: "gacha_open" }],
  7824. isWeCanDo: () => {
  7825. const soulCrystal = this.questInfo['inventoryGet'].coin[38];
  7826. return soulCrystal > 0;
  7827. },
  7828. },
  7829. 10016: {
  7830. description: 'Отправь подарки согильдийцам', // ++++++++++++++++
  7831. doItCall: () => [{ name: "clanSendDailyGifts", args: {}, ident: "clanSendDailyGifts" }],
  7832. isWeCanDo: () => true,
  7833. },
  7834. 10018: {
  7835. description: 'Используй зелье опыта', // ++++++++++++++++
  7836. doItCall: () => {
  7837. const expHero = this.getExpHero();
  7838. return [{
  7839. name: "consumableUseHeroXp",
  7840. args: {
  7841. heroId: expHero.heroId,
  7842. libId: expHero.libId,
  7843. amount: 1
  7844. },
  7845. ident: "consumableUseHeroXp"
  7846. }];
  7847. },
  7848. isWeCanDo: () => {
  7849. const expHero = this.getExpHero();
  7850. return expHero.heroId && expHero.libId;
  7851. },
  7852. },
  7853. 10019: {
  7854. description: 'Открой 1 сундук в Башне',
  7855. doItFunc: testTower,
  7856. isWeCanDo: () => false,
  7857. },
  7858. 10020: {
  7859. description: 'Открой 3 сундука в Запределье', // Готово
  7860. doItCall: () => {
  7861. return this.getOutlandChest();
  7862. },
  7863. isWeCanDo: () => {
  7864. const outlandChest = this.getOutlandChest();
  7865. return outlandChest.length > 0;
  7866. },
  7867. },
  7868. 10021: {
  7869. description: 'Собери 75 Титанита в Подземелье Гильдии',
  7870. isWeCanDo: () => false,
  7871. },
  7872. 10022: {
  7873. description: 'Собери 150 Титанита в Подземелье Гильдии',
  7874. doItFunc: testDungeon,
  7875. isWeCanDo: () => false,
  7876. },
  7877. 10023: {
  7878. description: 'Прокачай Дар Стихий на 1 уровень', // Готово
  7879. doItCall: () => {
  7880. const heroId = this.getHeroIdTitanGift();
  7881. return [
  7882. { name: "heroTitanGiftLevelUp", args: { heroId }, ident: "heroTitanGiftLevelUp" },
  7883. { name: "heroTitanGiftDrop", args: { heroId }, ident: "heroTitanGiftDrop" }
  7884. ]
  7885. },
  7886. isWeCanDo: () => {
  7887. const heroId = this.getHeroIdTitanGift();
  7888. return heroId;
  7889. },
  7890. },
  7891. 10024: {
  7892. description: 'Повысь уровень любого артефакта один раз', // Готово
  7893. doItCall: () => {
  7894. const upArtifact = this.getUpgradeArtifact();
  7895. return [
  7896. {
  7897. name: "heroArtifactLevelUp",
  7898. args: {
  7899. heroId: upArtifact.heroId,
  7900. slotId: upArtifact.slotId
  7901. },
  7902. ident: `heroArtifactLevelUp`
  7903. }
  7904. ];
  7905. },
  7906. isWeCanDo: () => {
  7907. const upgradeArtifact = this.getUpgradeArtifact();
  7908. return upgradeArtifact.heroId;
  7909. },
  7910. },
  7911. 10025: {
  7912. description: 'Начни 1 Экспедицию',
  7913. doItFunc: checkExpedition,
  7914. isWeCanDo: () => false,
  7915. },
  7916. 10026: {
  7917. description: 'Начни 4 Экспедиции', // --------------
  7918. doItFunc: checkExpedition,
  7919. isWeCanDo: () => false,
  7920. },
  7921. 10027: {
  7922. description: 'Победи в 1 бою Турнира Стихий',
  7923. doItFunc: testTitanArena,
  7924. isWeCanDo: () => false,
  7925. },
  7926. 10028: {
  7927. description: 'Повысь уровень любого артефакта титанов', // Готово
  7928. doItCall: () => {
  7929. const upTitanArtifact = this.getUpgradeTitanArtifact();
  7930. return [
  7931. {
  7932. name: "titanArtifactLevelUp",
  7933. args: {
  7934. titanId: upTitanArtifact.titanId,
  7935. slotId: upTitanArtifact.slotId
  7936. },
  7937. ident: `titanArtifactLevelUp`
  7938. }
  7939. ];
  7940. },
  7941. isWeCanDo: () => {
  7942. const upgradeTitanArtifact = this.getUpgradeTitanArtifact();
  7943. return upgradeTitanArtifact.titanId;
  7944. },
  7945. },
  7946. 10029: {
  7947. description: 'Открой сферу артефактов титанов', // ++++++++++++++++
  7948. doItCall: () => [{ name: "titanArtifactChestOpen", args: { amount: 1, free: true }, ident: "titanArtifactChestOpen" }],
  7949. isWeCanDo: () => {
  7950. return this.questInfo['inventoryGet']?.consumable[55] > 0
  7951. },
  7952. },
  7953. 10030: {
  7954. description: 'Улучши облик любого героя 1 раз', // Готово
  7955. doItCall: () => {
  7956. const upSkin = this.getUpgradeSkin();
  7957. return [
  7958. {
  7959. name: "heroSkinUpgrade",
  7960. args: {
  7961. heroId: upSkin.heroId,
  7962. skinId: upSkin.skinId
  7963. },
  7964. ident: `heroSkinUpgrade`
  7965. }
  7966. ];
  7967. },
  7968. isWeCanDo: () => {
  7969. const upgradeSkin = this.getUpgradeSkin();
  7970. return upgradeSkin.heroId;
  7971. },
  7972. },
  7973. 10031: {
  7974. description: 'Победи в 6 боях Турнира Стихий', // --------------
  7975. doItFunc: testTitanArena,
  7976. isWeCanDo: () => false,
  7977. },
  7978. 10043: {
  7979. description: 'Начни или присоеденись к Приключению', // --------------
  7980. isWeCanDo: () => false,
  7981. },
  7982. 10044: {
  7983. description: 'Воспользуйся призывом питомцев 1 раз', // ++++++++++++++++
  7984. doItCall: () => [{ name: "pet_chestOpen", args: { amount: 1, paid: false }, ident: "pet_chestOpen" }],
  7985. isWeCanDo: () => {
  7986. return this.questInfo['inventoryGet']?.consumable[90] > 0
  7987. },
  7988. },
  7989. 10046: {
  7990. /**
  7991. * TODO: Watch Adventure
  7992. * TODO: Смотреть приключение
  7993. */
  7994. description: 'Открой 3 сундука в Приключениях',
  7995. isWeCanDo: () => false,
  7996. },
  7997. 10047: {
  7998. description: 'Набери 150 очков активности в Гильдии', // Готово
  7999. doItCall: () => {
  8000. const enchantRune = this.getEnchantRune();
  8001. return [
  8002. {
  8003. name: "heroEnchantRune",
  8004. args: {
  8005. heroId: enchantRune.heroId,
  8006. tier: enchantRune.tier,
  8007. items: {
  8008. consumable: { [enchantRune.itemId]: 1 }
  8009. }
  8010. },
  8011. ident: `heroEnchantRune`
  8012. }
  8013. ];
  8014. },
  8015. isWeCanDo: () => {
  8016. const userInfo = this.questInfo['userGetInfo'];
  8017. const enchantRune = this.getEnchantRune();
  8018. return enchantRune.heroId && userInfo.gold > 1e3;
  8019. },
  8020. },
  8021. };
  8022.  
  8023. constructor(resolve, reject, questInfo) {
  8024. this.resolve = resolve;
  8025. this.reject = reject;
  8026. }
  8027.  
  8028. init(questInfo) {
  8029. this.questInfo = questInfo;
  8030. this.isAuto = false;
  8031. }
  8032.  
  8033. async autoInit(isAuto) {
  8034. this.isAuto = isAuto || false;
  8035. const quests = {};
  8036. const calls = this.callsList.map(name => ({
  8037. name, args: {}, ident: name
  8038. }))
  8039. const result = await Send(JSON.stringify({ calls })).then(e => e.results);
  8040. for (const call of result) {
  8041. quests[call.ident] = call.result.response;
  8042. }
  8043. this.questInfo = quests;
  8044. }
  8045.  
  8046. async start() {
  8047. /**
  8048. * TODO may not be needed
  8049. *
  8050. * TODO возожно не нужна
  8051. */
  8052. let countQuest = 0;
  8053. const weCanDo = [];
  8054. const selectedActions = getSaveVal('selectedActions', {});
  8055. for (let quest of this.questInfo['questGetAll']) {
  8056. if (quest.id in this.dataQuests && quest.state == 1) {
  8057. if (!selectedActions[quest.id]) {
  8058. selectedActions[quest.id] = {
  8059. checked: false
  8060. }
  8061. }
  8062.  
  8063. const isWeCanDo = this.dataQuests[quest.id].isWeCanDo;
  8064. if (!isWeCanDo.call(this)) {
  8065. continue;
  8066. }
  8067.  
  8068. weCanDo.push({
  8069. name: quest.id,
  8070. label: I18N(`QUEST_${quest.id}`),
  8071. checked: selectedActions[quest.id].checked
  8072. });
  8073. countQuest++;
  8074. }
  8075. }
  8076.  
  8077. if (!weCanDo.length) {
  8078. this.end(I18N('NOTHING_TO_DO'));
  8079. return;
  8080. }
  8081.  
  8082. console.log(weCanDo);
  8083. let taskList = [];
  8084. if (this.isAuto) {
  8085. taskList = weCanDo;
  8086. } else {
  8087. const answer = await popup.confirm(`${I18N('YOU_CAN_COMPLETE') }:`, [
  8088. { msg: I18N('BTN_DO_IT'), result: true },
  8089. { msg: I18N('BTN_CANCEL'), result: false },
  8090. ], weCanDo);
  8091. if (!answer) {
  8092. this.end('');
  8093. return;
  8094. }
  8095. taskList = popup.getCheckBoxes();
  8096. taskList.forEach(e => {
  8097. selectedActions[e.name].checked = e.checked;
  8098. });
  8099. setSaveVal('selectedActions', selectedActions);
  8100. }
  8101.  
  8102. const calls = [];
  8103. let countChecked = 0;
  8104. for (const task of taskList) {
  8105. if (task.checked) {
  8106. countChecked++;
  8107. const quest = this.dataQuests[task.name]
  8108. console.log(quest.description);
  8109.  
  8110. if (quest.doItCall) {
  8111. const doItCall = quest.doItCall.call(this);
  8112. calls.push(...doItCall);
  8113. }
  8114. }
  8115. }
  8116.  
  8117. if (!countChecked) {
  8118. this.end(I18N('NOT_QUEST_COMPLETED'));
  8119. return;
  8120. }
  8121.  
  8122. const result = await Send(JSON.stringify({ calls }));
  8123. if (result.error) {
  8124. console.error(result.error, result.error.call)
  8125. }
  8126. this.end(`${I18N('COMPLETED_QUESTS')}: ${countChecked}`);
  8127. }
  8128.  
  8129. errorHandling(error) {
  8130. //console.error(error);
  8131. let errorInfo = error.toString() + '\n';
  8132. try {
  8133. const errorStack = error.stack.split('\n');
  8134. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testDoYourBest");
  8135. errorInfo += errorStack.slice(0, endStack).join('\n');
  8136. } catch (e) {
  8137. errorInfo += error.stack;
  8138. }
  8139. copyText(errorInfo);
  8140. }
  8141.  
  8142. skillCost(lvl) {
  8143. return 573 * lvl ** 0.9 + lvl ** 2.379;
  8144. }
  8145.  
  8146. getUpgradeSkills() {
  8147. const heroes = Object.values(this.questInfo['heroGetAll']);
  8148. const upgradeSkills = [
  8149. { heroId: 0, slotId: 0, value: 130 },
  8150. { heroId: 0, slotId: 0, value: 130 },
  8151. { heroId: 0, slotId: 0, value: 130 },
  8152. ];
  8153. const skillLib = lib.getData('skill');
  8154. /**
  8155. * color - 1 (белый) открывает 1 навык
  8156. * color - 2 (зеленый) открывает 2 навык
  8157. * color - 4 (синий) открывает 3 навык
  8158. * color - 7 (фиолетовый) открывает 4 навык
  8159. */
  8160. const colors = [1, 2, 4, 7];
  8161. for (const hero of heroes) {
  8162. const level = hero.level;
  8163. const color = hero.color;
  8164. for (let skillId in hero.skills) {
  8165. const tier = skillLib[skillId].tier;
  8166. const sVal = hero.skills[skillId];
  8167. if (color < colors[tier] || tier < 1 || tier > 4) {
  8168. continue;
  8169. }
  8170. for (let upSkill of upgradeSkills) {
  8171. if (sVal < upSkill.value && sVal < level) {
  8172. upSkill.value = sVal;
  8173. upSkill.heroId = hero.id;
  8174. upSkill.skill = tier;
  8175. break;
  8176. }
  8177. }
  8178. }
  8179. }
  8180. return upgradeSkills;
  8181. }
  8182.  
  8183. getUpgradeArtifact() {
  8184. const heroes = Object.values(this.questInfo['heroGetAll']);
  8185. const inventory = this.questInfo['inventoryGet'];
  8186. const upArt = { heroId: 0, slotId: 0, level: 100 };
  8187.  
  8188. const heroLib = lib.getData('hero');
  8189. const artifactLib = lib.getData('artifact');
  8190.  
  8191. for (const hero of heroes) {
  8192. const heroInfo = heroLib[hero.id];
  8193. const level = hero.level
  8194. if (level < 20) {
  8195. continue;
  8196. }
  8197.  
  8198. for (let slotId in hero.artifacts) {
  8199. const art = hero.artifacts[slotId];
  8200. /* Текущая звезданость арта */
  8201. const star = art.star;
  8202. if (!star) {
  8203. continue;
  8204. }
  8205. /* Текущий уровень арта */
  8206. const level = art.level;
  8207. if (level >= 100) {
  8208. continue;
  8209. }
  8210. /* Идентификатор арта в библиотеке */
  8211. const artifactId = heroInfo.artifacts[slotId];
  8212. const artInfo = artifactLib.id[artifactId];
  8213. const costNextLevel = artifactLib.type[artInfo.type].levels[level + 1].cost;
  8214.  
  8215. const costСurrency = Object.keys(costNextLevel).pop();
  8216. const costValues = Object.entries(costNextLevel[costСurrency]).pop();
  8217. const costId = costValues[0];
  8218. const costValue = +costValues[1];
  8219.  
  8220. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  8221. if (level < upArt.level && inventory[costСurrency][costId] >= costValue) {
  8222. upArt.level = level;
  8223. upArt.heroId = hero.id;
  8224. upArt.slotId = slotId;
  8225. }
  8226. }
  8227. }
  8228. return upArt;
  8229. }
  8230.  
  8231. getUpgradeSkin() {
  8232. const heroes = Object.values(this.questInfo['heroGetAll']);
  8233. const inventory = this.questInfo['inventoryGet'];
  8234. const upSkin = { heroId: 0, skinId: 0, level: 60, cost: 1500 };
  8235.  
  8236. const skinLib = lib.getData('skin');
  8237.  
  8238. for (const hero of heroes) {
  8239. const level = hero.level
  8240. if (level < 20) {
  8241. continue;
  8242. }
  8243.  
  8244. for (let skinId in hero.skins) {
  8245. /* Текущий уровень скина */
  8246. const level = hero.skins[skinId];
  8247. if (level >= 60) {
  8248. continue;
  8249. }
  8250. /* Идентификатор скина в библиотеке */
  8251. const skinInfo = skinLib[skinId];
  8252. const costNextLevel = skinInfo.statData.levels[level + 1].cost;
  8253.  
  8254. const costСurrency = Object.keys(costNextLevel).pop();
  8255. const costСurrencyId = Object.keys(costNextLevel[costСurrency]).pop();
  8256. const costValue = +costNextLevel[costСurrency][costСurrencyId];
  8257.  
  8258. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  8259. if (level < upSkin.level &&
  8260. costValue < upSkin.cost &&
  8261. inventory[costСurrency][costСurrencyId] >= costValue) {
  8262. upSkin.cost = costValue;
  8263. upSkin.level = level;
  8264. upSkin.heroId = hero.id;
  8265. upSkin.skinId = skinId;
  8266. }
  8267. }
  8268. }
  8269. return upSkin;
  8270. }
  8271.  
  8272. getUpgradeTitanArtifact() {
  8273. const titans = Object.values(this.questInfo['titanGetAll']);
  8274. const inventory = this.questInfo['inventoryGet'];
  8275. const userInfo = this.questInfo['userGetInfo'];
  8276. const upArt = { titanId: 0, slotId: 0, level: 120 };
  8277.  
  8278. const titanLib = lib.getData('titan');
  8279. const artTitanLib = lib.getData('titanArtifact');
  8280.  
  8281. for (const titan of titans) {
  8282. const titanInfo = titanLib[titan.id];
  8283. // const level = titan.level
  8284. // if (level < 20) {
  8285. // continue;
  8286. // }
  8287.  
  8288. for (let slotId in titan.artifacts) {
  8289. const art = titan.artifacts[slotId];
  8290. /* Текущая звезданость арта */
  8291. const star = art.star;
  8292. if (!star) {
  8293. continue;
  8294. }
  8295. /* Текущий уровень арта */
  8296. const level = art.level;
  8297. if (level >= 120) {
  8298. continue;
  8299. }
  8300. /* Идентификатор арта в библиотеке */
  8301. const artifactId = titanInfo.artifacts[slotId];
  8302. const artInfo = artTitanLib.id[artifactId];
  8303. const costNextLevel = artTitanLib.type[artInfo.type].levels[level + 1].cost;
  8304.  
  8305. const costСurrency = Object.keys(costNextLevel).pop();
  8306. let costValue = 0;
  8307. let currentValue = 0;
  8308. if (costСurrency == 'gold') {
  8309. costValue = costNextLevel[costСurrency];
  8310. currentValue = userInfo.gold;
  8311. } else {
  8312. const costValues = Object.entries(costNextLevel[costСurrency]).pop();
  8313. const costId = costValues[0];
  8314. costValue = +costValues[1];
  8315. currentValue = inventory[costСurrency][costId];
  8316. }
  8317.  
  8318. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  8319. if (level < upArt.level && currentValue >= costValue) {
  8320. upArt.level = level;
  8321. upArt.titanId = titan.id;
  8322. upArt.slotId = slotId;
  8323. break;
  8324. }
  8325. }
  8326. }
  8327. return upArt;
  8328. }
  8329.  
  8330. getEnchantRune() {
  8331. const heroes = Object.values(this.questInfo['heroGetAll']);
  8332. const inventory = this.questInfo['inventoryGet'];
  8333. const enchRune = { heroId: 0, tier: 0, exp: 43750, itemId: 0 };
  8334. for (let i = 1; i <= 4; i++) {
  8335. if (inventory.consumable[i] > 0) {
  8336. enchRune.itemId = i;
  8337. break;
  8338. }
  8339. return enchRune;
  8340. }
  8341.  
  8342. const runeLib = lib.getData('rune');
  8343. const runeLvls = Object.values(runeLib.level);
  8344. /**
  8345. * color - 4 (синий) открывает 1 и 2 символ
  8346. * color - 7 (фиолетовый) открывает 3 символ
  8347. * color - 8 (фиолетовый +1) открывает 4 символ
  8348. * color - 9 (фиолетовый +2) открывает 5 символ
  8349. */
  8350. // TODO: кажется надо учесть уровень команды
  8351. const colors = [4, 4, 7, 8, 9];
  8352. for (const hero of heroes) {
  8353. const color = hero.color;
  8354.  
  8355.  
  8356. for (let runeTier in hero.runes) {
  8357. /* Проверка на доступность руны */
  8358. if (color < colors[runeTier]) {
  8359. continue;
  8360. }
  8361. /* Текущий опыт руны */
  8362. const exp = hero.runes[runeTier];
  8363. if (exp >= 43750) {
  8364. continue;
  8365. }
  8366.  
  8367. let level = 0;
  8368. if (exp) {
  8369. for (let lvl of runeLvls) {
  8370. if (exp >= lvl.enchantValue) {
  8371. level = lvl.level;
  8372. } else {
  8373. break;
  8374. }
  8375. }
  8376. }
  8377. /** Уровень героя необходимый для уровня руны */
  8378. const heroLevel = runeLib.level[level].heroLevel;
  8379. if (hero.level < heroLevel) {
  8380. continue;
  8381. }
  8382.  
  8383. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  8384. if (exp < enchRune.exp) {
  8385. enchRune.exp = exp;
  8386. enchRune.heroId = hero.id;
  8387. enchRune.tier = runeTier;
  8388. break;
  8389. }
  8390. }
  8391. }
  8392. return enchRune;
  8393. }
  8394.  
  8395. getOutlandChest() {
  8396. const bosses = this.questInfo['bossGetAll'];
  8397.  
  8398. const calls = [];
  8399.  
  8400. for (let boss of bosses) {
  8401. if (boss.mayRaid) {
  8402. calls.push({
  8403. name: "bossRaid",
  8404. args: {
  8405. bossId: boss.id
  8406. },
  8407. ident: "bossRaid_" + boss.id
  8408. });
  8409. calls.push({
  8410. name: "bossOpenChest",
  8411. args: {
  8412. bossId: boss.id,
  8413. amount: 1,
  8414. starmoney: 0
  8415. },
  8416. ident: "bossOpenChest_" + boss.id
  8417. });
  8418. } else if (boss.chestId == 1) {
  8419. calls.push({
  8420. name: "bossOpenChest",
  8421. args: {
  8422. bossId: boss.id,
  8423. amount: 1,
  8424. starmoney: 0
  8425. },
  8426. ident: "bossOpenChest_" + boss.id
  8427. });
  8428. }
  8429. }
  8430.  
  8431. return calls;
  8432. }
  8433.  
  8434. getExpHero() {
  8435. const heroes = Object.values(this.questInfo['heroGetAll']);
  8436. const inventory = this.questInfo['inventoryGet'];
  8437. const expHero = { heroId: 0, exp: 3625195, libId: 0 };
  8438. /** зелья опыта (consumable 9, 10, 11, 12) */
  8439. for (let i = 9; i <= 12; i++) {
  8440. if (inventory.consumable[i]) {
  8441. expHero.libId = i;
  8442. break;
  8443. }
  8444. }
  8445.  
  8446. for (const hero of heroes) {
  8447. const exp = hero.xp;
  8448. if (exp < expHero.exp) {
  8449. expHero.heroId = hero.id;
  8450. }
  8451. }
  8452. return expHero;
  8453. }
  8454.  
  8455. getHeroIdTitanGift() {
  8456. const heroes = Object.values(this.questInfo['heroGetAll']);
  8457. const inventory = this.questInfo['inventoryGet'];
  8458. const user = this.questInfo['userGetInfo'];
  8459. const titanGiftLib = lib.getData('titanGift');
  8460. /** Искры */
  8461. const titanGift = inventory.consumable[24];
  8462. let heroId = 0;
  8463. let minLevel = 30;
  8464.  
  8465. if (titanGift < 250 || user.gold < 7000) {
  8466. return 0;
  8467. }
  8468.  
  8469. for (const hero of heroes) {
  8470. if (hero.titanGiftLevel >= 30) {
  8471. continue;
  8472. }
  8473.  
  8474. if (!hero.titanGiftLevel) {
  8475. return hero.id;
  8476. }
  8477.  
  8478. const cost = titanGiftLib[hero.titanGiftLevel].cost;
  8479. if (minLevel > hero.titanGiftLevel &&
  8480. titanGift >= cost.consumable[24] &&
  8481. user.gold >= cost.gold
  8482. ) {
  8483. minLevel = hero.titanGiftLevel;
  8484. heroId = hero.id;
  8485. }
  8486. }
  8487.  
  8488. return heroId;
  8489. }
  8490.  
  8491. end(status) {
  8492. setProgress(status, true);
  8493. this.resolve();
  8494. }
  8495. }
  8496.  
  8497. this.questRun = dailyQuests;
  8498.  
  8499. function testDoYourBest() {
  8500. return new Promise((resolve, reject) => {
  8501. const doIt = new doYourBest(resolve, reject);
  8502. doIt.start();
  8503. });
  8504. }
  8505.  
  8506. /**
  8507. * Do everything button
  8508. *
  8509. * Кнопка сделать все
  8510. */
  8511. class doYourBest {
  8512.  
  8513. funcList = [
  8514. {
  8515. name: 'getOutland',
  8516. label: I18N('ASSEMBLE_OUTLAND'),
  8517. checked: false
  8518. },
  8519. {
  8520. name: 'testTower',
  8521. label: I18N('PASS_THE_TOWER'),
  8522. checked: false
  8523. },
  8524. {
  8525. name: 'checkExpedition',
  8526. label: I18N('CHECK_EXPEDITIONS'),
  8527. checked: false
  8528. },
  8529. {
  8530. name: 'testTitanArena',
  8531. label: I18N('COMPLETE_TOE'),
  8532. checked: false
  8533. },
  8534. {
  8535. name: 'mailGetAll',
  8536. label: I18N('COLLECT_MAIL'),
  8537. checked: false
  8538. },
  8539. {
  8540. name: 'collectAllStuff',
  8541. label: I18N('COLLECT_MISC'),
  8542. title: I18N('COLLECT_MISC_TITLE'),
  8543. checked: false
  8544. },
  8545. {
  8546. name: 'getDailyBonus',
  8547. label: I18N('DAILY_BONUS'),
  8548. checked: false
  8549. },
  8550. {
  8551. name: 'dailyQuests',
  8552. label: I18N('DO_DAILY_QUESTS'),
  8553. checked: false
  8554. },
  8555. {
  8556. name: 'questAllFarm',
  8557. label: I18N('COLLECT_QUEST_REWARDS'),
  8558. checked: false
  8559. },
  8560. {
  8561. name: 'testDungeon',
  8562. label: I18N('COMPLETE_DUNGEON'),
  8563. checked: false
  8564. },
  8565. {
  8566. name: 'synchronization',
  8567. label: I18N('MAKE_A_SYNC'),
  8568. checked: false
  8569. },
  8570. {
  8571. name: 'reloadGame',
  8572. label: I18N('RELOAD_GAME'),
  8573. checked: false
  8574. },
  8575. ];
  8576.  
  8577. functions = {
  8578. getOutland,
  8579. testTower,
  8580. checkExpedition,
  8581. testTitanArena,
  8582. mailGetAll,
  8583. collectAllStuff: async () => {
  8584. await offerFarmAllReward();
  8585. 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"}]}');
  8586. },
  8587. dailyQuests: async function () {
  8588. const quests = new dailyQuests(() => { }, () => { });
  8589. await quests.autoInit(true);
  8590. await quests.start();
  8591. },
  8592. getDailyBonus,
  8593. questAllFarm,
  8594. testDungeon,
  8595. synchronization: async () => {
  8596. cheats.refreshGame();
  8597. },
  8598. reloadGame: async () => {
  8599. location.reload();
  8600. }
  8601. }
  8602.  
  8603. constructor(resolve, reject, questInfo) {
  8604. this.resolve = resolve;
  8605. this.reject = reject;
  8606. this.questInfo = questInfo
  8607. }
  8608.  
  8609. async start() {
  8610. const selectedDoIt = getSaveVal('selectedDoIt', {});
  8611.  
  8612. this.funcList.forEach(task => {
  8613. if (!selectedDoIt[task.name]) {
  8614. selectedDoIt[task.name] = {
  8615. checked: task.checked
  8616. }
  8617. } else {
  8618. task.checked = selectedDoIt[task.name].checked
  8619. }
  8620. });
  8621.  
  8622. const answer = await popup.confirm(I18N('RUN_FUNCTION'), [
  8623. { msg: I18N('BTN_CANCEL'), result: false },
  8624. { msg: I18N('BTN_GO'), result: true },
  8625. ], this.funcList);
  8626.  
  8627. if (!answer) {
  8628. this.end('');
  8629. return;
  8630. }
  8631.  
  8632. const taskList = popup.getCheckBoxes();
  8633. taskList.forEach(task => {
  8634. selectedDoIt[task.name].checked = task.checked;
  8635. });
  8636. setSaveVal('selectedDoIt', selectedDoIt);
  8637. for (const task of popup.getCheckBoxes()) {
  8638. if (task.checked) {
  8639. try {
  8640. setProgress(`${task.label} <br>${I18N('PERFORMED')}!`);
  8641. await this.functions[task.name]();
  8642. setProgress(`${task.label} <br>${I18N('DONE')}!`);
  8643. } catch (error) {
  8644. if (await popup.confirm(`${I18N('ERRORS_OCCURRES')}:<br> ${task.label} <br>${I18N('COPY_ERROR')}?`, [
  8645. { msg: I18N('BTN_NO'), result: false },
  8646. { msg: I18N('BTN_YES'), result: true },
  8647. ])) {
  8648. this.errorHandling(error);
  8649. }
  8650. }
  8651. }
  8652. }
  8653. setTimeout((msg) => {
  8654. this.end(msg);
  8655. }, 2000, I18N('ALL_TASK_COMPLETED'));
  8656. return;
  8657. }
  8658.  
  8659. errorHandling(error) {
  8660. //console.error(error);
  8661. let errorInfo = error.toString() + '\n';
  8662. try {
  8663. const errorStack = error.stack.split('\n');
  8664. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testDoYourBest");
  8665. errorInfo += errorStack.slice(0, endStack).join('\n');
  8666. } catch (e) {
  8667. errorInfo += error.stack;
  8668. }
  8669. copyText(errorInfo);
  8670. }
  8671.  
  8672. end(status) {
  8673. setProgress(status, true);
  8674. this.resolve();
  8675. }
  8676. }
  8677.  
  8678. /**
  8679. * Passing the adventure along the specified route
  8680. *
  8681. * Прохождение приключения по указанному маршруту
  8682. */
  8683. function testAdventure(type) {
  8684. return new Promise((resolve, reject) => {
  8685. const bossBattle = new executeAdventure(resolve, reject);
  8686. bossBattle.start(type);
  8687. });
  8688. }
  8689.  
  8690. /**
  8691. * Passing the adventure along the specified route
  8692. *
  8693. * Прохождение приключения по указанному маршруту
  8694. */
  8695. class executeAdventure {
  8696.  
  8697. type = 'default';
  8698.  
  8699. actions = {
  8700. default: {
  8701. getInfo: "adventure_getInfo",
  8702. startBattle: 'adventure_turnStartBattle',
  8703. endBattle: 'adventure_endBattle',
  8704. collectBuff: 'adventure_turnCollectBuff'
  8705. },
  8706. solo: {
  8707. getInfo: "adventureSolo_getInfo",
  8708. startBattle: 'adventureSolo_turnStartBattle',
  8709. endBattle: 'adventureSolo_endBattle',
  8710. collectBuff: 'adventureSolo_turnCollectBuff'
  8711. }
  8712. }
  8713.  
  8714. terminatеReason = I18N('UNKNOWN');
  8715. callAdventureInfo = {
  8716. name: "adventure_getInfo",
  8717. args: {},
  8718. ident: "adventure_getInfo"
  8719. }
  8720. callTeamGetAll = {
  8721. name: "teamGetAll",
  8722. args: {},
  8723. ident: "teamGetAll"
  8724. }
  8725. callTeamGetFavor = {
  8726. name: "teamGetFavor",
  8727. args: {},
  8728. ident: "teamGetFavor"
  8729. }
  8730. callStartBattle = {
  8731. name: "adventure_turnStartBattle",
  8732. args: {},
  8733. ident: "body"
  8734. }
  8735. callEndBattle = {
  8736. name: "adventure_endBattle",
  8737. args: {
  8738. result: {},
  8739. progress: {},
  8740. },
  8741. ident: "body"
  8742. }
  8743. callCollectBuff = {
  8744. name: "adventure_turnCollectBuff",
  8745. args: {},
  8746. ident: "body"
  8747. }
  8748.  
  8749. constructor(resolve, reject) {
  8750. this.resolve = resolve;
  8751. this.reject = reject;
  8752. }
  8753.  
  8754. async start(type) {
  8755. this.type = type || this.type;
  8756. this.path = await this.getPath();
  8757. if (!this.path) {
  8758. this.end();
  8759. return;
  8760. }
  8761. this.callAdventureInfo.name = this.actions[this.type].getInfo;
  8762. const data = await Send(JSON.stringify({
  8763. calls: [
  8764. this.callAdventureInfo,
  8765. this.callTeamGetAll,
  8766. this.callTeamGetFavor
  8767. ]
  8768. }));
  8769. return this.checkAdventureInfo(data.results);
  8770. }
  8771.  
  8772. async getPath() {
  8773. const answer = await popup.confirm(I18N('ENTER_THE_PATH'), [
  8774. {
  8775. msg: I18N('START_ADVENTURE'),
  8776. placeholder: '1,2,3,4,5,6',
  8777. isInput: true,
  8778. default: getSaveVal('adventurePath', '')
  8779. },
  8780. {
  8781. msg: I18N('BTN_CANCEL'),
  8782. result: false
  8783. },
  8784. ]);
  8785. if (!answer) {
  8786. this.terminatеReason = I18N('BTN_CANCELED');
  8787. return false;
  8788. }
  8789.  
  8790. let path = answer.split(',');
  8791. if (path.length < 2) {
  8792. path = answer.split('-');
  8793. }
  8794. if (path.length < 2) {
  8795. this.terminatеReason = I18N('MUST_TWO_POINTS');
  8796. return false;
  8797. }
  8798.  
  8799. for (let p in path) {
  8800. path[p] = +path[p].trim()
  8801. if (Number.isNaN(path[p])) {
  8802. this.terminatеReason = I18N('MUST_ONLY_NUMBERS');
  8803. return false;
  8804. }
  8805. }
  8806. setSaveVal('adventurePath', answer);
  8807. return path;
  8808. }
  8809.  
  8810. checkAdventureInfo(data) {
  8811. this.advInfo = data[0].result.response;
  8812. if (!this.advInfo) {
  8813. this.terminatеReason = I18N('NOT_ON_AN_ADVENTURE') ;
  8814. return this.end();
  8815. }
  8816. const heroesTeam = data[1].result.response.adventure_hero;
  8817. const favor = data[2]?.result.response.adventure_hero;
  8818. const heroes = heroesTeam.slice(0, 5);
  8819. const pet = heroesTeam[5];
  8820. this.args = {
  8821. pet,
  8822. heroes,
  8823. favor,
  8824. path: [],
  8825. broadcast: false
  8826. }
  8827. const advUserInfo = this.advInfo.users[userInfo.id];
  8828. this.turnsLeft = advUserInfo.turnsLeft;
  8829. this.currentNode = advUserInfo.currentNode;
  8830. this.nodes = this.advInfo.nodes;
  8831.  
  8832. if (this.currentNode == 1 && this.path[0] != 1) {
  8833. this.path.unshift(1);
  8834. }
  8835.  
  8836. return this.loop();
  8837. }
  8838.  
  8839. async loop() {
  8840. const position = this.path.indexOf(+this.currentNode);
  8841. if (!(~position)) {
  8842. this.terminatеReason = I18N('YOU_IN_NOT_ON_THE_WAY');
  8843. return this.end();
  8844. }
  8845. this.path = this.path.slice(position);
  8846. if ((this.path.length - 1) > this.turnsLeft &&
  8847. await popup.confirm(I18N('ATTEMPTS_NOT_ENOUGH'), [
  8848. { msg: I18N('YES_CONTINUE'), result: false },
  8849. { msg: I18N('BTN_NO'), result: true },
  8850. ])) {
  8851. this.terminatеReason = I18N('NOT_ENOUGH_AP');
  8852. return this.end();
  8853. }
  8854. const toPath = [];
  8855. for (const nodeId of this.path) {
  8856. if (!this.turnsLeft) {
  8857. this.terminatеReason = I18N('ATTEMPTS_ARE_OVER');
  8858. return this.end();
  8859. }
  8860. toPath.push(nodeId);
  8861. console.log(toPath);
  8862. if (toPath.length > 1) {
  8863. setProgress(toPath.join(' > ') + ` ${I18N('MOVES')}: ` + this.turnsLeft);
  8864. }
  8865. if (nodeId == this.currentNode) {
  8866. continue;
  8867. }
  8868.  
  8869. const nodeInfo = this.getNodeInfo(nodeId);
  8870. if (nodeInfo.type == 'TYPE_COMBAT') {
  8871. if (nodeInfo.state == 'empty') {
  8872. this.turnsLeft--;
  8873. continue;
  8874. }
  8875.  
  8876. /**
  8877. * Disable regular battle cancellation
  8878. *
  8879. * Отключаем штатную отменую боя
  8880. */
  8881. isCancalBattle = false;
  8882. if (await this.battle(toPath)) {
  8883. this.turnsLeft--;
  8884. toPath.splice(0, toPath.indexOf(nodeId));
  8885. nodeInfo.state = 'empty';
  8886. isCancalBattle = true;
  8887. continue;
  8888. }
  8889. isCancalBattle = true;
  8890. return this.end()
  8891. }
  8892.  
  8893. if (nodeInfo.type == 'TYPE_PLAYERBUFF') {
  8894. const buff = this.checkBuff(nodeInfo);
  8895. if (buff == null) {
  8896. continue;
  8897. }
  8898.  
  8899. if (await this.collectBuff(buff, toPath)) {
  8900. this.turnsLeft--;
  8901. toPath.splice(0, toPath.indexOf(nodeId));
  8902. continue;
  8903. }
  8904. this.terminatеReason = I18N('BUFF_GET_ERROR');
  8905. return this.end();
  8906. }
  8907. }
  8908. this.terminatеReason = I18N('SUCCESS');
  8909. return this.end();
  8910. }
  8911.  
  8912. /**
  8913. * Carrying out a fight
  8914. *
  8915. * Проведение боя
  8916. */
  8917. async battle(path, preCalc = true) {
  8918. const data = await this.startBattle(path);
  8919. try {
  8920. const battle = data.results[0].result.response.battle;
  8921. const result = await Calc(battle);
  8922. if (result.result.win) {
  8923. const info = await this.endBattle(result);
  8924. if (info.results[0].result.response?.error) {
  8925. this.terminatеReason = I18N('BATTLE_END_ERROR');
  8926. return false;
  8927. }
  8928. } else {
  8929. await this.cancelBattle(result);
  8930.  
  8931. if (preCalc && await this.preCalcBattle(battle)) {
  8932. path = path.slice(-2);
  8933. for (let i = 1; i <= getInput('countAutoBattle'); i++) {
  8934. setProgress(`${I18N('AUTOBOT')}: ${i}/${getInput('countAutoBattle')}`);
  8935. const result = await this.battle(path, false);
  8936. if (result) {
  8937. setProgress(I18N('VICTORY'));
  8938. return true;
  8939. }
  8940. }
  8941. this.terminatеReason = I18N('FAILED_TO_WIN_AUTO');
  8942. return false;
  8943. }
  8944. return false;
  8945. }
  8946. } catch (error) {
  8947. console.error(error);
  8948. if (await popup.confirm(I18N('ERROR_OF_THE_BATTLE_COPY'), [
  8949. { msg: I18N('BTN_NO'), result: false },
  8950. { msg: I18N('BTN_YES'), result: true },
  8951. ])) {
  8952. this.errorHandling(error, data);
  8953. }
  8954. this.terminatеReason = I18N('ERROR_DURING_THE_BATTLE');
  8955. return false;
  8956. }
  8957. return true;
  8958. }
  8959.  
  8960. /**
  8961. * Recalculate battles
  8962. *
  8963. * Прерасчтет битвы
  8964. */
  8965. async preCalcBattle(battle) {
  8966. const countTestBattle = getInput('countTestBattle');
  8967. for (let i = 0; i < countTestBattle; i++) {
  8968. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  8969. const result = await Calc(battle);
  8970. if (result.result.win) {
  8971. console.log(i, countTestBattle);
  8972. return true;
  8973. }
  8974. }
  8975. this.terminatеReason = I18N('NO_CHANCE_WIN') + countTestBattle;
  8976. return false;
  8977. }
  8978.  
  8979. /**
  8980. * Starts a fight
  8981. *
  8982. * Начинает бой
  8983. */
  8984. startBattle(path) {
  8985. this.args.path = path;
  8986. this.callStartBattle.name = this.actions[this.type].startBattle;
  8987. this.callStartBattle.args = this.args
  8988. const calls = [this.callStartBattle];
  8989. return Send(JSON.stringify({ calls }));
  8990. }
  8991.  
  8992. cancelBattle(battle) {
  8993. const fixBattle = function (heroes) {
  8994. for (const ids in heroes) {
  8995. const hero = heroes[ids];
  8996. hero.energy = random(1, 999);
  8997. if (hero.hp > 0) {
  8998. hero.hp = random(1, hero.hp);
  8999. }
  9000. }
  9001. }
  9002. fixBattle(battle.progress[0].attackers.heroes);
  9003. fixBattle(battle.progress[0].defenders.heroes);
  9004. return this.endBattle(battle);
  9005. }
  9006.  
  9007. /**
  9008. * Ends the fight
  9009. *
  9010. * Заканчивает бой
  9011. */
  9012. endBattle(battle) {
  9013. this.callEndBattle.name = this.actions[this.type].endBattle;
  9014. this.callEndBattle.args.result = battle.result
  9015. this.callEndBattle.args.progress = battle.progress
  9016. const calls = [this.callEndBattle];
  9017. return Send(JSON.stringify({ calls }));
  9018. }
  9019.  
  9020. /**
  9021. * Checks if you can get a buff
  9022. *
  9023. * Проверяет можно ли получить баф
  9024. */
  9025. checkBuff(nodeInfo) {
  9026. let id = null;
  9027. let value = 0;
  9028. for (const buffId in nodeInfo.buffs) {
  9029. const buff = nodeInfo.buffs[buffId];
  9030. if (buff.owner == null && buff.value > value) {
  9031. id = buffId;
  9032. value = buff.value;
  9033. }
  9034. }
  9035. nodeInfo.buffs[id].owner = 'Я';
  9036. return id;
  9037. }
  9038.  
  9039. /**
  9040. * Collects a buff
  9041. *
  9042. * Собирает баф
  9043. */
  9044. async collectBuff(buff, path) {
  9045. this.callCollectBuff.name = this.actions[this.type].collectBuff;
  9046. this.callCollectBuff.args = { buff, path };
  9047. const calls = [this.callCollectBuff];
  9048. return Send(JSON.stringify({ calls }));
  9049. }
  9050.  
  9051. getNodeInfo(nodeId) {
  9052. return this.nodes.find(node => node.id == nodeId);
  9053. }
  9054.  
  9055. errorHandling(error, data) {
  9056. //console.error(error);
  9057. let errorInfo = error.toString() + '\n';
  9058. try {
  9059. const errorStack = error.stack.split('\n');
  9060. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testAdventure");
  9061. errorInfo += errorStack.slice(0, endStack).join('\n');
  9062. } catch (e) {
  9063. errorInfo += error.stack;
  9064. }
  9065. if (data) {
  9066. errorInfo += '\nData: ' + JSON.stringify(data);
  9067. }
  9068. copyText(errorInfo);
  9069. }
  9070.  
  9071. end() {
  9072. isCancalBattle = true;
  9073. setProgress(this.terminatеReason, true);
  9074. console.log(this.terminatеReason);
  9075. this.resolve();
  9076. }
  9077. }
  9078.  
  9079. /**
  9080. * Passage of brawls
  9081. *
  9082. * Прохождение потасовок
  9083. */
  9084. function testBrawls() {
  9085. return new Promise((resolve, reject) => {
  9086. const brawls = new executeBrawls(resolve, reject);
  9087. brawls.start(brawlsPack);
  9088. });
  9089. }
  9090. /**
  9091. * Passage of brawls
  9092. *
  9093. * Прохождение потасовок
  9094. */
  9095. class executeBrawls {
  9096. callBrawlQuestGetInfo = {
  9097. name: "brawl_questGetInfo",
  9098. args: {},
  9099. ident: "brawl_questGetInfo"
  9100. }
  9101. callBrawlFindEnemies = {
  9102. name: "brawl_findEnemies",
  9103. args: {},
  9104. ident: "brawl_findEnemies"
  9105. }
  9106. callBrawlQuestFarm = {
  9107. name: "brawl_questFarm",
  9108. args: {},
  9109. ident: "brawl_questFarm"
  9110. }
  9111. callUserGetInfo = {
  9112. name: "userGetInfo",
  9113. args: {},
  9114. ident: "userGetInfo"
  9115. }
  9116.  
  9117. stats = {
  9118. win: 0,
  9119. loss: 0,
  9120. count: 0,
  9121. }
  9122.  
  9123. stage = {
  9124. '3': 1,
  9125. '7': 2,
  9126. '12': 3,
  9127. }
  9128.  
  9129. constructor(resolve, reject) {
  9130. this.resolve = resolve;
  9131. this.reject = reject;
  9132. }
  9133.  
  9134. async start(heroes) {
  9135. this.heroes = heroes;
  9136. isCancalBattle = false;
  9137. this.brawlInfo = await this.getBrawlInfo();
  9138.  
  9139. if (!this.brawlInfo.attempts) {
  9140. this.end(I18N('DONT_HAVE_LIVES'))
  9141. return;
  9142. }
  9143.  
  9144. while (1) {
  9145. if (!isBrawlsAutoStart) {
  9146. this.end(I18N('BTN_CANCELED'))
  9147. return;
  9148. }
  9149.  
  9150. const maxStage = this.brawlInfo.questInfo.stage;
  9151. const stage = this.stage[maxStage];
  9152. const progress = this.brawlInfo.questInfo.progress;
  9153.  
  9154. setProgress(`${I18N('STAGE')} ${stage}: ${progress}/${maxStage}<br>${I18N('FIGHTS')}: ${this.stats.count}<br>${I18N('WINS')}: ${this.stats.win}<br>${I18N('LOSSES')}: ${this.stats.loss}<br>${I18N('STOP')}`, false, function () {
  9155. isBrawlsAutoStart = false;
  9156. });
  9157.  
  9158. if (this.brawlInfo.questInfo.canFarm) {
  9159. const result = await this.questFarm();
  9160. console.log(result);
  9161. }
  9162.  
  9163. if (this.brawlInfo.questInfo.stage == 12 && this.brawlInfo.questInfo.progress == 12) {
  9164. this.end(I18N('SUCCESS'))
  9165. return;
  9166. }
  9167.  
  9168. const enemie = Object.values(this.brawlInfo.findEnemies).shift();
  9169.  
  9170. const result = await this.battle(enemie.userId);
  9171. this.brawlInfo = {
  9172. questInfo: result[1].result.response,
  9173. findEnemies: result[2].result.response,
  9174. }
  9175. }
  9176. }
  9177.  
  9178. async questFarm() {
  9179. const calls = [this.callBrawlQuestFarm];
  9180. const result = await Send(JSON.stringify({ calls }));
  9181. return result.results[0].result.response;
  9182. }
  9183.  
  9184. async getBrawlInfo() {
  9185. const data = await Send(JSON.stringify({
  9186. calls: [
  9187. this.callUserGetInfo,
  9188. this.callBrawlQuestGetInfo,
  9189. this.callBrawlFindEnemies,
  9190. ]
  9191. }));
  9192.  
  9193. let attempts = data.results[0].result.response.refillable.find(n => n.id == 48);
  9194. return {
  9195. attempts: attempts.amount,
  9196. questInfo: data.results[1].result.response,
  9197. findEnemies: data.results[2].result.response,
  9198. }
  9199. }
  9200.  
  9201. /**
  9202. * Carrying out a fight
  9203. *
  9204. * Проведение боя
  9205. */
  9206. async battle(userId) {
  9207. this.stats.count++;
  9208. const battle = await this.startBattle(userId, this.heroes);
  9209. const result = await Calc(battle);
  9210. console.log(result.result);
  9211. if (result.result.win) {
  9212. this.stats.win++;
  9213. return await this.endBattle(result);
  9214. }
  9215. this.stats.loss++;
  9216. return await this.cancelBattle(result);
  9217. }
  9218.  
  9219. /**
  9220. * Starts a fight
  9221. *
  9222. * Начинает бой
  9223. */
  9224. async startBattle(userId, heroes) {
  9225. const calls = [{
  9226. name: "brawl_startBattle",
  9227. args: {
  9228. userId,
  9229. heroes,
  9230. favor: {},
  9231. },
  9232. ident: "brawl_startBattle"
  9233. }];
  9234. const result = await Send(JSON.stringify({ calls }));
  9235. return result.results[0].result.response;
  9236. }
  9237.  
  9238. cancelBattle(battle) {
  9239. const fixBattle = function (heroes) {
  9240. for (const ids in heroes) {
  9241. const hero = heroes[ids];
  9242. hero.energy = random(1, 999);
  9243. if (hero.hp > 0) {
  9244. hero.hp = random(1, hero.hp);
  9245. }
  9246. }
  9247. }
  9248. fixBattle(battle.progress[0].attackers.heroes);
  9249. fixBattle(battle.progress[0].defenders.heroes);
  9250. return this.endBattle(battle);
  9251. }
  9252.  
  9253. /**
  9254. * Ends the fight
  9255. *
  9256. * Заканчивает бой
  9257. */
  9258. async endBattle(battle) {
  9259. battle.progress[0].attackers.input = ['auto', 0, 0, 'auto', 0, 0];
  9260. const calls = [{
  9261. name: "brawl_endBattle",
  9262. args: {
  9263. result: battle.result,
  9264. progress: battle.progress
  9265. },
  9266. ident: "brawl_endBattle"
  9267. },
  9268. this.callBrawlQuestGetInfo,
  9269. this.callBrawlFindEnemies,
  9270. ];
  9271. const result = await Send(JSON.stringify({ calls }));
  9272. return result.results;
  9273. }
  9274.  
  9275. end(endReason) {
  9276. isCancalBattle = true;
  9277. isBrawlsAutoStart = false;
  9278. setProgress(endReason, true);
  9279. console.log(endReason);
  9280. this.resolve();
  9281. }
  9282. }
  9283. })();
  9284.  
  9285. /**
  9286. * TODO:
  9287. * Получение всех уровней при сборе всех наград (квест на титанит и на энку)
  9288. * Добавить проверку правильности пути для приключения
  9289. * Добивание на арене титанов
  9290. * Кнопку Турнир стихий красить в красный цвет если не дошел до 7 этапа
  9291. * Удалить progress боя при прерасчете реплеев
  9292. */