HeroWarsHelper

Automation of actions for the game Hero Wars

当前为 2024-02-05 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name HeroWarsHelper
  3. // @name:en HeroWarsHelper
  4. // @name:ru HeroWarsHelper
  5. // @namespace HeroWarsHelper
  6. // @version 2.201
  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://apps-1701433570146040.apps.fbsbx.com/*
  17. // @include https://*.nextersglobal.com/*
  18. // @include https://*.hero-wars*.com/*
  19. // @match https://www.solfors.com/
  20. // @match https://t.me/s/hw_ru
  21. // @run-at document-start
  22. // ==/UserScript==
  23.  
  24. (function() {
  25. /**
  26. * Start script
  27. *
  28. * Стартуем скрипт
  29. */
  30. console.log('Start ' + GM_info.script.name + ', v' + GM_info.script.version);
  31. /**
  32. * Script info
  33. *
  34. * Информация о скрипте
  35. */
  36. const scriptInfo = (({name, version, author, homepage, lastModified}, updateUrl, source) =>
  37. ({name, version, author, homepage, lastModified, updateUrl, source}))
  38. (GM_info.script, GM_info.scriptUpdateURL, arguments.callee.toString());
  39. /**
  40. * If we are on the gifts page, then we collect and send them to the server
  41. *
  42. * Если находимся на странице подарков, то собираем и отправляем их на сервер
  43. */
  44. if (['www.solfors.com', 't.me'].includes(location.host)) {
  45. setTimeout(sendCodes, 2000);
  46. return;
  47. }
  48. /**
  49. * Information for completing daily quests
  50. *
  51. * Информация для выполнения ежендевных квестов
  52. */
  53. const questsInfo = {};
  54. /**
  55. * Is the game data loaded
  56. *
  57. * Загружены ли данные игры
  58. */
  59. let isLoadGame = false;
  60. /**
  61. * Headers of the last request
  62. *
  63. * Заголовки последнего запроса
  64. */
  65. let lastHeaders = {};
  66. /**
  67. * Information about sent gifts
  68. *
  69. * Информация об отправленных подарках
  70. */
  71. let freebieCheckInfo = null;
  72. /**
  73. * User data
  74. *
  75. * Данные пользователя
  76. */
  77. let userInfo;
  78. /**
  79. * Original methods for working with AJAX
  80. *
  81. * Оригинальные методы для работы с AJAX
  82. */
  83. const original = {
  84. open: XMLHttpRequest.prototype.open,
  85. send: XMLHttpRequest.prototype.send,
  86. setRequestHeader: XMLHttpRequest.prototype.setRequestHeader,
  87. };
  88. /**
  89. * Decoder for converting byte data to JSON string
  90. *
  91. * Декодер для перобразования байтовых данных в JSON строку
  92. */
  93. const decoder = new TextDecoder("utf-8");
  94. /**
  95. * Stores a history of requests
  96. *
  97. * Хранит историю запросов
  98. */
  99. let requestHistory = {};
  100. /**
  101. * URL for API requests
  102. *
  103. * URL для запросов к API
  104. */
  105. let apiUrl = '';
  106.  
  107. /**
  108. * Connecting to the game code
  109. *
  110. * Подключение к коду игры
  111. */
  112. this.cheats = new hackGame();
  113. /**
  114. * The function of calculating the results of the battle
  115. *
  116. * Функция расчета результатов боя
  117. */
  118. this.BattleCalc = cheats.BattleCalc;
  119. /**
  120. * Sending a request available through the console
  121. *
  122. * Отправка запроса доступная через консоль
  123. */
  124. this.SendRequest = send;
  125. /**
  126. * Simple combat calculation available through the console
  127. *
  128. * Простой расчет боя доступный через консоль
  129. */
  130. this.Calc = function (data) {
  131. const type = getBattleType(data?.type);
  132. return new Promise((resolve, reject) => {
  133. try {
  134. BattleCalc(data, type, resolve);
  135. } catch (e) {
  136. reject(e);
  137. }
  138. })
  139. }
  140. /**
  141. * Short asynchronous request
  142. * Usage example (returns information about a character):
  143. * const userInfo = await Send('{"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}')
  144. *
  145. * Короткий асинхронный запрос
  146. * Пример использования (возвращает информацию о персонаже):
  147. * const userInfo = await Send('{"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}')
  148. */
  149. this.Send = function (json, pr) {
  150. return new Promise((resolve, reject) => {
  151. try {
  152. send(json, resolve, pr);
  153. } catch (e) {
  154. reject(e);
  155. }
  156. })
  157. }
  158.  
  159. const i18nLangData = {
  160. /* English translation by BaBa */
  161. en: {
  162. /* Checkboxes */
  163. SKIP_FIGHTS: 'Skip battle',
  164. SKIP_FIGHTS_TITLE: 'Skip battle in Outland and the arena of the titans, auto-pass in the tower and campaign',
  165. ENDLESS_CARDS: 'Infinite cards',
  166. ENDLESS_CARDS_TITLE: 'Disable Divination Cards wasting',
  167. AUTO_EXPEDITION: 'Auto Expedition',
  168. AUTO_EXPEDITION_TITLE: 'Auto-sending expeditions',
  169. CANCEL_FIGHT: 'Cancel battle',
  170. CANCEL_FIGHT_TITLE: 'The possibility of canceling the battle on VG',
  171. GIFTS: 'Gifts',
  172. GIFTS_TITLE: 'Collect gifts automatically',
  173. BATTLE_RECALCULATION: 'Battle recalculation',
  174. BATTLE_RECALCULATION_TITLE: 'Preliminary calculation of the battle',
  175. QUANTITY_CONTROL: 'Quantity control',
  176. QUANTITY_CONTROL_TITLE: 'Ability to specify the number of opened "lootboxes"',
  177. REPEAT_CAMPAIGN: 'Repeat missions',
  178. REPEAT_CAMPAIGN_TITLE: 'Auto-repeat battles in the campaign',
  179. DISABLE_DONAT: 'Disable donation',
  180. DISABLE_DONAT_TITLE: 'Removes all donation offers',
  181. DAILY_QUESTS: 'Quests',
  182. DAILY_QUESTS_TITLE: 'Complete daily quests',
  183. AUTO_QUIZ: 'AutoQuiz',
  184. AUTO_QUIZ_TITLE: 'Automatically receive correct answers to quiz questions',
  185. SECRET_WEALTH_CHECKBOX: 'Automatic purchase in the store "Secret Wealth" when entering the game',
  186. HIDE_SERVERS: 'Collapse servers',
  187. HIDE_SERVERS_TITLE: 'Hide unused servers',
  188. /* Input fields */
  189. HOW_MUCH_TITANITE: 'How much titanite to farm',
  190. COMBAT_SPEED: 'Combat Speed Multiplier',
  191. NUMBER_OF_TEST: 'Number of test fights',
  192. NUMBER_OF_AUTO_BATTLE: 'Number of auto-battle attempts',
  193. /* Buttons */
  194. RUN_SCRIPT: 'Run the',
  195. TO_DO_EVERYTHING: 'Do All',
  196. TO_DO_EVERYTHING_TITLE: 'Perform multiple actions of your choice',
  197. OUTLAND: 'Outland',
  198. OUTLAND_TITLE: 'Collect Outland',
  199. TITAN_ARENA: 'ToE',
  200. TITAN_ARENA_TITLE: 'Complete the titan arena',
  201. DUNGEON: 'Dungeon',
  202. DUNGEON_TITLE: 'Go through the dungeon',
  203. SEER: 'Seer',
  204. SEER_TITLE: 'Roll the Seer',
  205. TOWER: 'Tower',
  206. TOWER_TITLE: 'Pass the tower',
  207. EXPEDITIONS: 'Expeditions',
  208. EXPEDITIONS_TITLE: 'Sending and collecting expeditions',
  209. SYNC: 'Sync',
  210. SYNC_TITLE: 'Partial synchronization of game data without reloading the page',
  211. ARCHDEMON: 'Archdemon',
  212. ARCHDEMON_TITLE: 'Hitting kills and collecting rewards',
  213. ESTER_EGGS: 'Easter eggs',
  214. ESTER_EGGS_TITLE: 'Collect all Easter eggs or rewards',
  215. REWARDS: 'Rewards',
  216. REWARDS_TITLE: 'Collect all quest rewards',
  217. MAIL: 'Mail',
  218. MAIL_TITLE: 'Collect all mail, except letters with energy and charges of the portal',
  219. MINIONS: 'Minions',
  220. MINIONS_TITLE: 'Attack minions with saved packs',
  221. ADVENTURE: 'Adventure',
  222. ADVENTURE_TITLE: 'Passes the adventure along the specified route',
  223. STORM: 'Storm',
  224. STORM_TITLE: 'Passes the Storm along the specified route',
  225. SANCTUARY: 'Sanctuary',
  226. SANCTUARY_TITLE: 'Fast travel to Sanctuary',
  227. GUILD_WAR: 'Guild War',
  228. GUILD_WAR_TITLE: 'Fast travel to Guild War',
  229. SECRET_WEALTH: 'Secret Wealth',
  230. SECRET_WEALTH_TITLE: 'Buy something in the store "Secret Wealth"',
  231. /* Misc */
  232. 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>',
  233. GIFTS_SENT: 'Gifts sent!',
  234. DO_YOU_WANT: "Do you really want to do this?",
  235. BTN_RUN: 'Run',
  236. BTN_CANCEL: 'Cancel',
  237. BTN_OK: 'OK',
  238. MSG_HAVE_BEEN_DEFEATED: 'You have been defeated!',
  239. BTN_AUTO: 'Auto',
  240. MSG_YOU_APPLIED: 'You applied',
  241. MSG_DAMAGE: 'damage',
  242. MSG_CANCEL_AND_STAT: 'Auto (F5) and show statistic',
  243. MSG_REPEAT_MISSION: 'Repeat the mission?',
  244. BTN_REPEAT: 'Repeat',
  245. BTN_NO: 'No',
  246. MSG_SPECIFY_QUANT: 'Specify Quantity:',
  247. BTN_OPEN: 'Open',
  248. QUESTION_COPY: 'Question copied to clipboard',
  249. ANSWER_KNOWN: 'The answer is known',
  250. ANSWER_NOT_KNOWN: 'ATTENTION THE ANSWER IS NOT KNOWN',
  251. BEING_RECALC: 'The battle is being recalculated',
  252. THIS_TIME: 'This time',
  253. VICTORY: '<span style="color:green;">VICTORY</span>',
  254. DEFEAT: '<span style="color:red;">DEFEAT</span>',
  255. CHANCE_TO_WIN: 'Chance to win <span style="color: red;">based on pre-calculation</span>',
  256. OPEN_DOLLS: 'nesting dolls recursively',
  257. SENT_QUESTION: 'Question sent',
  258. SETTINGS: 'Settings',
  259. MSG_BAN_ATTENTION: '<p style="color:red;">Using this feature may result in a ban.</p> Continue?',
  260. BTN_YES_I_AGREE: 'Yes, I understand the risks!',
  261. BTN_NO_I_AM_AGAINST: 'No, I refuse it!',
  262. VALUES: 'Values',
  263. EXPEDITIONS_SENT: 'Expeditions sent',
  264. TITANIT: 'Titanit',
  265. COMPLETED: 'completed',
  266. FLOOR: 'Floor',
  267. LEVEL: 'Level',
  268. BATTLES: 'battles',
  269. EVENT: 'Event',
  270. NOT_AVAILABLE: 'not available',
  271. NO_HEROES: 'No heroes',
  272. DAMAGE_AMOUNT: 'Damage amount',
  273. NOTHING_TO_COLLECT: 'Nothing to collect',
  274. COLLECTED: 'Collected',
  275. REWARD: 'rewards',
  276. REMAINING_ATTEMPTS: 'Remaining attempts',
  277. BATTLES_CANCELED: 'Battles canceled',
  278. MINION_RAID: 'Minion Raid',
  279. STOPPED: 'Stopped',
  280. REPETITIONS: 'Repetitions',
  281. MISSIONS_PASSED: 'Missions passed',
  282. STOP: 'stop',
  283. TOTAL_OPEN: 'Total open',
  284. OPEN: 'Open',
  285. ROUND_STAT: 'Damage statistics for ',
  286. BATTLE: 'battles',
  287. MINIMUM: 'Minimum',
  288. MAXIMUM: 'Maximum',
  289. AVERAGE: 'Average',
  290. NOT_THIS_TIME: 'Not this time',
  291. RETRY_LIMIT_EXCEEDED: 'Retry limit exceeded',
  292. SUCCESS: 'Success',
  293. RECEIVED: 'Received',
  294. LETTERS: 'letters',
  295. PORTALS: 'portals',
  296. ATTEMPTS: 'attempts',
  297. /* Quests */
  298. QUEST_10001: 'Upgrade the skills of heroes 3 times',
  299. QUEST_10002: 'Complete 10 missions',
  300. QUEST_10003: 'Complete 3 heroic missions',
  301. QUEST_10004: 'Fight 3 times in the Arena or Grand Arena',
  302. QUEST_10006: 'Use the exchange of emeralds 1 time',
  303. QUEST_10007: 'Perform 1 summon in the Solu Atrium',
  304. QUEST_10016: 'Send gifts to guildmates',
  305. QUEST_10018: 'Use an experience potion',
  306. QUEST_10019: 'Open 1 chest in the Tower',
  307. QUEST_10020: 'Open 3 chests in Outland',
  308. QUEST_10021: 'Collect 75 Titanite in the Guild Dungeon',
  309. QUEST_10021: 'Collect 150 Titanite in the Guild Dungeon',
  310. QUEST_10023: 'Upgrade Gift of the Elements by 1 level',
  311. QUEST_10024: 'Level up any artifact once',
  312. QUEST_10025: 'Start Expedition 1',
  313. QUEST_10026: 'Start 4 Expeditions',
  314. QUEST_10027: 'Win 1 battle of the Tournament of Elements',
  315. QUEST_10028: 'Level up any titan artifact',
  316. QUEST_10029: 'Unlock the Orb of Titan Artifacts',
  317. QUEST_10030: 'Upgrade any Skin of any hero 1 time',
  318. QUEST_10031: 'Win 6 battles of the Tournament of Elements',
  319. QUEST_10043: 'Start or Join an Adventure',
  320. QUEST_10044: 'Use Summon Pets 1 time',
  321. QUEST_10046: 'Open 3 chests in Adventure',
  322. QUEST_10047: 'Get 150 Guild Activity Points',
  323. NOTHING_TO_DO: 'Nothing to do',
  324. YOU_CAN_COMPLETE: 'You can complete quests',
  325. BTN_DO_IT: 'Do it',
  326. NOT_QUEST_COMPLETED: 'Not a single quest completed',
  327. COMPLETED_QUESTS: 'Completed quests',
  328. /* everything button */
  329. ASSEMBLE_OUTLAND: 'Assemble Outland',
  330. PASS_THE_TOWER: 'Pass the tower',
  331. CHECK_EXPEDITIONS: 'Check Expeditions',
  332. COMPLETE_TOE: 'Complete ToE',
  333. COMPLETE_DUNGEON: 'Complete the dungeon',
  334. COLLECT_MAIL: 'Collect mail',
  335. COLLECT_MISC: 'Collect some bullshit',
  336. COLLECT_MISC_TITLE: 'Collect Easter Eggs, Skin Gems, Keys, Arena Coins and Soul Crystal',
  337. COLLECT_QUEST_REWARDS: 'Collect quest rewards',
  338. MAKE_A_SYNC: 'Make a sync',
  339.  
  340. RUN_FUNCTION: 'Run the following functions?',
  341. BTN_GO: 'Go!',
  342. PERFORMED: 'Performed',
  343. DONE: 'Done',
  344. ERRORS_OCCURRES: 'Errors occurred while executing',
  345. COPY_ERROR: 'Copy error information to clipboard',
  346. BTN_YES: 'Yes',
  347. ALL_TASK_COMPLETED: 'All tasks completed',
  348.  
  349. UNKNOWN: 'unknown',
  350. ENTER_THE_PATH: 'Enter the path of adventure using commas or dashes',
  351. START_ADVENTURE: 'Start your adventure along this path!',
  352. INCORRECT_WAY: 'Incorrect path in adventure: {from} -> {to}',
  353. BTN_CANCELED: 'Canceled',
  354. MUST_TWO_POINTS: 'The path must contain at least 2 points.',
  355. MUST_ONLY_NUMBERS: 'The path must contain only numbers and commas',
  356. NOT_ON_AN_ADVENTURE: 'You are not on an adventure',
  357. YOU_IN_NOT_ON_THE_WAY: 'Your location is not on the way',
  358. ATTEMPTS_NOT_ENOUGH: 'Your attempts are not enough to complete the path, continue?',
  359. YES_CONTINUE: 'Yes, continue!',
  360. NOT_ENOUGH_AP: 'Not enough action points',
  361. ATTEMPTS_ARE_OVER: 'The attempts are over',
  362. MOVES: 'Moves',
  363. BUFF_GET_ERROR: 'Buff getting error',
  364. BATTLE_END_ERROR: 'Battle end error',
  365. AUTOBOT: 'Autobot',
  366. FAILED_TO_WIN_AUTO: 'Failed to win the auto battle',
  367. ERROR_OF_THE_BATTLE_COPY: 'An error occurred during the passage of the battle<br>Copy the error to the clipboard?',
  368. ERROR_DURING_THE_BATTLE: 'Error during the battle',
  369. NO_CHANCE_WIN: 'No chance of winning this fight: 0/',
  370. LOST_HEROES: 'You have won, but you have lost one or several heroes',
  371. VICTORY_IMPOSSIBLE: 'Is victory impossible, should we focus on the result?',
  372. FIND_COEFF: 'Find the coefficient greater than',
  373. BTN_PASS: 'PASS',
  374. BRAWLS: 'Brawls',
  375. BRAWLS_TITLE: 'Activates the ability to auto-brawl',
  376. START_AUTO_BRAWLS: 'Start Auto Brawls?',
  377. LOSSES: 'Losses',
  378. WINS: 'Wins',
  379. FIGHTS: 'Fights',
  380. STAGE: 'Stage',
  381. DONT_HAVE_LIVES: 'You don\'t have lives',
  382. LIVES: 'Lives',
  383. SECRET_WEALTH_ALREADY: 'Item for Pet Potions already purchased',
  384. SECRET_WEALTH_NOT_ENOUGH: 'Not Enough Pet Potion, You Have {available}, Need {need}',
  385. SECRET_WEALTH_UPGRADE_NEW_PET: 'After purchasing the Pet Potion, it will not be enough to upgrade a new pet',
  386. SECRET_WEALTH_PURCHASED: 'Purchased {count} {name}',
  387. SECRET_WEALTH_CANCELED: 'Secret Wealth: Purchase Canceled',
  388. SECRET_WEALTH_BUY: 'You have {available} Pet Potion.<br>Do you want to buy {countBuy} {name} for {price} Pet Potion?',
  389. DAILY_BONUS: 'Daily bonus',
  390. DO_DAILY_QUESTS: 'Do daily quests',
  391. ACTIONS: 'Actions',
  392. ACTIONS_TITLE: 'Dialog box with various actions',
  393. OTHERS: 'Others',
  394. OTHERS_TITLE: 'Others',
  395. CHOOSE_ACTION: 'Choose an action',
  396. OPEN_LOOTBOX: 'You have {lootBox} boxes, should we open them?',
  397. STAMINA: 'Energy',
  398. BOXES_OVER: 'The boxes are over',
  399. NO_BOXES: 'No boxes',
  400. NO_MORE_ACTIVITY: 'No more activity for items today',
  401. EXCHANGE_ITEMS: 'Exchange items for activity points (max {maxActive})?',
  402. GET_ACTIVITY: 'Get Activity',
  403. NOT_ENOUGH_ITEMS: 'Not enough items',
  404. ACTIVITY_RECEIVED: 'Activity received',
  405. NO_PURCHASABLE_HERO_SOULS: 'No purchasable Hero Souls',
  406. PURCHASED_HERO_SOULS: 'Purchased {countHeroSouls} Hero Souls',
  407. NOT_ENOUGH_EMERALDS_540: 'Not enough emeralds, you need 540 you have {currentStarMoney}',
  408. CHESTS_NOT_AVAILABLE: 'Chests not available',
  409. OUTLAND_CHESTS_RECEIVED: 'Outland chests received',
  410. RAID_NOT_AVAILABLE: 'The raid is not available or there are no spheres',
  411. RAID_ADVENTURE: 'Raid {adventureId} adventure!',
  412. SOMETHING_WENT_WRONG: 'Something went wrong',
  413. ADVENTURE_COMPLETED: 'Adventure {adventureId} completed {times} times',
  414. CLAN_STAT_COPY: 'Clan statistics copied to clipboard',
  415. GET_ENERGY: 'Get Energy',
  416. GET_ENERGY_TITLE: 'Opens platinum boxes one at a time until you get 250 energy',
  417. ITEM_EXCHANGE: 'Item Exchange',
  418. ITEM_EXCHANGE_TITLE: 'Exchanges items for the specified amount of activity',
  419. BUY_SOULS: 'Buy souls',
  420. BUY_SOULS_TITLE: 'Buy hero souls from all available shops',
  421. BUY_OUTLAND: 'Buy Outland',
  422. BUY_OUTLAND_TITLE: 'Buy 9 chests in Outland for 540 emeralds',
  423. AUTO_RAID_ADVENTURE: 'Raid adventure',
  424. AUTO_RAID_ADVENTURE_TITLE: 'Raid adventure set number of times',
  425. CLAN_STAT: 'Clan statistics',
  426. CLAN_STAT_TITLE: 'Copies clan statistics to the clipboard',
  427. BTN_AUTO_F5: 'Auto (F5)',
  428. BOSS_DAMAGE: 'Boss Damage: ',
  429. NOTHING_BUY: 'Nothing to buy',
  430. LOTS_BOUGHT: '{countBuy} lots bought for gold',
  431. BUY_FOR_GOLD: 'Buy for gold',
  432. BUY_FOR_GOLD_TITLE: 'Buy items for gold in the Town Shop and in the Pet Soul Stone Shop',
  433. REWARDS_AND_MAIL: 'Rewars and Mail',
  434. REWARDS_AND_MAIL_TITLE: 'Collects rewards and mail',
  435. COLLECT_REWARDS_AND_MAIL: 'Collected {countQuests} rewards and {countMail} letters',
  436. TIMER_ALREADY: 'Timer already started',
  437. NO_ATTEMPTS_TIMER_START: 'No attempts, timer started',
  438. EPIC_BRAWL_RESULT: 'Wins: {wins}/{attempts}, Coins: {coins}, Streak: {progress}/{nextStage} [Close]{end}',
  439. ATTEMPT_ENDED: '<br>Attempts ended, timer started',
  440. EPIC_BRAWL: 'Cosmic Battle',
  441. EPIC_BRAWL_TITLE: 'Spends attempts in the Cosmic Battle',
  442. RELOAD_GAME: 'Reload game',
  443. TIMER: 'Timer:',
  444. SHOW_ERRORS: 'Show errors',
  445. SHOW_ERRORS_TITLE: 'Show server request errors',
  446. ERROR_MSG: 'Error: {name}<br>{description}',
  447. EVENT_AUTO_BOSS: 'Maximum number of battles for calculation:</br>{length} ∗ {countTestBattle} = {maxCalcBattle}</br>If you have a weak computer, it may take a long time for this, click on the cross to cancel.</br>Should I search for the best pack from all or the first suitable one?',
  448. BEST_SLOW: 'Best (slower)',
  449. FIRST_FAST: 'First (faster)',
  450. FREEZE_INTERFACE: 'Calculating... <br>The interface may freeze.',
  451. ERROR_F12: 'Error, details in the console (F12)',
  452. FAILED_FIND_WIN_PACK: 'Failed to find a winning pack',
  453. BEST_PACK: 'Best pack:',
  454. BOSS_HAS_BEEN_DEF: 'Boss {bossLvl} has been defeated.',
  455. NOT_ENOUGH_ATTEMPTS_BOSS: 'Not enough attempts to defeat boss {bossLvl}, retry?',
  456. BOSS_VICTORY_IMPOSSIBLE: 'Based on the recalculation of {battles} battles, victory has not been achieved. Would you like to continue the search for a winning battle in real battles? <p style="color:red;">Using this feature may be considered as DDoS attack or HTTP flooding and result in permanent ban</p>',
  457. BOSS_HAS_BEEN_DEF_TEXT: 'Boss {bossLvl} defeated in<br>{countBattle}/{countMaxBattle} attempts<br>(Please synchronize or restart the game to update the data)',
  458. PLAYER_POS: 'Player positions:',
  459. NY_GIFTS: 'Gifts',
  460. NY_GIFTS_TITLE: 'Open all New Year\'s gifts',
  461. NY_NO_GIFTS: 'No gifts not received',
  462. NY_GIFTS_COLLECTED: '{count} gifts collected',
  463. CHANGE_MAP: 'Island map',
  464. CHANGE_MAP_TITLE: 'Change island map',
  465. SELECT_ISLAND_MAP: 'Select an island map:',
  466. FIRST_MAP: 'First map',
  467. SECOND_MAP: 'Second map',
  468. SECRET_WEALTH_SHOP: 'Secret Wealth {name}: ',
  469. SHOPS: 'Shops',
  470. SHOPS_DEFAULT: 'Default',
  471. SHOPS_DEFAULT_TITLE: 'Default stores',
  472. SHOPS_LIST: 'Shops {number}',
  473. SHOPS_LIST_TITLE: 'List of shops {number}',
  474. SHOPS_WARNING: 'Stores<br><span style="color:red">If you buy brawl store coins for emeralds, you must use them immediately, otherwise they will disappear after restarting the game!</span>',
  475. MINIONS_WARNING: 'The hero packs for attacking minions are incomplete, should I continue?',
  476. FAST_SEASON: 'Fast season',
  477. FAST_SEASON_TITLE: 'Skip the map selection screen in a season',
  478. GET_SOMETHING: 'Get something',
  479. GET_SOMETHING_TITLE: 'Collects everything something',
  480. GET_ALL_SOMETHING: 'Get all somethings?',
  481. NO_SOMETHING_DATA: 'Some data is missing',
  482. COLLECTED_SOMETHING: 'Collected: {count}',
  483. SET_NUMBER_LEVELS: 'Specify the number of levels:',
  484. NOT_ENOUGH_RESOURECES: 'Not enough resources',
  485. IMPROVED_LEVELS: 'Improved levels: {count}',
  486. ARTIFACTS_IMPROVEMENT: 'Artifacts improvement',
  487. ARTIFACTS_IMPROVEMENT_TITLE: 'Upgrades the specified amount of the cheapest hero artifacts',
  488. SKINS_IMPROVEMENT: 'Skins improvement',
  489. SKINS_IMPROVEMENT_TITLE: 'Upgrades the specified amount of the cheapest hero skins',
  490. },
  491. ru: {
  492. /* Чекбоксы */
  493. SKIP_FIGHTS: 'Пропуск боев',
  494. SKIP_FIGHTS_TITLE: 'Пропуск боев в запределье и арене титанов, автопропуск в башне и кампании',
  495. ENDLESS_CARDS: 'Бесконечные карты',
  496. ENDLESS_CARDS_TITLE: 'Отключить трату карт предсказаний',
  497. AUTO_EXPEDITION: 'АвтоЭкспедиции',
  498. AUTO_EXPEDITION_TITLE: 'Автоотправка экспедиций',
  499. CANCEL_FIGHT: 'Отмена боя',
  500. CANCEL_FIGHT_TITLE: 'Возможность отмены боя на ВГ, СМ и в Асгарде',
  501. GIFTS: 'Подарки',
  502. GIFTS_TITLE: 'Собирать подарки автоматически',
  503. BATTLE_RECALCULATION: 'Прерасчет боя',
  504. BATTLE_RECALCULATION_TITLE: 'Предварительный расчет боя',
  505. QUANTITY_CONTROL: 'Контроль кол-ва',
  506. QUANTITY_CONTROL_TITLE: 'Возможность указывать количество открываемых "лутбоксов"',
  507. REPEAT_CAMPAIGN: 'Повтор в компании',
  508. REPEAT_CAMPAIGN_TITLE: 'Автоповтор боев в кампании',
  509. DISABLE_DONAT: 'Отключить донат',
  510. DISABLE_DONAT_TITLE: 'Убирает все предложения доната',
  511. DAILY_QUESTS: 'Квесты',
  512. DAILY_QUESTS_TITLE: 'Выполнять ежедневные квесты',
  513. AUTO_QUIZ: 'АвтоВикторина',
  514. AUTO_QUIZ_TITLE: 'Автоматическое получение правильных ответов на вопросы викторины',
  515. SECRET_WEALTH_CHECKBOX: 'Автоматическая покупка в магазине "Тайное Богатство" при заходе в игру',
  516. HIDE_SERVERS: 'Свернуть сервера',
  517. HIDE_SERVERS_TITLE: 'Скрывать неиспользуемые сервера',
  518. /* Поля ввода */
  519. HOW_MUCH_TITANITE: 'Сколько фармим титанита',
  520. COMBAT_SPEED: 'Множитель ускорения боя',
  521. NUMBER_OF_TEST: 'Количество тестовых боев',
  522. NUMBER_OF_AUTO_BATTLE: 'Количество попыток автобоев',
  523. /* Кнопки */
  524. RUN_SCRIPT: 'Запустить скрипт',
  525. TO_DO_EVERYTHING: 'Сделать все',
  526. TO_DO_EVERYTHING_TITLE: 'Выполнить несколько действий',
  527. OUTLAND: 'Запределье',
  528. OUTLAND_TITLE: 'Собрать Запределье',
  529. TITAN_ARENA: 'Турнир Стихий',
  530. TITAN_ARENA_TITLE: 'Автопрохождение Турнира Стихий',
  531. DUNGEON: 'Подземелье',
  532. DUNGEON_TITLE: 'Автопрохождение подземелья',
  533. SEER: 'Провидец',
  534. SEER_TITLE: 'Покрутить Провидца',
  535. TOWER: 'Башня',
  536. TOWER_TITLE: 'Автопрохождение башни',
  537. EXPEDITIONS: 'Экспедиции',
  538. EXPEDITIONS_TITLE: 'Отправка и сбор экспедиций',
  539. SYNC: 'Синхронизация',
  540. SYNC_TITLE: 'Частичная синхронизация данных игры без перезагрузки сатраницы',
  541. ARCHDEMON: 'Архидемон',
  542. ARCHDEMON_TITLE: 'Набивает килы и собирает награду',
  543. ESTER_EGGS: 'Пасхалки',
  544. ESTER_EGGS_TITLE: 'Собрать все пасхалки или награды',
  545. REWARDS: 'Награды',
  546. REWARDS_TITLE: 'Собрать все награды за задания',
  547. MAIL: 'Почта',
  548. MAIL_TITLE: 'Собрать всю почту, кроме писем с энергией и зарядами портала',
  549. MINIONS: 'Прислужники',
  550. MINIONS_TITLE: 'Атакует прислужников сохраннеными пачками',
  551. ADVENTURE: 'Приключение',
  552. ADVENTURE_TITLE: 'Проходит приключение по указанному маршруту',
  553. STORM: 'Буря',
  554. STORM_TITLE: 'Проходит бурю по указанному маршруту',
  555. SANCTUARY: 'Святилище',
  556. SANCTUARY_TITLE: 'Быстрый переход к Святилищу',
  557. GUILD_WAR: 'Война гильдий',
  558. GUILD_WAR_TITLE: 'Быстрый переход к Войне гильдий',
  559. SECRET_WEALTH: 'Тайное богатство',
  560. SECRET_WEALTH_TITLE: 'Купить что-то в магазине "Тайное богатство"',
  561. /* Разное */
  562. 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>',
  563. GIFTS_SENT: 'Подарки отправлены!',
  564. DO_YOU_WANT: "Вы действительно хотите это сделать?",
  565. BTN_RUN: 'Запускай',
  566. BTN_CANCEL: 'Отмена',
  567. BTN_OK: 'Ок',
  568. MSG_HAVE_BEEN_DEFEATED: 'Вы потерпели поражение!',
  569. BTN_AUTO: 'Авто',
  570. MSG_YOU_APPLIED: 'Вы нанесли',
  571. MSG_DAMAGE: 'урона',
  572. MSG_CANCEL_AND_STAT: 'Авто (F5) и показать Статистику',
  573. MSG_REPEAT_MISSION: 'Повторить миссию?',
  574. BTN_REPEAT: 'Повторить',
  575. BTN_NO: 'Нет',
  576. MSG_SPECIFY_QUANT: 'Указать количество:',
  577. BTN_OPEN: 'Открыть',
  578. QUESTION_COPY: 'Вопрос скопирован в буфер обмена',
  579. ANSWER_KNOWN: 'Ответ известен',
  580. ANSWER_NOT_KNOWN: 'ВНИМАНИЕ ОТВЕТ НЕ ИЗВЕСТЕН',
  581. BEING_RECALC: 'Идет прерасчет боя',
  582. THIS_TIME: 'На этот раз',
  583. VICTORY: '<span style="color:green;">ПОБЕДА</span>',
  584. DEFEAT: '<span style="color:red;">ПОРАЖЕНИЕ</span>',
  585. CHANCE_TO_WIN: 'Шансы на победу <span style="color:red;">на основе прерасчета</span>',
  586. OPEN_DOLLS: 'матрешек рекурсивно',
  587. SENT_QUESTION: 'Вопрос отправлен',
  588. SETTINGS: 'Настройки',
  589. MSG_BAN_ATTENTION: '<p style="color:red;">Использование этой функции может привести к бану.</p> Продолжить?',
  590. BTN_YES_I_AGREE: 'Да, я беру на себя все риски!',
  591. BTN_NO_I_AM_AGAINST: 'Нет, я отказываюсь от этого!',
  592. VALUES: 'Значения',
  593. EXPEDITIONS_SENT: 'Экспедиции отправлены',
  594. TITANIT: 'Титанит',
  595. COMPLETED: 'завершено',
  596. FLOOR: 'Этаж',
  597. LEVEL: 'Уровень',
  598. BATTLES: 'бои',
  599. EVENT: 'Эвент',
  600. NOT_AVAILABLE: 'недоступен',
  601. NO_HEROES: 'Нет героев',
  602. DAMAGE_AMOUNT: 'Количество урона',
  603. NOTHING_TO_COLLECT: 'Нечего собирать',
  604. COLLECTED: 'Собрано',
  605. REWARD: 'наград',
  606. REMAINING_ATTEMPTS: 'Осталось попыток',
  607. BATTLES_CANCELED: 'Битв отменено',
  608. MINION_RAID: 'Рейд прислужников',
  609. STOPPED: 'Остановлено',
  610. REPETITIONS: 'Повторений',
  611. MISSIONS_PASSED: 'Миссий пройдено',
  612. STOP: 'остановить',
  613. TOTAL_OPEN: 'Всего открыто',
  614. OPEN: 'Открыто',
  615. ROUND_STAT: 'Статистика урона за',
  616. BATTLE: 'боев',
  617. MINIMUM: 'Минимальный',
  618. MAXIMUM: 'Максимальный',
  619. AVERAGE: 'Средний',
  620. NOT_THIS_TIME: 'Не в этот раз',
  621. RETRY_LIMIT_EXCEEDED: 'Превышен лимит попыток',
  622. SUCCESS: 'Успех',
  623. RECEIVED: 'Получено',
  624. LETTERS: 'писем',
  625. PORTALS: 'порталов',
  626. ATTEMPTS: 'попыток',
  627. QUEST_10001: 'Улучши умения героев 3 раза',
  628. QUEST_10002: 'Пройди 10 миссий',
  629. QUEST_10003: 'Пройди 3 героические миссии',
  630. QUEST_10004: 'Сразись 3 раза на Арене или Гранд Арене',
  631. QUEST_10006: 'Используй обмен изумрудов 1 раз',
  632. QUEST_10007: 'Соверши 1 призыв в Атриуме Душ',
  633. QUEST_10016: 'Отправь подарки согильдийцам',
  634. QUEST_10018: 'Используй зелье опыта',
  635. QUEST_10019: 'Открой 1 сундук в Башне',
  636. QUEST_10020: 'Открой 3 сундука в Запределье',
  637. QUEST_10021: 'Собери 75 Титанита в Подземелье Гильдии',
  638. QUEST_10021: 'Собери 150 Титанита в Подземелье Гильдии',
  639. QUEST_10023: 'Прокачай Дар Стихий на 1 уровень',
  640. QUEST_10024: 'Повысь уровень любого артефакта один раз',
  641. QUEST_10025: 'Начни 1 Экспедицию',
  642. QUEST_10026: 'Начни 4 Экспедиции',
  643. QUEST_10027: 'Победи в 1 бою Турнира Стихий',
  644. QUEST_10028: 'Повысь уровень любого артефакта титанов',
  645. QUEST_10029: 'Открой сферу артефактов титанов',
  646. QUEST_10030: 'Улучши облик любого героя 1 раз',
  647. QUEST_10031: 'Победи в 6 боях Турнира Стихий',
  648. QUEST_10043: 'Начни или присоеденись к Приключению',
  649. QUEST_10044: 'Воспользуйся призывом питомцев 1 раз',
  650. QUEST_10046: 'Открой 3 сундука в Приключениях',
  651. QUEST_10047: 'Набери 150 очков активности в Гильдии',
  652. NOTHING_TO_DO: 'Нечего выполнять',
  653. YOU_CAN_COMPLETE: 'Можно выполнить квесты',
  654. BTN_DO_IT: 'Выполняй',
  655. NOT_QUEST_COMPLETED: 'Ни одного квеста не выполенно',
  656. COMPLETED_QUESTS: 'Выполнено квестов',
  657. /* everything button */
  658. ASSEMBLE_OUTLAND: 'Собрать Запределье',
  659. PASS_THE_TOWER: 'Пройти башню',
  660. CHECK_EXPEDITIONS: 'Проверить экспедиции',
  661. COMPLETE_TOE: 'Пройти Турнир Стихий',
  662. COMPLETE_DUNGEON: 'Пройти подземелье',
  663. COLLECT_MAIL: 'Собрать почту',
  664. COLLECT_MISC: 'Собрать всякую херню',
  665. COLLECT_MISC_TITLE: 'Собрать пасхалки, камни облика, ключи, монеты арены и Хрусталь души',
  666. COLLECT_QUEST_REWARDS: 'Собрать награды за квесты',
  667. MAKE_A_SYNC: 'Сделать синхронизацю',
  668.  
  669. RUN_FUNCTION: 'Выполнить следующие функции?',
  670. BTN_GO: 'Погнали!',
  671. PERFORMED: 'Выполняется',
  672. DONE: 'Выполнено',
  673. ERRORS_OCCURRES: 'Призошли ошибки при выполнении',
  674. COPY_ERROR: 'Скопировать в буфер информацию об ошибке',
  675. BTN_YES: 'Да',
  676. ALL_TASK_COMPLETED: 'Все задачи выполнены',
  677.  
  678. UNKNOWN: 'Неизвестно',
  679. ENTER_THE_PATH: 'Введите путь приключения через запятые или дефисы',
  680. START_ADVENTURE: 'Начать приключение по этому пути!',
  681. INCORRECT_WAY: 'Неверный путь в приключении: {from} -> {to}',
  682. BTN_CANCELED: 'Отменено',
  683. MUST_TWO_POINTS: 'Путь должен состоять минимум из 2х точек',
  684. MUST_ONLY_NUMBERS: 'Путь должен содержать только цифры и запятые',
  685. NOT_ON_AN_ADVENTURE: 'Вы не в приключении',
  686. YOU_IN_NOT_ON_THE_WAY: 'Указанный путь должен включать точку вашего положения',
  687. ATTEMPTS_NOT_ENOUGH: 'Ваших попыток не достаточно для завершения пути, продолжить?',
  688. YES_CONTINUE: 'Да, продолжай!',
  689. NOT_ENOUGH_AP: 'Попыток не достаточно',
  690. ATTEMPTS_ARE_OVER: 'Попытки закончились',
  691. MOVES: 'Ходы',
  692. BUFF_GET_ERROR: 'Ошибка при получении бафа',
  693. BATTLE_END_ERROR: 'Ошибка завершения боя',
  694. AUTOBOT: 'АвтоБой',
  695. FAILED_TO_WIN_AUTO: 'Не удалось победить в автобою',
  696. ERROR_OF_THE_BATTLE_COPY: 'Призошли ошибка в процессе прохождения боя<br>Скопировать ошибку в буфер обмена?',
  697. ERROR_DURING_THE_BATTLE: 'Ошибка в процессе прохождения боя',
  698. NO_CHANCE_WIN: 'Нет шансов победить в этом бою: 0/',
  699. LOST_HEROES: 'Вы победили, но потеряли одного или несколько героев!',
  700. VICTORY_IMPOSSIBLE: 'Победа не возможна, бъем на результат?',
  701. FIND_COEFF: 'Поиск коэффициента больше чем',
  702. BTN_PASS: 'ПРОПУСК',
  703. BRAWLS: 'Потасовки',
  704. BRAWLS_TITLE: 'Включает возможность автопотасовок',
  705. START_AUTO_BRAWLS: 'Запустить Автопотасовки?',
  706. LOSSES: 'Поражений',
  707. WINS: 'Побед',
  708. FIGHTS: 'Боев',
  709. STAGE: 'Стадия',
  710. DONT_HAVE_LIVES: 'У Вас нет жизней',
  711. LIVES: 'Жизни',
  712. SECRET_WEALTH_ALREADY: 'товар за Зелья питомцев уже куплен',
  713. SECRET_WEALTH_NOT_ENOUGH: 'Не достаточно Зелье Питомца, у Вас {available}, нужно {need}',
  714. SECRET_WEALTH_UPGRADE_NEW_PET: 'После покупки Зелье Питомца будет не достаточно для прокачки нового питомца',
  715. SECRET_WEALTH_PURCHASED: 'Куплено {count} {name}',
  716. SECRET_WEALTH_CANCELED: 'Тайное богатство: покупка отменена',
  717. SECRET_WEALTH_BUY: 'У вас {available} Зелье Питомца.<br>Вы хотите купить {countBuy} {name} за {price} Зелье Питомца?',
  718. DAILY_BONUS: 'Ежедневная награда',
  719. DO_DAILY_QUESTS: 'Сделать ежедневные квесты',
  720. ACTIONS: 'Действия',
  721. ACTIONS_TITLE: 'Диалоговое окно с различными действиями',
  722. OTHERS: 'Разное',
  723. OTHERS_TITLE: 'Диалоговое окно с дополнительными различными действиями',
  724. CHOOSE_ACTION: 'Выберите действие',
  725. OPEN_LOOTBOX: 'У Вас {lootBox} ящиков, откываем?',
  726. STAMINA: 'Энергия',
  727. BOXES_OVER: 'Ящики закончились',
  728. NO_BOXES: 'Нет ящиков',
  729. NO_MORE_ACTIVITY: 'Больше активности за предметы сегодня не получить',
  730. EXCHANGE_ITEMS: 'Обменять предметы на очки активности (не более {maxActive})?',
  731. GET_ACTIVITY: 'Получить активность',
  732. NOT_ENOUGH_ITEMS: 'Предметов недостаточно',
  733. ACTIVITY_RECEIVED: 'Получено активности',
  734. NO_PURCHASABLE_HERO_SOULS: 'Нет доступных для покупки душ героев',
  735. PURCHASED_HERO_SOULS: 'Куплено {countHeroSouls} душ героев',
  736. NOT_ENOUGH_EMERALDS_540: 'Недостаточно изюма, нужно 540 у Вас {currentStarMoney}',
  737. CHESTS_NOT_AVAILABLE: 'Сундуки не доступны',
  738. OUTLAND_CHESTS_RECEIVED: 'Получено сундуков Запределья',
  739. RAID_NOT_AVAILABLE: 'Рейд не доступен или сфер нет',
  740. RAID_ADVENTURE: 'Рейд {adventureId} приключения!',
  741. SOMETHING_WENT_WRONG: 'Что-то пошло не так',
  742. ADVENTURE_COMPLETED: 'Приключение {adventureId} пройдено {times} раз',
  743. CLAN_STAT_COPY: 'Клановая статистика скопирована в буфер обмена',
  744. GET_ENERGY: 'Получить энергию',
  745. GET_ENERGY_TITLE: 'Открывает платиновые шкатулки по одной до получения 250 энергии',
  746. ITEM_EXCHANGE: 'Обмен предметов',
  747. ITEM_EXCHANGE_TITLE: 'Обменивает предметы на указанное количество активности',
  748. BUY_SOULS: 'Купить души',
  749. BUY_SOULS_TITLE: 'Купить души героев из всех доступных магазинов',
  750. BUY_OUTLAND: 'Купить Запределье',
  751. BUY_OUTLAND_TITLE: 'Купить 9 сундуков в Запределье за 540 изумрудов',
  752. AUTO_RAID_ADVENTURE: 'Рейд приключения',
  753. AUTO_RAID_ADVENTURE_TITLE: 'Рейд приключения заданное количество раз',
  754. CLAN_STAT: 'Клановая статистика',
  755. CLAN_STAT_TITLE: 'Копирует клановую статистику в буфер обмена',
  756. BTN_AUTO_F5: 'Авто (F5)',
  757. BOSS_DAMAGE: 'Урон по боссу: ',
  758. NOTHING_BUY: 'Нечего покупать',
  759. LOTS_BOUGHT: 'За золото куплено {countBuy} лотов',
  760. BUY_FOR_GOLD: 'Скупить за золото',
  761. BUY_FOR_GOLD_TITLE: 'Скупить предметы за золото в Городской лавке и в магазине Камней Душ Питомцев',
  762. REWARDS_AND_MAIL: 'Награды и почта',
  763. REWARDS_AND_MAIL_TITLE: 'Собирает награды и почту',
  764. COLLECT_REWARDS_AND_MAIL: 'Собрано {countQuests} наград и {countMail} писем',
  765. TIMER_ALREADY: 'Таймер уже запущен',
  766. NO_ATTEMPTS_TIMER_START: 'Попыток нет, запущен таймер',
  767. EPIC_BRAWL_RESULT: '{i} Победы: {wins}/{attempts}, Монеты: {coins}, Серия: {progress}/{nextStage} [Закрыть]{end}',
  768. ATTEMPT_ENDED: '<br>Попытки закончились, запущен таймер',
  769. EPIC_BRAWL: 'Вселенская битва',
  770. EPIC_BRAWL_TITLE: 'Тратит попытки во Вселенской битве',
  771. RELOAD_GAME: 'Перезагрузить игру',
  772. TIMER: 'Таймер:',
  773. SHOW_ERRORS: 'Отображать ошибки',
  774. SHOW_ERRORS_TITLE: 'Отображать ошибки запросов к серверу',
  775. ERROR_MSG: 'Ошибка: {name}<br>{description}',
  776. EVENT_AUTO_BOSS: 'Максимальное количество боев для расчета:</br>{length} * {countTestBattle} = {maxCalcBattle}</br>Если у Вас слабый компьютер на это может потребоваться много времени, нажмите крестик для отмены.</br>Искать лучший пак из всех или первый подходящий?',
  777. BEST_SLOW: 'Лучший (медленее)',
  778. FIRST_FAST: 'Первый (быстрее)',
  779. FREEZE_INTERFACE: 'Идет расчет... <br> Интерфейс может зависнуть.',
  780. ERROR_F12: 'Ошибка, подробности в консоли (F12)',
  781. FAILED_FIND_WIN_PACK: 'Победный пак найти не удалось',
  782. BEST_PACK: 'Наилучший пак: ',
  783. BOSS_HAS_BEEN_DEF: 'Босс {bossLvl} побежден',
  784. NOT_ENOUGH_ATTEMPTS_BOSS: 'Для победы босса ${bossLvl} не хватило попыток, повторить?',
  785. BOSS_VICTORY_IMPOSSIBLE: 'По результатам прерасчета {battles} боев победу получить не удалось. Вы хотите продолжить поиск победного боя на реальных боях? <p style="color:red;">Использование этой функции может быть расценено как DDoS атака или HTTP-флуд и привести к перманентному бану</p>',
  786. BOSS_HAS_BEEN_DEF_TEXT: 'Босс {bossLvl} побежден за<br>{countBattle}/{countMaxBattle} попыток<br>(Сделайте синхронизацию или перезагрузите игру для обновления данных)',
  787. PLAYER_POS: 'Позиции игроков:',
  788. NY_GIFTS: 'Подарки',
  789. NY_GIFTS_TITLE: 'Открыть все новогодние подарки',
  790. NY_NO_GIFTS: 'Нет не полученных подарков',
  791. NY_GIFTS_COLLECTED: 'Собрано {count} подарков',
  792. CHANGE_MAP: 'Карта острова',
  793. CHANGE_MAP_TITLE: 'Сменить карту острова',
  794. SELECT_ISLAND_MAP: 'Выберите карту острова:',
  795. FIRST_MAP: 'Первая карта',
  796. SECOND_MAP: 'Вторая карта',
  797. SECRET_WEALTH_SHOP: 'Тайное богатство {name}: ',
  798. SHOPS: 'Магазины',
  799. SHOPS_DEFAULT: 'Стандартные',
  800. SHOPS_DEFAULT_TITLE: 'Стандартные магазины',
  801. SHOPS_LIST: 'Магазины {number}',
  802. SHOPS_LIST_TITLE: 'Список магазинов {number}',
  803. SHOPS_WARNING: 'Магазины<br><span style="color:red">Если Вы купите монеты магазинов потасовок за изумруды, то их надо использовать сразу, иначе после перезагрузки игры они пропадут!</span>',
  804. MINIONS_WARNING: 'Пачки героев для атаки приспешников неполные, продолжить?',
  805. FAST_SEASON: 'Быстрый сезон',
  806. FAST_SEASON_TITLE: 'Пропуск экрана с выбором карты в сезоне',
  807. GET_SOMETHING: 'Получить кое-что',
  808. GET_SOMETHING_TITLE: 'Собирает все кое-что',
  809. GET_ALL_SOMETHING: 'Собрать все кое-что?',
  810. NO_SOMETHING_DATA: 'Нет кое-каких данных',
  811. COLLECTED_SOMETHING: 'Собрано: {count}',
  812. SET_NUMBER_LEVELS: 'Указать колличество уровней:',
  813. NOT_ENOUGH_RESOURECES: 'Не хватает ресурсов',
  814. IMPROVED_LEVELS: 'Улучшено уровней: {count}',
  815. ARTIFACTS_IMPROVEMENT: 'Улучшение артефактов',
  816. ARTIFACTS_IMPROVEMENT_TITLE: 'Улучшает указанное количество самых дешевых артефактов героев',
  817. SKINS_IMPROVEMENT: 'Улучшение обликов',
  818. SKINS_IMPROVEMENT_TITLE: 'Улучшает указанное количество самых дешевых обликов героев',
  819. }
  820. }
  821.  
  822. function getLang() {
  823. let lang = '';
  824. if (typeof NXFlashVars !== 'undefined') {
  825. lang = NXFlashVars.interface_lang
  826. }
  827. if (!lang) {
  828. lang = (navigator.language || navigator.userLanguage).substr(0, 2);
  829. }
  830. if (lang == 'ru') {
  831. return lang;
  832. }
  833. return 'en';
  834. }
  835.  
  836. this.I18N = function (constant, replace) {
  837. const selectLang = getLang();
  838. if (constant && constant in i18nLangData[selectLang]) {
  839. const result = i18nLangData[selectLang][constant];
  840. if (replace) {
  841. return result.sprintf(replace);
  842. }
  843. return result;
  844. }
  845. return `% ${constant} %`;
  846. };
  847.  
  848. String.prototype.sprintf = String.prototype.sprintf ||
  849. function () {
  850. "use strict";
  851. var str = this.toString();
  852. if (arguments.length) {
  853. var t = typeof arguments[0];
  854. var key;
  855. var args = ("string" === t || "number" === t) ?
  856. Array.prototype.slice.call(arguments)
  857. : arguments[0];
  858.  
  859. for (key in args) {
  860. str = str.replace(new RegExp("\\{" + key + "\\}", "gi"), args[key]);
  861. }
  862. }
  863.  
  864. return str;
  865. };
  866.  
  867. /**
  868. * Checkboxes
  869. *
  870. * Чекбоксы
  871. */
  872. const checkboxes = {
  873. passBattle: {
  874. label: I18N('SKIP_FIGHTS'),
  875. cbox: null,
  876. title: I18N('SKIP_FIGHTS_TITLE'),
  877. default: false
  878. },
  879. /*
  880. endlessCards: {
  881. label: I18N('ENDLESS_CARDS'),
  882. cbox: null,
  883. title: I18N('ENDLESS_CARDS_TITLE'),
  884. default: true
  885. },
  886. */
  887. sendExpedition: {
  888. label: I18N('AUTO_EXPEDITION'),
  889. cbox: null,
  890. title: I18N('AUTO_EXPEDITION_TITLE'),
  891. default: true
  892. },
  893. cancelBattle: {
  894. label: I18N('CANCEL_FIGHT'),
  895. cbox: null,
  896. title: I18N('CANCEL_FIGHT_TITLE'),
  897. default: false,
  898. },
  899. preCalcBattle: {
  900. label: I18N('BATTLE_RECALCULATION'),
  901. cbox: null,
  902. title: I18N('BATTLE_RECALCULATION_TITLE'),
  903. default: false
  904. },
  905. countControl: {
  906. label: I18N('QUANTITY_CONTROL'),
  907. cbox: null,
  908. title: I18N('QUANTITY_CONTROL_TITLE'),
  909. default: true
  910. },
  911. repeatMission: {
  912. label: I18N('REPEAT_CAMPAIGN'),
  913. cbox: null,
  914. title: I18N('REPEAT_CAMPAIGN_TITLE'),
  915. default: false
  916. },
  917. noOfferDonat: {
  918. label: I18N('DISABLE_DONAT'),
  919. cbox: null,
  920. title: I18N('DISABLE_DONAT_TITLE'),
  921. /**
  922. * A crutch to get the field before getting the character id
  923. *
  924. * Костыль чтоб получать поле до получения id персонажа
  925. */
  926. default: (() => {
  927. $result = false;
  928. try {
  929. $result = JSON.parse(localStorage[GM_info.script.name + ':noOfferDonat'])
  930. } catch(e) {
  931. $result = false;
  932. }
  933. return $result || false;
  934. })(),
  935. },
  936. dailyQuests: {
  937. label: I18N('DAILY_QUESTS'),
  938. cbox: null,
  939. title: I18N('DAILY_QUESTS_TITLE'),
  940. default: false
  941. },
  942. secretWealth: {
  943. label: I18N('SECRET_WEALTH'),
  944. cbox: null,
  945. title: I18N('SECRET_WEALTH_CHECKBOX'),
  946. default: false
  947. },
  948. // Потасовки
  949. /*
  950. autoBrawls: {
  951. label: I18N('BRAWLS'),
  952. cbox: null,
  953. title: I18N('BRAWLS_TITLE'),
  954. default: (() => {
  955. $result = false;
  956. try {
  957. $result = JSON.parse(localStorage[GM_info.script.name + ':autoBrawls'])
  958. } catch (e) {
  959. $result = false;
  960. }
  961. return $result || false;
  962. })(),
  963. },
  964. */
  965. /*
  966. getAnswer: {
  967. label: I18N('AUTO_QUIZ'),
  968. cbox: null,
  969. title: I18N('AUTO_QUIZ_TITLE'),
  970. default: false
  971. },
  972. */
  973. showErrors: {
  974. label: I18N('SHOW_ERRORS'),
  975. cbox: null,
  976. title: I18N('SHOW_ERRORS_TITLE'),
  977. default: true
  978. },
  979. buyForGold: {
  980. label: I18N('BUY_FOR_GOLD'),
  981. cbox: null,
  982. title: I18N('BUY_FOR_GOLD_TITLE'),
  983. default: false
  984. },
  985. hideServers: {
  986. label: I18N('HIDE_SERVERS'),
  987. cbox: null,
  988. title: I18N('HIDE_SERVERS_TITLE'),
  989. default: false
  990. },
  991. fastSeason: {
  992. label: I18N('FAST_SEASON'),
  993. cbox: null,
  994. title: I18N('FAST_SEASON_TITLE'),
  995. default: false
  996. },
  997. };
  998. /**
  999. * Get checkbox state
  1000. *
  1001. * Получить состояние чекбокса
  1002. */
  1003. function isChecked(checkBox) {
  1004. if (!(checkBox in checkboxes)) {
  1005. return false;
  1006. }
  1007. return checkboxes[checkBox].cbox?.checked;
  1008. }
  1009. /**
  1010. * Input fields
  1011. *
  1012. * Поля ввода
  1013. */
  1014. const inputs = {
  1015. countTitanit: {
  1016. input: null,
  1017. title: I18N('HOW_MUCH_TITANITE'),
  1018. default: 150,
  1019. },
  1020. speedBattle: {
  1021. input: null,
  1022. title: I18N('COMBAT_SPEED'),
  1023. default: 5,
  1024. },
  1025. countTestBattle: {
  1026. input: null,
  1027. title: I18N('NUMBER_OF_TEST'),
  1028. default: 10,
  1029. },
  1030. countAutoBattle: {
  1031. input: null,
  1032. title: I18N('NUMBER_OF_AUTO_BATTLE'),
  1033. default: 10,
  1034. }
  1035. }
  1036. /**
  1037. * Checks the checkbox
  1038. *
  1039. * Поплучить данные поля ввода
  1040. */
  1041. function getInput(inputName) {
  1042. return inputs[inputName].input.value;
  1043. }
  1044. /**
  1045. * Button List
  1046. *
  1047. * Список кнопочек
  1048. */
  1049. const buttons = {
  1050. getOutland: {
  1051. name: I18N('TO_DO_EVERYTHING'),
  1052. title: I18N('TO_DO_EVERYTHING_TITLE'),
  1053. func: testDoYourBest,
  1054. },
  1055. doActions: {
  1056. name: I18N('ACTIONS'),
  1057. title: I18N('ACTIONS_TITLE'),
  1058. func: async function () {
  1059. const popupButtons = [
  1060. {
  1061. msg: I18N('OUTLAND'),
  1062. result: function () {
  1063. confShow(`${I18N('RUN_SCRIPT')} ${I18N('OUTLAND')}?`, getOutland);
  1064. },
  1065. title: I18N('OUTLAND_TITLE'),
  1066. },
  1067. {
  1068. msg: I18N('TOWER'),
  1069. result: function () {
  1070. confShow(`${I18N('RUN_SCRIPT')} ${I18N('TOWER')}?`, testTower);
  1071. },
  1072. title: I18N('TOWER_TITLE'),
  1073. },
  1074. {
  1075. msg: I18N('EXPEDITIONS'),
  1076. result: function () {
  1077. confShow(`${I18N('RUN_SCRIPT')} ${I18N('EXPEDITIONS')}?`, checkExpedition);
  1078. },
  1079. title: I18N('EXPEDITIONS_TITLE'),
  1080. },
  1081. {
  1082. msg: I18N('MINIONS'),
  1083. result: function () {
  1084. confShow(`${I18N('RUN_SCRIPT')} ${I18N('MINIONS')}?`, testRaidNodes);
  1085. },
  1086. title: I18N('MINIONS_TITLE'),
  1087. },
  1088. {
  1089. msg: I18N('ESTER_EGGS'),
  1090. result: function () {
  1091. confShow(`${I18N('RUN_SCRIPT')} ${I18N('ESTER_EGGS')}?`, offerFarmAllReward);
  1092. },
  1093. title: I18N('ESTER_EGGS_TITLE'),
  1094. },
  1095. {
  1096. msg: I18N('STORM'),
  1097. result: function () {
  1098. testAdventure('solo');
  1099. },
  1100. title: I18N('STORM_TITLE'),
  1101. },
  1102. {
  1103. msg: I18N('REWARDS'),
  1104. result: function () {
  1105. confShow(`${I18N('RUN_SCRIPT')} ${I18N('REWARDS')}?`, questAllFarm);
  1106. },
  1107. title: I18N('REWARDS_TITLE'),
  1108. },
  1109. {
  1110. msg: I18N('MAIL'),
  1111. result: function () {
  1112. confShow(`${I18N('RUN_SCRIPT')} ${I18N('MAIL')}?`, mailGetAll);
  1113. },
  1114. title: I18N('MAIL_TITLE'),
  1115. },
  1116. {
  1117. msg: I18N('SEER'),
  1118. result: function () {
  1119. confShow(`${I18N('RUN_SCRIPT')} ${I18N('SEER')}?`, rollAscension);
  1120. },
  1121. title: I18N('SEER_TITLE'),
  1122. },
  1123. /*
  1124. {
  1125. msg: I18N('NY_GIFTS'),
  1126. result: getGiftNewYear,
  1127. title: I18N('NY_GIFTS_TITLE'),
  1128. },
  1129. */
  1130. ];
  1131. popupButtons.push({ result: false, isClose: true })
  1132. const answer = await popup.confirm(`${I18N('CHOOSE_ACTION')}:`, popupButtons);
  1133. if (typeof answer === 'function') {
  1134. answer();
  1135. }
  1136. }
  1137. },
  1138. doOthers: {
  1139. name: I18N('OTHERS'),
  1140. title: I18N('OTHERS_TITLE'),
  1141. func: async function () {
  1142. const popupButtons = [
  1143. {
  1144. msg: I18N('GET_ENERGY'),
  1145. result: farmStamina,
  1146. title: I18N('GET_ENERGY_TITLE'),
  1147. },
  1148. {
  1149. msg: I18N('ITEM_EXCHANGE'),
  1150. result: fillActive,
  1151. title: I18N('ITEM_EXCHANGE_TITLE'),
  1152. },
  1153. {
  1154. msg: I18N('BUY_SOULS'),
  1155. result: function () {
  1156. confShow(`${I18N('RUN_SCRIPT')} ${I18N('BUY_SOULS')}?`, buyHeroFragments);
  1157. },
  1158. title: I18N('BUY_SOULS_TITLE'),
  1159. },
  1160. {
  1161. msg: I18N('BUY_FOR_GOLD'),
  1162. result: function () {
  1163. confShow(`${I18N('RUN_SCRIPT')} ${I18N('BUY_FOR_GOLD')}?`, buyInStoreForGold);
  1164. },
  1165. title: I18N('BUY_FOR_GOLD_TITLE'),
  1166. },
  1167. {
  1168. msg: I18N('BUY_OUTLAND'),
  1169. result: function () {
  1170. confShow(I18N('BUY_OUTLAND_TITLE') + '?', bossOpenChestPay);
  1171. },
  1172. title: I18N('BUY_OUTLAND_TITLE'),
  1173. },
  1174. {
  1175. msg: I18N('AUTO_RAID_ADVENTURE'),
  1176. result: autoRaidAdventure,
  1177. title: I18N('AUTO_RAID_ADVENTURE_TITLE'),
  1178. },
  1179. {
  1180. msg: I18N('CLAN_STAT'),
  1181. result: clanStatistic,
  1182. title: I18N('CLAN_STAT_TITLE'),
  1183. },
  1184. /*
  1185. {
  1186. msg: I18N('SECRET_WEALTH'),
  1187. result: buyWithPetExperience,
  1188. title: I18N('SECRET_WEALTH_TITLE'),
  1189. },
  1190. */
  1191. {
  1192. msg: I18N('EPIC_BRAWL'),
  1193. result: async function () {
  1194. confShow(`${I18N('RUN_SCRIPT')} ${I18N('EPIC_BRAWL')}?`, () => {
  1195. const brawl = new epicBrawl;
  1196. brawl.start();
  1197. });
  1198. },
  1199. title: I18N('EPIC_BRAWL_TITLE'),
  1200. },
  1201. {
  1202. msg: I18N('ARTIFACTS_IMPROVEMENT'),
  1203. result: updateArtifacts,
  1204. title: I18N('ARTIFACTS_IMPROVEMENT_TITLE'),
  1205. },
  1206. {
  1207. msg: I18N('SKINS_IMPROVEMENT'),
  1208. result: updateSkins,
  1209. title: I18N('SKINS_IMPROVEMENT_TITLE'),
  1210. },
  1211. {
  1212. msg: I18N('CHANGE_MAP'),
  1213. result: async function () {
  1214. const result = await popup.confirm(I18N('SELECT_ISLAND_MAP'), [
  1215. { msg: I18N('FIRST_MAP'), result: 1 },
  1216. { msg: I18N('SECOND_MAP'), result: 2 },
  1217. { result: false, isClose: true },
  1218. ]
  1219. );
  1220. if (result) {
  1221. cheats.changeIslandMap(result);
  1222. }
  1223. },
  1224. title: I18N('CHANGE_MAP_TITLE'),
  1225. },
  1226. {
  1227. msg: I18N('SHOPS'),
  1228. result: async function () {
  1229. const shopButtons = [{
  1230. msg: I18N('SHOPS_DEFAULT'),
  1231. result: function () {
  1232. cheats.goDefaultShops();
  1233. },
  1234. title: I18N('SHOPS_DEFAULT_TITLE'),
  1235. }, {
  1236. msg: I18N('SECRET_WEALTH'),
  1237. result: function () {
  1238. cheats.goSecretWealthShops();
  1239. },
  1240. title: I18N('SECRET_WEALTH'),
  1241. }];
  1242. for (let i = 0; i < 4; i++) {
  1243. const number = i + 1;
  1244. shopButtons.push({
  1245. msg: I18N('SHOPS_LIST', { number }),
  1246. result: function () {
  1247. cheats.goCustomShops(i);
  1248. },
  1249. title: I18N('SHOPS_LIST_TITLE', { number }),
  1250. })
  1251. }
  1252. shopButtons.push({ result: false, isClose: true })
  1253. const answer = await popup.confirm(I18N('SHOPS_WARNING'), shopButtons);
  1254. if (typeof answer === 'function') {
  1255. answer();
  1256. }
  1257. },
  1258. title: I18N('SHOPS'),
  1259. },
  1260. ];
  1261. if (getSaveVal('argsDataForSomething', false)) {
  1262. popupButtons.push({
  1263. msg: I18N('GET_SOMETHING'),
  1264. result: function () {
  1265. getSomething();
  1266. },
  1267. title: I18N('GET_SOMETHING_TITLE'),
  1268. })
  1269. }
  1270.  
  1271. popupButtons.push({ result: false, isClose: true })
  1272. const answer = await popup.confirm(`${I18N('CHOOSE_ACTION')}:`, popupButtons);
  1273. if (typeof answer === 'function') {
  1274. answer();
  1275. }
  1276. }
  1277. },
  1278. testTitanArena: {
  1279. name: I18N('TITAN_ARENA'),
  1280. title: I18N('TITAN_ARENA_TITLE'),
  1281. func: function () {
  1282. confShow(`${I18N('RUN_SCRIPT')} ${I18N('TITAN_ARENA')}?`, testTitanArena);
  1283. },
  1284. },
  1285. testDungeon: {
  1286. name: I18N('DUNGEON'),
  1287. title: I18N('DUNGEON_TITLE'),
  1288. func: function () {
  1289. confShow(`${I18N('RUN_SCRIPT')} ${I18N('DUNGEON')}?`, testDungeon);
  1290. },
  1291. },
  1292. /*
  1293. autoBoss: {
  1294. name: 'autoBoss',
  1295. title: 'autoBoss',
  1296. func: function () {
  1297. (new executeEventAutoBoss()).start()
  1298. },
  1299. },
  1300. */
  1301. /*
  1302. // Архидемон
  1303. bossRatingEvent: {
  1304. name: I18N('ARCHDEMON'),
  1305. title: I18N('ARCHDEMON_TITLE'),
  1306. func: function () {
  1307. confShow(`${I18N('RUN_SCRIPT')} ${I18N('ARCHDEMON')}?`, bossRatingEvent);
  1308. },
  1309. },
  1310. */
  1311. /*
  1312. // Горнило душ
  1313. bossRatingEvent: {
  1314. name: I18N('ARCHDEMON'),
  1315. title: I18N('ARCHDEMON_TITLE'),
  1316. func: function () {
  1317. confShow(`${I18N('RUN_SCRIPT')} ${I18N('ARCHDEMON')}?`, bossRatingEventSouls);
  1318. },
  1319. },
  1320. */
  1321. rewardsAndMailFarm: {
  1322. name: I18N('REWARDS_AND_MAIL'),
  1323. title: I18N('REWARDS_AND_MAIL_TITLE'),
  1324. func: function () {
  1325. confShow(`${I18N('RUN_SCRIPT')} ${I18N('REWARDS_AND_MAIL')}?`, rewardsAndMailFarm);
  1326. },
  1327. },
  1328. testAdventure: {
  1329. name: I18N('ADVENTURE'),
  1330. title: I18N('ADVENTURE_TITLE'),
  1331. func: () => {
  1332. testAdventure();
  1333. },
  1334. },
  1335. goToSanctuary: {
  1336. name: I18N('SANCTUARY'),
  1337. title: I18N('SANCTUARY_TITLE'),
  1338. func: cheats.goSanctuary,
  1339. },
  1340. goToClanWar: {
  1341. name: I18N('GUILD_WAR'),
  1342. title: I18N('GUILD_WAR_TITLE'),
  1343. func: cheats.goClanWar,
  1344. },
  1345. dailyQuests: {
  1346. name: I18N('DAILY_QUESTS'),
  1347. title: I18N('DAILY_QUESTS_TITLE'),
  1348. func: async function () {
  1349. const quests = new dailyQuests(() => { }, () => { });
  1350. await quests.autoInit();
  1351. quests.start();
  1352. },
  1353. },
  1354. newDay: {
  1355. name: I18N('SYNC'),
  1356. title: I18N('SYNC_TITLE'),
  1357. func: function () {
  1358. confShow(`${I18N('RUN_SCRIPT')} ${I18N('SYNC')}?`, cheats.refreshGame);
  1359. },
  1360. },
  1361. }
  1362. /**
  1363. * Display buttons
  1364. *
  1365. * Вывести кнопочки
  1366. */
  1367. function addControlButtons() {
  1368. for (let name in buttons) {
  1369. button = buttons[name];
  1370. button['button'] = scriptMenu.addButton(button.name, button.func, button.title);
  1371. }
  1372. }
  1373. /**
  1374. * Adds links
  1375. *
  1376. * Добавляет ссылки
  1377. */
  1378. function addBottomUrls() {
  1379. scriptMenu.addHeader(I18N('BOTTOM_URLS'));
  1380. }
  1381. /**
  1382. * Stop repetition of the mission
  1383. *
  1384. * Остановить повтор миссии
  1385. */
  1386. let isStopSendMission = false;
  1387. /**
  1388. * There is a repetition of the mission
  1389. *
  1390. * Идет повтор миссии
  1391. */
  1392. let isSendsMission = false;
  1393. /**
  1394. * Data on the past mission
  1395. *
  1396. * Данные о прошедшей мисии
  1397. */
  1398. let lastMissionStart = {}
  1399.  
  1400. /**
  1401. * Data on the past attack on the boss
  1402. *
  1403. * Данные о прошедшей атаке на босса
  1404. */
  1405. let lastBossBattle = {}
  1406. /**
  1407. * Data for calculating the last battle with the boss
  1408. *
  1409. * Данные для расчете последнего боя с боссом
  1410. */
  1411. let lastBossBattleInfo = null;
  1412. /**
  1413. * Ability to cancel the battle in Asgard
  1414. *
  1415. * Возможность отменить бой в Астгарде
  1416. */
  1417. let isCancalBossBattle = true;
  1418. /**
  1419. * Information about the last battle
  1420. *
  1421. * Данные о прошедшей битве
  1422. */
  1423. let lastBattleArg = {}
  1424. /**
  1425. * The name of the function of the beginning of the battle
  1426. *
  1427. * Имя функции начала боя
  1428. */
  1429. let nameFuncStartBattle = '';
  1430. /**
  1431. * The name of the function of the end of the battle
  1432. *
  1433. * Имя функции конца боя
  1434. */
  1435. let nameFuncEndBattle = '';
  1436. /**
  1437. * Data for calculating the last battle
  1438. *
  1439. * Данные для расчета последнего боя
  1440. */
  1441. let lastBattleInfo = null;
  1442. /**
  1443. * The ability to cancel the battle
  1444. *
  1445. * Возможность отменить бой
  1446. */
  1447. let isCancalBattle = true;
  1448.  
  1449. /**
  1450. * Certificator of the last open nesting doll
  1451. *
  1452. * Идетификатор последней открытой матрешки
  1453. */
  1454. let lastRussianDollId = null;
  1455. /**
  1456. * Cancel the training guide
  1457. *
  1458. * Отменить обучающее руководство
  1459. */
  1460. this.isCanceledTutorial = false;
  1461.  
  1462. /**
  1463. * Data from the last question of the quiz
  1464. *
  1465. * Данные последнего вопроса викторины
  1466. */
  1467. let lastQuestion = null;
  1468. /**
  1469. * Answer to the last question of the quiz
  1470. *
  1471. * Ответ на последний вопрос викторины
  1472. */
  1473. let lastAnswer = null;
  1474. /**
  1475. * Flag for opening keys or titan artifact spheres
  1476. *
  1477. * Флаг открытия ключей или сфер артефактов титанов
  1478. */
  1479. let artifactChestOpen = false;
  1480. /**
  1481. * The name of the function to open keys or orbs of titan artifacts
  1482. *
  1483. * Имя функции открытия ключей или сфер артефактов титанов
  1484. */
  1485. let artifactChestOpenCallName = '';
  1486. let correctShowOpenArtifact = 0;
  1487. /**
  1488. * Data for the last battle in the dungeon
  1489. * (Fix endless cards)
  1490. *
  1491. * Данные для последнего боя в подземке
  1492. * (Исправление бесконечных карт)
  1493. */
  1494. let lastDungeonBattleData = null;
  1495. /**
  1496. * Start time of the last battle in the dungeon
  1497. *
  1498. * Время начала последнего боя в подземелье
  1499. */
  1500. let lastDungeonBattleStart = 0;
  1501. /**
  1502. * Subscription end time
  1503. *
  1504. * Время окончания подписки
  1505. */
  1506. let subEndTime = 0;
  1507. /**
  1508. * Number of prediction cards
  1509. *
  1510. * Количество карт предсказаний
  1511. */
  1512. let countPredictionCard = 0;
  1513.  
  1514. /**
  1515. * Brawl pack
  1516. *
  1517. * Пачка для потасовок
  1518. */
  1519. let brawlsPack = null;
  1520. /**
  1521. * Autobrawl started
  1522. *
  1523. * Автопотасовка запущена
  1524. */
  1525. let isBrawlsAutoStart = false;
  1526. /**
  1527. * Copies the text to the clipboard
  1528. *
  1529. * Копирует тест в буфер обмена
  1530. * @param {*} text copied text // копируемый текст
  1531. */
  1532. function copyText(text) {
  1533. let copyTextarea = document.createElement("textarea");
  1534. copyTextarea.style.opacity = "0";
  1535. copyTextarea.textContent = text;
  1536. document.body.appendChild(copyTextarea);
  1537. copyTextarea.select();
  1538. document.execCommand("copy");
  1539. document.body.removeChild(copyTextarea);
  1540. delete copyTextarea;
  1541. }
  1542. /**
  1543. * Returns the history of requests
  1544. *
  1545. * Возвращает историю запросов
  1546. */
  1547. this.getRequestHistory = function() {
  1548. return requestHistory;
  1549. }
  1550. /**
  1551. * Generates a random integer from min to max
  1552. *
  1553. * Гененирует случайное целое число от min до max
  1554. */
  1555. const random = function (min, max) {
  1556. return Math.floor(Math.random() * (max - min + 1) + min);
  1557. }
  1558. /**
  1559. * Clearing the request history
  1560. *
  1561. * Очистка истоии запросов
  1562. */
  1563. setInterval(function () {
  1564. let now = Date.now();
  1565. for (let i in requestHistory) {
  1566. if (now - i > 300000) {
  1567. delete requestHistory[i];
  1568. }
  1569. }
  1570. }, 300000);
  1571. /**
  1572. * DOM Loading Event page
  1573. *
  1574. * Событие загрузки DOM дерева страницы
  1575. */
  1576. document.addEventListener("DOMContentLoaded", () => {
  1577. /**
  1578. * Create the script interface
  1579. *
  1580. * Создание интерфеса скрипта
  1581. */
  1582. createInterface();
  1583. });
  1584. /**
  1585. * Gift codes collecting and sending codes
  1586. *
  1587. * Сбор и отправка кодов подарков
  1588. */
  1589. function sendCodes() {
  1590. let codes = [], count = 0;
  1591. if (!localStorage['giftSendIds']) {
  1592. localStorage['giftSendIds'] = '';
  1593. }
  1594. document.querySelectorAll('a[target="_blank"]').forEach(e => {
  1595. let url = e?.href;
  1596. if (!url) return;
  1597. url = new URL(url);
  1598. let giftId = url.searchParams.get('gift_id');
  1599. if (!giftId || localStorage['giftSendIds'].includes(giftId)) return;
  1600. localStorage['giftSendIds'] += ';' + giftId;
  1601. codes.push(giftId);
  1602. count++;
  1603. });
  1604.  
  1605. if (codes.length) {
  1606. localStorage['giftSendIds'] = localStorage['giftSendIds'].split(';').splice(-50).join(';');
  1607. sendGiftsCodes(codes);
  1608. }
  1609.  
  1610. if (!count) {
  1611. setTimeout(sendCodes, 2000);
  1612. }
  1613. }
  1614. /**
  1615. * Checking sent codes
  1616. *
  1617. * Проверка отправленных кодов
  1618. */
  1619. function checkSendGifts() {
  1620. if (!freebieCheckInfo) {
  1621. return;
  1622. }
  1623.  
  1624. let giftId = freebieCheckInfo.args.giftId;
  1625. let valName = 'giftSendIds_' + userInfo.id;
  1626. localStorage[valName] = localStorage[valName] ?? '';
  1627. if (!localStorage[valName].includes(giftId)) {
  1628. localStorage[valName] += ';' + giftId;
  1629. sendGiftsCodes([giftId]);
  1630. }
  1631. }
  1632. /**
  1633. * Sending codes
  1634. *
  1635. * Отправка кодов
  1636. */
  1637. function sendGiftsCodes(codes) {
  1638. fetch('https://zingery.ru/heroes/setGifts.php', {
  1639. method: 'POST',
  1640. body: JSON.stringify(codes)
  1641. }).then(
  1642. response => response.json()
  1643. ).then(
  1644. data => {
  1645. if (data.result) {
  1646. console.log(I18N('GIFTS_SENT'));
  1647. }
  1648. }
  1649. )
  1650. }
  1651. /**
  1652. * Displays the dialog box
  1653. *
  1654. * Отображает диалоговое окно
  1655. */
  1656. function confShow(message, yesCallback, noCallback) {
  1657. let buts = [];
  1658. message = message || I18N('DO_YOU_WANT');
  1659. noCallback = noCallback || (() => {});
  1660. if (yesCallback) {
  1661. buts = [
  1662. { msg: I18N('BTN_RUN'), result: true},
  1663. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true},
  1664. ]
  1665. } else {
  1666. yesCallback = () => {};
  1667. buts = [
  1668. { msg: I18N('BTN_OK'), result: true},
  1669. ];
  1670. }
  1671. popup.confirm(message, buts).then((e) => {
  1672. // dialogPromice = null;
  1673. if (e) {
  1674. yesCallback();
  1675. } else {
  1676. noCallback();
  1677. }
  1678. });
  1679. }
  1680. /**
  1681. * Overriding/Proxying the Ajax Request Creation Method
  1682. *
  1683. * Переопределяем/проксируем метод создания Ajax запроса
  1684. */
  1685. XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
  1686. this.uniqid = Date.now();
  1687. this.errorRequest = false;
  1688. if (method == 'POST' && url.includes('.nextersglobal.com/api/') && /api\/$/.test(url)) {
  1689. if (!apiUrl) {
  1690. apiUrl = url;
  1691. const socialInfo = /heroes-(.+?)\./.exec(apiUrl);
  1692. console.log(socialInfo);
  1693. }
  1694. requestHistory[this.uniqid] = {
  1695. method,
  1696. url,
  1697. error: [],
  1698. headers: {},
  1699. request: null,
  1700. response: null,
  1701. signature: [],
  1702. calls: {},
  1703. };
  1704. } else if (method == 'POST' && url.includes('error.nextersglobal.com/client/')) {
  1705. this.errorRequest = true;
  1706. }
  1707. return original.open.call(this, method, url, async, user, password);
  1708. };
  1709. /**
  1710. * Overriding/Proxying the header setting method for the AJAX request
  1711. *
  1712. * Переопределяем/проксируем метод установки заголовков для AJAX запроса
  1713. */
  1714. XMLHttpRequest.prototype.setRequestHeader = function (name, value, check) {
  1715. if (this.uniqid in requestHistory) {
  1716. requestHistory[this.uniqid].headers[name] = value;
  1717. } else {
  1718. check = true;
  1719. }
  1720.  
  1721. if (name == 'X-Auth-Signature') {
  1722. requestHistory[this.uniqid].signature.push(value);
  1723. if (!check) {
  1724. return;
  1725. }
  1726. }
  1727.  
  1728. return original.setRequestHeader.call(this, name, value);
  1729. };
  1730. /**
  1731. * Overriding/Proxying the AJAX Request Sending Method
  1732. *
  1733. * Переопределяем/проксируем метод отправки AJAX запроса
  1734. */
  1735. XMLHttpRequest.prototype.send = async function (sourceData) {
  1736. if (this.uniqid in requestHistory) {
  1737. let tempData = null;
  1738. if (getClass(sourceData) == "ArrayBuffer") {
  1739. tempData = decoder.decode(sourceData);
  1740. } else {
  1741. tempData = sourceData;
  1742. }
  1743. requestHistory[this.uniqid].request = tempData;
  1744. let headers = requestHistory[this.uniqid].headers;
  1745. lastHeaders = Object.assign({}, headers);
  1746. /**
  1747. * Game loading event
  1748. *
  1749. * Событие загрузки игры
  1750. */
  1751. if (headers["X-Request-Id"] > 2 && !isLoadGame) {
  1752. isLoadGame = true;
  1753. await lib.load();
  1754. addControls();
  1755. addControlButtons();
  1756. addBottomUrls();
  1757.  
  1758. if (isChecked('sendExpedition')) {
  1759. checkExpedition();
  1760. }
  1761.  
  1762. checkSendGifts();
  1763. getAutoGifts();
  1764.  
  1765. cheats.activateHacks();
  1766. justInfo();
  1767. if (isChecked('dailyQuests')) {
  1768. testDailyQuests();
  1769. }
  1770.  
  1771. if (isChecked('secretWealth')) {
  1772. buyWithPetExperienceAuto();
  1773. }
  1774.  
  1775. if (isChecked('buyForGold')) {
  1776. buyInStoreForGold();
  1777. }
  1778. }
  1779. /**
  1780. * Outgoing request data processing
  1781. *
  1782. * Обработка данных исходящего запроса
  1783. */
  1784. sourceData = await checkChangeSend.call(this, sourceData, tempData);
  1785. /**
  1786. * Handling incoming request data
  1787. *
  1788. * Обработка данных входящего запроса
  1789. */
  1790. const oldReady = this.onreadystatechange;
  1791. this.onreadystatechange = async function (e) {
  1792. if(this.readyState == 4 && this.status == 200) {
  1793. isTextResponse = this.responseType === "text" || this.responseType === "";
  1794. let response = isTextResponse ? this.responseText : this.response;
  1795. requestHistory[this.uniqid].response = response;
  1796. /**
  1797. * Replacing incoming request data
  1798. *
  1799. * Заменна данных входящего запроса
  1800. */
  1801. if (isTextResponse) {
  1802. await checkChangeResponse.call(this, response);
  1803. }
  1804. /**
  1805. * A function to run after the request is executed
  1806. *
  1807. * Функция запускаемая после выполения запроса
  1808. */
  1809. if (typeof this.onReadySuccess == 'function') {
  1810. setTimeout(this.onReadySuccess, 500);
  1811. }
  1812. }
  1813. if (oldReady) {
  1814. return oldReady.apply(this, arguments);
  1815. }
  1816. }
  1817. }
  1818. if (this.errorRequest) {
  1819. const oldReady = this.onreadystatechange;
  1820. this.onreadystatechange = function () {
  1821. Object.defineProperty(this, 'status', {
  1822. writable: true
  1823. });
  1824. this.status = 200;
  1825. Object.defineProperty(this, 'readyState', {
  1826. writable: true
  1827. });
  1828. this.readyState = 4;
  1829. Object.defineProperty(this, 'responseText', {
  1830. writable: true
  1831. });
  1832. this.responseText = JSON.stringify({
  1833. "result": true
  1834. });
  1835. return oldReady.apply(this, arguments);
  1836. }
  1837. this.onreadystatechange();
  1838. } else {
  1839. try {
  1840. return original.send.call(this, sourceData);
  1841. } catch(e) {
  1842. debugger;
  1843. }
  1844. }
  1845. };
  1846. /**
  1847. * Processing and substitution of outgoing data
  1848. *
  1849. * Обработка и подмена исходящих данных
  1850. */
  1851. async function checkChangeSend(sourceData, tempData) {
  1852. try {
  1853. /**
  1854. * A function that replaces battle data with incorrect ones to cancel combatя
  1855. *
  1856. * Функция заменяющая данные боя на неверные для отмены боя
  1857. */
  1858. const fixBattle = function (heroes) {
  1859. for (const ids in heroes) {
  1860. hero = heroes[ids];
  1861. hero.energy = random(1, 999);
  1862. if (hero.hp > 0) {
  1863. hero.hp = random(1, hero.hp);
  1864. }
  1865. }
  1866. }
  1867. /**
  1868. * Dialog window 2
  1869. *
  1870. * Диалоговое окно 2
  1871. */
  1872. const showMsg = async function (msg, ansF, ansS) {
  1873. if (typeof popup == 'object') {
  1874. return await popup.confirm(msg, [
  1875. {msg: ansF, result: false},
  1876. {msg: ansS, result: true},
  1877. ]);
  1878. } else {
  1879. return !confirm(`${msg}\n ${ansF} (${I18N('BTN_OK')})\n ${ansS} (${I18N('BTN_CANCEL')})`);
  1880. }
  1881. }
  1882. /**
  1883. * Dialog window 3
  1884. *
  1885. * Диалоговое окно 3
  1886. */
  1887. const showMsgs = async function (msg, ansF, ansS, ansT) {
  1888. return await popup.confirm(msg, [
  1889. {msg: ansF, result: 0},
  1890. {msg: ansS, result: 1},
  1891. {msg: ansT, result: 2},
  1892. ]);
  1893. }
  1894.  
  1895. let changeRequest = false;
  1896. testData = JSON.parse(tempData);
  1897. for (const call of testData.calls) {
  1898. if (!artifactChestOpen) {
  1899. requestHistory[this.uniqid].calls[call.name] = call.ident;
  1900. }
  1901. /**
  1902. * Cancellation of the battle in adventures, on VG and with minions of Asgard
  1903. * Отмена боя в приключениях, на ВГ и с прислужниками Асгарда
  1904. */
  1905. if ((call.name == 'adventure_endBattle' ||
  1906. call.name == 'adventureSolo_endBattle' ||
  1907. call.name == 'clanWarEndBattle' &&
  1908. isChecked('cancelBattle') ||
  1909. call.name == 'crossClanWar_endBattle' &&
  1910. isChecked('cancelBattle') ||
  1911. call.name == 'brawl_endBattle' ||
  1912. call.name == 'towerEndBattle' ||
  1913. call.name == 'invasion_bossEnd' ||
  1914. call.name == 'bossEndBattle' ||
  1915. call.name == 'clanRaid_endNodeBattle') &&
  1916. isCancalBattle) {
  1917. nameFuncEndBattle = call.name;
  1918. if (!call.args.result.win) {
  1919. let resultPopup = false;
  1920. if (call.name == 'adventure_endBattle' ||
  1921. call.name == 'invasion_bossEnd' ||
  1922. call.name == 'bossEndBattle' ||
  1923. call.name == 'adventureSolo_endBattle') {
  1924. resultPopup = await showMsgs(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_CANCEL'), I18N('BTN_AUTO'));
  1925. } else if (call.name == 'clanWarEndBattle' ||
  1926. call.name == 'crossClanWar_endBattle') {
  1927. resultPopup = await showMsg(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_AUTO_F5'));
  1928. } else {
  1929. resultPopup = await showMsg(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_CANCEL'));
  1930. }
  1931. if (resultPopup) {
  1932. fixBattle(call.args.progress[0].attackers.heroes);
  1933. fixBattle(call.args.progress[0].defenders.heroes);
  1934. changeRequest = true;
  1935. if (resultPopup > 1) {
  1936. this.onReadySuccess = testAutoBattle;
  1937. // setTimeout(bossBattle, 1000);
  1938. }
  1939. }
  1940. } else if (call.args.result.stars < 3 && call.name == 'towerEndBattle') {
  1941. resultPopup = await showMsg(I18N('LOST_HEROES'), I18N('BTN_OK'), I18N('BTN_CANCEL'), I18N('BTN_AUTO'));
  1942. if (resultPopup) {
  1943. fixBattle(call.args.progress[0].attackers.heroes);
  1944. fixBattle(call.args.progress[0].defenders.heroes);
  1945. changeRequest = true;
  1946. if (resultPopup > 1) {
  1947. this.onReadySuccess = testAutoBattle;
  1948. }
  1949. }
  1950. }
  1951. // Потасовки
  1952. /*
  1953. if (isChecked('autoBrawls') && !isBrawlsAutoStart && call.name == 'brawl_endBattle') {
  1954. if (await popup.confirm(I18N('START_AUTO_BRAWLS'), [
  1955. { msg: I18N('BTN_NO'), result: false },
  1956. { msg: I18N('BTN_YES'), result: true },
  1957. ])) {
  1958. this.onReadySuccess = testBrawls;
  1959. isBrawlsAutoStart = true;
  1960. }
  1961. }
  1962. */
  1963. }
  1964. /**
  1965. * Save pack for Brawls
  1966. *
  1967. * Сохраняем пачку для потасовок
  1968. */
  1969. if (call.name == 'brawl_startBattle') {
  1970. console.log(JSON.stringify(call.args));
  1971. brawlsPack = call.args;
  1972. }
  1973. /**
  1974. * Canceled fight in Asgard
  1975. * Отмена боя в Асгарде
  1976. */
  1977. if (call.name == 'clanRaid_endBossBattle' &&
  1978. isCancalBossBattle &&
  1979. isChecked('cancelBattle')) {
  1980. bossDamage = call.args.progress[0].defenders.heroes[1].extra;
  1981. sumDamage = bossDamage.damageTaken + bossDamage.damageTakenNextLevel;
  1982. let resultPopup = await showMsgs(
  1983. `${I18N('MSG_YOU_APPLIED')} ${sumDamage.toLocaleString()} ${I18N('MSG_DAMAGE')}.`,
  1984. I18N('BTN_OK'), I18N('BTN_AUTO_F5'), I18N('MSG_CANCEL_AND_STAT'))
  1985. if (resultPopup) {
  1986. fixBattle(call.args.progress[0].attackers.heroes);
  1987. fixBattle(call.args.progress[0].defenders.heroes);
  1988. changeRequest = true;
  1989. if (resultPopup > 1) {
  1990. this.onReadySuccess = testBossBattle;
  1991. // setTimeout(bossBattle, 1000);
  1992. }
  1993. }
  1994. }
  1995. /**
  1996. * Save the Asgard Boss Attack Pack
  1997. * Сохраняем пачку для атаки босса Асгарда
  1998. */
  1999. if (call.name == 'clanRaid_startBossBattle') {
  2000. lastBossBattle = call.args;
  2001. }
  2002. /**
  2003. * Saving the request to start the last battle
  2004. * Сохранение запроса начала последнего боя
  2005. */
  2006. if (call.name == 'clanWarAttack' ||
  2007. call.name == 'crossClanWar_startBattle' ||
  2008. call.name == 'adventure_turnStartBattle' ||
  2009. call.name == 'bossAttack' ||
  2010. call.name == 'invasion_bossStart' ||
  2011. call.name == 'towerStartBattle') {
  2012. nameFuncStartBattle = call.name;
  2013. lastBattleArg = call.args;
  2014. }
  2015. /**
  2016. * Disable spending divination cards
  2017. * Отключить трату карт предсказаний
  2018. */
  2019. if (call.name == 'dungeonEndBattle') {
  2020. if (call.args.isRaid) {
  2021. if (countPredictionCard <= 0) {
  2022. delete call.args.isRaid;
  2023. changeRequest = true;
  2024. } else if (countPredictionCard > 0) {
  2025. countPredictionCard--;
  2026. }
  2027. }
  2028. console.log(`Cards: ${countPredictionCard}`);
  2029. /**
  2030. * Fix endless cards
  2031. * Исправление бесконечных карт
  2032. */
  2033. const lastBattle = lastDungeonBattleData;
  2034. if (lastBattle && !call.args.isRaid) {
  2035. if (changeRequest) {
  2036. lastBattle.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  2037. } else {
  2038. lastBattle.progress = call.args.progress;
  2039. }
  2040. const result = await Calc(lastBattle);
  2041.  
  2042. if (changeRequest) {
  2043. call.args.progress = result.progress;
  2044. call.args.result = result.result;
  2045. }
  2046. let timer = getTimer(result.battleTime);
  2047. const period = Math.ceil((Date.now() - lastDungeonBattleStart) / 1000);
  2048. console.log(timer, period);
  2049. if (period < timer) {
  2050. timer = timer - period;
  2051. await countdownTimer(timer);
  2052. }
  2053. }
  2054. }
  2055. /**
  2056. * Quiz Answer
  2057. * Ответ на викторину
  2058. */
  2059. if (call.name == 'quizAnswer') {
  2060. /**
  2061. * Automatically changes the answer to the correct one if there is one.
  2062. * Автоматически меняет ответ на правильный если он есть
  2063. */
  2064. if (lastAnswer && isChecked('getAnswer')) {
  2065. call.args.answerId = lastAnswer;
  2066. lastAnswer = null;
  2067. changeRequest = true;
  2068. }
  2069. }
  2070. /**
  2071. * Present
  2072. * Подарки
  2073. */
  2074. if (call.name == 'freebieCheck') {
  2075. freebieCheckInfo = call;
  2076. }
  2077. /**
  2078. * Getting mission data for auto-repeat
  2079. * Получение данных миссии для автоповтора
  2080. */
  2081. if (isChecked('repeatMission') &&
  2082. call.name == 'missionEnd') {
  2083. let missionInfo = {
  2084. id: call.args.id,
  2085. result: call.args.result,
  2086. heroes: call.args.progress[0].attackers.heroes,
  2087. count: 0,
  2088. }
  2089. setTimeout(async () => {
  2090. if (!isSendsMission && await popup.confirm(I18N('MSG_REPEAT_MISSION'), [
  2091. { msg: I18N('BTN_REPEAT'), result: true},
  2092. { msg: I18N('BTN_NO'), result: false},
  2093. ])) {
  2094. isStopSendMission = false;
  2095. isSendsMission = true;
  2096. sendsMission(missionInfo);
  2097. }
  2098. }, 0);
  2099. }
  2100. /**
  2101. * Getting mission data
  2102. * Получение данных миссии
  2103. */
  2104. if (call.name == 'missionStart') {
  2105. lastMissionStart = call.args;
  2106. }
  2107. /**
  2108. * Specify the quantity for Titan Orbs and Pet Eggs
  2109. * Указать количество для сфер титанов и яиц петов
  2110. */
  2111. if (isChecked('countControl') &&
  2112. (call.name == 'pet_chestOpen' ||
  2113. call.name == 'titanUseSummonCircle') &&
  2114. call.args.amount > 1) {
  2115. call.args.amount = 1;
  2116. const result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2117. { msg: I18N('BTN_OPEN'), isInput: true, default: call.args.amount},
  2118. ]);
  2119. if (result) {
  2120. call.args.amount = result;
  2121. changeRequest = true;
  2122. }
  2123. }
  2124. /**
  2125. * Specify the amount for keys and spheres of titan artifacts
  2126. * Указать колличество для ключей и сфер артефактов титанов
  2127. */
  2128. if (isChecked('countControl') &&
  2129. (call.name == 'artifactChestOpen' ||
  2130. call.name == 'titanArtifactChestOpen') &&
  2131. call.args.amount > 1 &&
  2132. call.args.free &&
  2133. !changeRequest) {
  2134. artifactChestOpenCallName = call.name;
  2135. let result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2136. { msg: I18N('BTN_OPEN'), isInput: true, default: call.args.amount },
  2137. ]);
  2138. if (result) {
  2139. let sphere = result < 10 ? 1 : 10;
  2140.  
  2141. call.args.amount = sphere;
  2142. result -= sphere;
  2143.  
  2144. for (let count = result; count > 0; count -= sphere) {
  2145. if (count < 10) sphere = 1;
  2146. const ident = artifactChestOpenCallName + "_" + count;
  2147. testData.calls.push({
  2148. name: artifactChestOpenCallName,
  2149. args: {
  2150. amount: sphere,
  2151. free: true,
  2152. },
  2153. ident: ident
  2154. });
  2155. if (!Array.isArray(requestHistory[this.uniqid].calls[call.name])) {
  2156. requestHistory[this.uniqid].calls[call.name] = [requestHistory[this.uniqid].calls[call.name]];
  2157. }
  2158. requestHistory[this.uniqid].calls[call.name].push(ident);
  2159. }
  2160.  
  2161. artifactChestOpen = true;
  2162. changeRequest = true;
  2163. }
  2164. }
  2165. if (call.name == 'consumableUseLootBox') {
  2166. lastRussianDollId = call.args.libId;
  2167. /**
  2168. * Specify quantity for gold caskets
  2169. * Указать количество для золотых шкатулок
  2170. */
  2171. if (isChecked('countControl') &&
  2172. call.args.libId == 148 &&
  2173. call.args.amount > 1) {
  2174. const result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2175. { msg: I18N('BTN_OPEN'), isInput: true, default: call.args.amount},
  2176. ]);
  2177. call.args.amount = result;
  2178. changeRequest = true;
  2179. }
  2180. }
  2181. if (call.name == 'rewardedVideo_boxyFarmReward') {
  2182. if (!getSaveVal('argsDataForSomething', false)) {
  2183. this.onReadySuccess = async () => {
  2184. if (await popup.confirm(I18N('GET_ALL_SOMETHING'), [
  2185. { msg: 'Да', result: true },
  2186. { msg: 'Нет', result: false },
  2187. { result: false, isClose: true }
  2188. ])) {
  2189. getSomething()
  2190. }
  2191. }
  2192. }
  2193. setSaveVal('argsDataForSomething', call.args);
  2194. }
  2195. /**
  2196. * Changing the maximum number of raids in the campaign
  2197. * Изменение максимального количества рейдов в кампании
  2198. */
  2199. // if (call.name == 'missionRaid') {
  2200. // if (isChecked('countControl') && call.args.times > 1) {
  2201. // const result = +(await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2202. // { msg: I18N('BTN_RUN'), isInput: true, default: call.args.times },
  2203. // ]));
  2204. // call.args.times = result > call.args.times ? call.args.times : result;
  2205. // changeRequest = true;
  2206. // }
  2207. // }
  2208. }
  2209.  
  2210. let headers = requestHistory[this.uniqid].headers;
  2211. if (changeRequest) {
  2212. sourceData = JSON.stringify(testData);
  2213. headers['X-Auth-Signature'] = getSignature(headers, sourceData);
  2214. }
  2215.  
  2216. let signature = headers['X-Auth-Signature'];
  2217. if (signature) {
  2218. original.setRequestHeader.call(this, 'X-Auth-Signature', signature);
  2219. }
  2220. } catch (err) {
  2221. console.log("Request(send, " + this.uniqid + "):\n", sourceData, "Error:\n", err);
  2222. }
  2223. return sourceData;
  2224. }
  2225. /**
  2226. * Processing and substitution of incoming data
  2227. *
  2228. * Обработка и подмена входящих данных
  2229. */
  2230. async function checkChangeResponse(response) {
  2231. try {
  2232. isChange = false;
  2233. let nowTime = Math.round(Date.now() / 1000);
  2234. callsIdent = requestHistory[this.uniqid].calls;
  2235. respond = JSON.parse(response);
  2236. /**
  2237. * If the request returned an error removes the error (removes synchronization errors)
  2238. * Если запрос вернул ошибку удаляет ошибку (убирает ошибки синхронизации)
  2239. */
  2240. if (respond.error) {
  2241. isChange = true;
  2242. console.error(respond.error);
  2243. if (isChecked('showErrors')) {
  2244. popup.confirm(I18N('ERROR_MSG', {
  2245. name: respond.error.name,
  2246. description: respond.error.description,
  2247. }));
  2248. }
  2249. delete respond.error;
  2250. respond.results = [];
  2251. }
  2252. let mainReward = null;
  2253. const allReward = {};
  2254. let countTypeReward = 0;
  2255. let readQuestInfo = false;
  2256. for (const call of respond.results) {
  2257. /**
  2258. * Obtaining initial data for completing quests
  2259. * Получение исходных данных для выполнения квестов
  2260. */
  2261. if (readQuestInfo) {
  2262. questsInfo[call.ident] = call.result.response;
  2263. }
  2264. /**
  2265. * Getting a user ID
  2266. * Получение идетификатора пользователя
  2267. */
  2268. if (call.ident == callsIdent['registration']) {
  2269. userId = call.result.response.userId;
  2270. await openOrMigrateDatabase(userId);
  2271. readQuestInfo = true;
  2272. }
  2273. /**
  2274. * Hiding donation offers 1
  2275. * Скрываем предложения доната 1
  2276. */
  2277. if (call.ident == callsIdent['billingGetAll'] && getSaveVal('noOfferDonat')) {
  2278. const billings = call.result.response?.billings;
  2279. const bundle = call.result.response?.bundle;
  2280. if (billings && bundle) {
  2281. call.result.response.billings = [];
  2282. call.result.response.bundle = [];
  2283. isChange = true;
  2284. }
  2285. }
  2286. /**
  2287. * Hiding donation offers 2
  2288. * Скрываем предложения доната 2
  2289. */
  2290. if (getSaveVal('noOfferDonat') &&
  2291. (call.ident == callsIdent['offerGetAll'] ||
  2292. call.ident == callsIdent['specialOffer_getAll'])) {
  2293. let offers = call.result.response;
  2294. if (offers) {
  2295. call.result.response = offers.filter(e => !['addBilling', 'bundleCarousel'].includes(e.type) || ['idleResource'].includes(e.offerType));
  2296. isChange = true;
  2297. }
  2298. }
  2299. /**
  2300. * Hiding donation offers 3
  2301. * Скрываем предложения доната 3
  2302. */
  2303. if (getSaveVal('noOfferDonat') && call.result?.bundleUpdate) {
  2304. delete call.result.bundleUpdate;
  2305. isChange = true;
  2306. }
  2307. /**
  2308. * Copies a quiz question to the clipboard
  2309. * Копирует вопрос викторины в буфер обмена и получает на него ответ если есть
  2310. */
  2311. if (call.ident == callsIdent['quizGetNewQuestion']) {
  2312. let quest = call.result.response;
  2313. console.log(quest.question);
  2314. copyText(quest.question);
  2315. setProgress(I18N('QUESTION_COPY'), true);
  2316. quest.lang = null;
  2317. if (typeof NXFlashVars !== 'undefined') {
  2318. quest.lang = NXFlashVars.interface_lang;
  2319. }
  2320. lastQuestion = quest;
  2321. if (isChecked('getAnswer')) {
  2322. const answer = await getAnswer(lastQuestion);
  2323. if (answer) {
  2324. lastAnswer = answer;
  2325. console.log(answer);
  2326. setProgress(`${I18N('ANSWER_KNOWN')}: ${answer}`, true);
  2327. } else {
  2328. setProgress(I18N('ANSWER_NOT_KNOWN'), true);
  2329. }
  2330. }
  2331. }
  2332. /**
  2333. * Submits a question with an answer to the database
  2334. * Отправляет вопрос с ответом в базу данных
  2335. */
  2336. if (call.ident == callsIdent['quizAnswer']) {
  2337. const answer = call.result.response;
  2338. if (lastQuestion) {
  2339. const answerInfo = {
  2340. answer,
  2341. question: lastQuestion,
  2342. lang: null,
  2343. }
  2344. if (typeof NXFlashVars !== 'undefined') {
  2345. answerInfo.lang = NXFlashVars.interface_lang;
  2346. }
  2347. lastQuestion = null;
  2348. setTimeout(sendAnswerInfo, 0, answerInfo);
  2349. }
  2350. }
  2351. /**
  2352. * Get user data
  2353. * Получить даныне пользователя
  2354. */
  2355. if (call.ident == callsIdent['userGetInfo']) {
  2356. let user = call.result.response;
  2357. userInfo = Object.assign({}, user);
  2358. delete userInfo.refillable;
  2359. if (!questsInfo['userGetInfo']) {
  2360. questsInfo['userGetInfo'] = user;
  2361. }
  2362. }
  2363. /**
  2364. * Start of the battle for recalculation
  2365. * Начало боя для прерасчета
  2366. */
  2367. if (call.ident == callsIdent['clanWarAttack'] ||
  2368. call.ident == callsIdent['crossClanWar_startBattle'] ||
  2369. call.ident == callsIdent['bossAttack'] ||
  2370. call.ident == callsIdent['battleGetReplay'] ||
  2371. call.ident == callsIdent['brawl_startBattle'] ||
  2372. call.ident == callsIdent['adventureSolo_turnStartBattle'] ||
  2373. call.ident == callsIdent['invasion_bossStart'] ||
  2374. call.ident == callsIdent['towerStartBattle'] ||
  2375. call.ident == callsIdent['adventure_turnStartBattle']) {
  2376. let battle = call.result.response.battle || call.result.response.replay;
  2377. if (call.ident == callsIdent['brawl_startBattle'] ||
  2378. call.ident == callsIdent['bossAttack'] ||
  2379. call.ident == callsIdent['towerStartBattle'] ||
  2380. call.ident == callsIdent['invasion_bossStart']) {
  2381. battle = call.result.response;
  2382. }
  2383. lastBattleInfo = battle;
  2384. if (!isChecked('preCalcBattle')) {
  2385. continue;
  2386. }
  2387. setProgress(I18N('BEING_RECALC'));
  2388. let battleDuration = 120;
  2389. try {
  2390. const typeBattle = getBattleType(battle.type);
  2391. battleDuration = +lib.data.battleConfig[typeBattle.split('_')[1]].config.battleDuration;
  2392. } catch (e) { }
  2393. //console.log(battle.type);
  2394. function getBattleInfo(battle, isRandSeed) {
  2395. return new Promise(function (resolve) {
  2396. if (isRandSeed) {
  2397. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  2398. }
  2399. BattleCalc(battle, getBattleType(battle.type), e => resolve(e));
  2400. });
  2401. }
  2402. let actions = [getBattleInfo(battle, false)]
  2403. const countTestBattle = getInput('countTestBattle');
  2404. if (call.ident == callsIdent['battleGetReplay']) {
  2405. battle.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  2406. }
  2407. for (let i = 0; i < countTestBattle; i++) {
  2408. actions.push(getBattleInfo(battle, true));
  2409. }
  2410. Promise.all(actions)
  2411. .then(e => {
  2412. e = e.map(n => ({win: n.result.win, time: n.battleTime}));
  2413. let firstBattle = e.shift();
  2414. const timer = Math.floor(battleDuration - firstBattle.time);
  2415. const min = ('00' + Math.floor(timer / 60)).slice(-2);
  2416. const sec = ('00' + Math.floor(timer - min * 60)).slice(-2);
  2417. const countWin = e.reduce((w, s) => w + s.win, 0);
  2418. setProgress(`${I18N('THIS_TIME')} ${(firstBattle.win ? I18N('VICTORY') : I18N('DEFEAT'))} ${I18N('CHANCE_TO_WIN')}: ${Math.floor(countWin / e.length * 100)}% (${e.length}), ${min}:${sec}`, false, hideProgress)
  2419. });
  2420. }
  2421. /**
  2422. * Start of the Asgard boss fight
  2423. * Начало боя с боссом Асгарда
  2424. */
  2425. if (call.ident == callsIdent['clanRaid_startBossBattle']) {
  2426. lastBossBattleInfo = call.result.response.battle;
  2427. if (isChecked('preCalcBattle')) {
  2428. const result = await Calc(lastBossBattleInfo).then(e => e.progress[0].defenders.heroes[1].extra);
  2429. const bossDamage = result.damageTaken + result.damageTakenNextLevel;
  2430. setProgress(I18N('BOSS_DAMAGE') + bossDamage.toLocaleString(), false, hideProgress);
  2431. }
  2432. }
  2433. /**
  2434. * Cancel tutorial
  2435. * Отмена туториала
  2436. */
  2437. if (isCanceledTutorial && call.ident == callsIdent['tutorialGetInfo']) {
  2438. let chains = call.result.response.chains;
  2439. for (let n in chains) {
  2440. chains[n] = 9999;
  2441. }
  2442. isChange = true;
  2443. }
  2444. /**
  2445. * Opening keys and spheres of titan artifacts
  2446. * Открытие ключей и сфер артефактов титанов
  2447. */
  2448. if (artifactChestOpen &&
  2449. (call.ident == callsIdent[artifactChestOpenCallName] ||
  2450. (callsIdent[artifactChestOpenCallName] && callsIdent[artifactChestOpenCallName].includes(call.ident)))) {
  2451. let reward = call.result.response[artifactChestOpenCallName == 'artifactChestOpen' ? 'chestReward' : 'reward'];
  2452.  
  2453. reward.forEach(e => {
  2454. for (let f in e) {
  2455. if (!allReward[f]) {
  2456. allReward[f] = {};
  2457. }
  2458. for (let o in e[f]) {
  2459. if (!allReward[f][o]) {
  2460. allReward[f][o] = e[f][o];
  2461. countTypeReward++;
  2462. } else {
  2463. allReward[f][o] += e[f][o];
  2464. }
  2465. }
  2466. }
  2467. });
  2468.  
  2469. if (!call.ident.includes(artifactChestOpenCallName)) {
  2470. mainReward = call.result.response;
  2471. }
  2472. }
  2473.  
  2474. if (countTypeReward > 20) {
  2475. correctShowOpenArtifact = 3;
  2476. } else {
  2477. correctShowOpenArtifact = 0;
  2478. }
  2479. /**
  2480. * Sum the result of opening Pet Eggs
  2481. * Суммирование результата открытия яиц питомцев
  2482. */
  2483. if (isChecked('countControl') && call.ident == callsIdent['pet_chestOpen']) {
  2484. const rewards = call.result.response.rewards;
  2485. rewards.forEach(e => {
  2486. for (let f in e) {
  2487. if (!allReward[f]) {
  2488. allReward[f] = {};
  2489. }
  2490. for (let o in e[f]) {
  2491. if (!allReward[f][o]) {
  2492. allReward[f][o] = e[f][o];
  2493. } else {
  2494. allReward[f][o] += e[f][o];
  2495. }
  2496. }
  2497. }
  2498. });
  2499. call.result.response.rewards = [allReward];
  2500. isChange = true;
  2501. }
  2502. /**
  2503. * Auto-repeat opening matryoshkas
  2504. * АвтоПовтор открытия матрешек
  2505. */
  2506. if (isChecked('countControl') && call.ident == callsIdent['consumableUseLootBox']) {
  2507. let lootBox = call.result.response;
  2508. let newCount = 0;
  2509. for (let n of lootBox) {
  2510. if (n?.consumable && n.consumable[lastRussianDollId]) {
  2511. newCount += n.consumable[lastRussianDollId]
  2512. }
  2513. }
  2514. if (newCount && await popup.confirm(`${I18N('BTN_OPEN')} ${newCount} ${I18N('OPEN_DOLLS')}?`, [
  2515. { msg: I18N('BTN_OPEN'), result: true},
  2516. { msg: I18N('BTN_NO'), result: false},
  2517. ])) {
  2518. const recursionResult = await openRussianDolls(lastRussianDollId, newCount);
  2519. lootBox = [...lootBox, ...recursionResult];
  2520. }
  2521.  
  2522. /** Объединение результата лутбоксов */
  2523. const allLootBox = {};
  2524. lootBox.forEach(e => {
  2525. for (let f in e) {
  2526. if (!allLootBox[f]) {
  2527. if (typeof e[f] == 'object') {
  2528. allLootBox[f] = {};
  2529. } else {
  2530. allLootBox[f] = 0;
  2531. }
  2532. }
  2533. if (typeof e[f] == 'object') {
  2534. for (let o in e[f]) {
  2535. if (newCount && o == lastRussianDollId) {
  2536. continue;
  2537. }
  2538. if (!allLootBox[f][o]) {
  2539. allLootBox[f][o] = e[f][o];
  2540. } else {
  2541. allLootBox[f][o] += e[f][o];
  2542. }
  2543. }
  2544. } else {
  2545. allLootBox[f] += e[f];
  2546. }
  2547. }
  2548. });
  2549. /** Разбитие результата */
  2550. const output = [];
  2551. const maxCount = 5;
  2552. let currentObj = {};
  2553. let count = 0;
  2554. for (let f in allLootBox) {
  2555. if (!currentObj[f]) {
  2556. if (typeof allLootBox[f] == 'object') {
  2557. for (let o in allLootBox[f]) {
  2558. currentObj[f] ||= {}
  2559. if (!currentObj[f][o]) {
  2560. currentObj[f][o] = allLootBox[f][o];
  2561. count++;
  2562. if (count === maxCount) {
  2563. output.push(currentObj);
  2564. currentObj = {};
  2565. count = 0;
  2566. }
  2567. }
  2568. }
  2569. } else {
  2570. currentObj[f] = allLootBox[f];
  2571. count++;
  2572. if (count === maxCount) {
  2573. output.push(currentObj);
  2574. currentObj = {};
  2575. count = 0;
  2576. }
  2577. }
  2578. }
  2579. }
  2580. if (count > 0) {
  2581. output.push(currentObj);
  2582. }
  2583.  
  2584. console.log(output);
  2585. call.result.response = output;
  2586. isChange = true;
  2587. }
  2588. /**
  2589. * Dungeon recalculation (fix endless cards)
  2590. * Прерасчет подземки (исправление бесконечных карт)
  2591. */
  2592. if (call.ident == callsIdent['dungeonStartBattle']) {
  2593. lastDungeonBattleData = call.result.response;
  2594. lastDungeonBattleStart = Date.now();
  2595. }
  2596. /**
  2597. * Getting the number of prediction cards
  2598. * Получение количества карт предсказаний
  2599. */
  2600. if (call.ident == callsIdent['inventoryGet']) {
  2601. countPredictionCard = call.result.response.consumable[81] || 0;
  2602. }
  2603. /**
  2604. * Getting subscription status
  2605. * Получение состояния подписки
  2606. */
  2607. if (call.ident == callsIdent['subscriptionGetInfo']) {
  2608. const subscription = call.result.response.subscription;
  2609. if (subscription) {
  2610. subEndTime = subscription.endTime * 1000;
  2611. }
  2612. }
  2613. /**
  2614. * Getting prediction cards
  2615. * Получение карт предсказаний
  2616. */
  2617. if (call.ident == callsIdent['questFarm']) {
  2618. const consumable = call.result.response?.consumable;
  2619. if (consumable && consumable[81]) {
  2620. countPredictionCard += consumable[81];
  2621. console.log(`Cards: ${countPredictionCard}`);
  2622. }
  2623. }
  2624. /**
  2625. * Hiding extra servers
  2626. * Скрытие лишних серверов
  2627. */
  2628. if (call.ident == callsIdent['serverGetAll'] && isChecked('hideServers')) {
  2629. let servers = call.result.response.users.map(s => s.serverId)
  2630. call.result.response.servers = call.result.response.servers.filter(s => servers.includes(s.id));
  2631. isChange = true;
  2632. }
  2633. /**
  2634. * Displays player positions in the adventure
  2635. * Отображает позиции игроков в приключении
  2636. */
  2637. if (call.ident == callsIdent['adventure_getLobbyInfo']) {
  2638. const users = Object.values(call.result.response.users);
  2639. let msg = I18N('PLAYER_POS');
  2640. for (const user of users) {
  2641. msg += `<br>${user.user.name} - ${user.currentNode}`;
  2642. }
  2643. setProgress(msg, false, hideProgress);
  2644. }
  2645. /**
  2646. * Automatic launch of a raid at the end of the adventure
  2647. * Автоматический запуск рейда при окончании приключения
  2648. */
  2649. if (call.ident == callsIdent['adventure_end']) {
  2650. autoRaidAdventure()
  2651. }
  2652. /**
  2653. * Do something
  2654. * Сделать кое-что
  2655. */
  2656. if (call.ident == callsIdent['splitGetAll']) {
  2657. if (!(NXFlashVars?.game_url || '').includes('facebook')) {
  2658. call.result.response.push({
  2659. "mechanic_level": {
  2660. "rewarded_video_boxy": {
  2661. "enabled": 1
  2662. }
  2663. }
  2664. });
  2665. isChange = true;
  2666. }
  2667. }
  2668. /** Удаление лавки редкостей */
  2669. if (call.ident == callsIdent['missionRaid']) {
  2670. if (call.result?.heroesMerchant) {
  2671. delete call.result.heroesMerchant;
  2672. isChange = true;
  2673. }
  2674. }
  2675. }
  2676.  
  2677. if (mainReward && artifactChestOpen) {
  2678. console.log(allReward);
  2679. mainReward[artifactChestOpenCallName == 'artifactChestOpen' ? 'chestReward' : 'reward'] = [allReward];
  2680. artifactChestOpen = false;
  2681. artifactChestOpenCallName = '';
  2682. isChange = true;
  2683. }
  2684. } catch(err) {
  2685. console.log("Request(response, " + this.uniqid + "):\n", "Error:\n", response, err);
  2686. }
  2687.  
  2688. if (isChange) {
  2689. Object.defineProperty(this, 'responseText', {
  2690. writable: true
  2691. });
  2692. this.responseText = JSON.stringify(respond);
  2693. }
  2694. }
  2695.  
  2696. /**
  2697. * Request an answer to a question
  2698. *
  2699. * Запрос ответа на вопрос
  2700. */
  2701. async function getAnswer(question) {
  2702. return new Promise((resolve, reject) => {
  2703. fetch('https://zingery.ru/heroes/getAnswer.php', {
  2704. method: 'POST',
  2705. body: JSON.stringify(question)
  2706. }).then(
  2707. response => response.json()
  2708. ).then(
  2709. data => {
  2710. if (data.result) {
  2711. resolve(data.result);
  2712. } else {
  2713. resolve(false);
  2714. }
  2715. }
  2716. ).catch((error) => {
  2717. console.error(error);
  2718. resolve(false);
  2719. });
  2720. })
  2721. }
  2722.  
  2723. /**
  2724. * Submitting a question and answer to a database
  2725. *
  2726. * Отправка вопроса и ответа в базу данных
  2727. */
  2728. function sendAnswerInfo(answerInfo) {
  2729. fetch('https://zingery.ru/heroes/setAnswer.php', {
  2730. method: 'POST',
  2731. body: JSON.stringify(answerInfo)
  2732. }).then(
  2733. response => response.json()
  2734. ).then(
  2735. data => {
  2736. if (data.result) {
  2737. console.log(I18N('SENT_QUESTION'));
  2738. }
  2739. }
  2740. )
  2741. }
  2742.  
  2743. /**
  2744. * Returns the battle type by preset type
  2745. *
  2746. * Возвращает тип боя по типу пресета
  2747. */
  2748. function getBattleType(strBattleType) {
  2749. if (strBattleType.includes("invasion")) {
  2750. return "get_invasion";
  2751. }
  2752. if (strBattleType.includes("boss")) {
  2753. return "get_boss";
  2754. }
  2755. switch (strBattleType) {
  2756. case "invasion":
  2757. return "get_invasion";
  2758. case "titan_pvp_manual":
  2759. return "get_titanPvpManual";
  2760. case "titan_pvp":
  2761. return "get_titanPvp";
  2762. case "titan_clan_pvp":
  2763. case "clan_pvp_titan":
  2764. case "clan_global_pvp_titan":
  2765. case "brawl_titan":
  2766. case "challenge_titan":
  2767. return "get_titanClanPvp";
  2768. case "clan_raid": // Asgard Boss // Босс асгарда
  2769. case "adventure": // Adventures // Приключения
  2770. case "clan_global_pvp":
  2771. case "clan_pvp":
  2772. return "get_clanPvp";
  2773. case "dungeon_titan":
  2774. case "titan_tower":
  2775. return "get_titan";
  2776. case "tower":
  2777. case "clan_dungeon":
  2778. return "get_tower";
  2779. case "pve":
  2780. return "get_pve";
  2781. case "pvp_manual":
  2782. return "get_pvpManual";
  2783. case "grand":
  2784. case "arena":
  2785. case "pvp":
  2786. case "challenge":
  2787. return "get_pvp";
  2788. case "core":
  2789. return "get_core";
  2790. case "boss_10":
  2791. case "boss_11":
  2792. case "boss_12":
  2793. return "get_boss";
  2794. default:
  2795. return "get_clanPvp";
  2796. }
  2797. }
  2798. /**
  2799. * Returns the class name of the passed object
  2800. *
  2801. * Возвращает название класса переданного объекта
  2802. */
  2803. function getClass(obj) {
  2804. return {}.toString.call(obj).slice(8, -1);
  2805. }
  2806. /**
  2807. * Calculates the request signature
  2808. *
  2809. * Расчитывает сигнатуру запроса
  2810. */
  2811. this.getSignature = function(headers, data) {
  2812. const sign = {
  2813. signature: '',
  2814. length: 0,
  2815. add: function (text) {
  2816. this.signature += text;
  2817. if (this.length < this.signature.length) {
  2818. this.length = 3 * (this.signature.length + 1) >> 1;
  2819. }
  2820. },
  2821. }
  2822. sign.add(headers["X-Request-Id"]);
  2823. sign.add(':');
  2824. sign.add(headers["X-Auth-Token"]);
  2825. sign.add(':');
  2826. sign.add(headers["X-Auth-Session-Id"]);
  2827. sign.add(':');
  2828. sign.add(data);
  2829. sign.add(':');
  2830. sign.add('LIBRARY-VERSION=1');
  2831. sign.add('UNIQUE-SESSION-ID=' + headers["X-Env-Unique-Session-Id"]);
  2832.  
  2833. return md5(sign.signature);
  2834. }
  2835. /**
  2836. * Creates an interface
  2837. *
  2838. * Создает интерфейс
  2839. */
  2840. function createInterface() {
  2841. scriptMenu.init({
  2842. showMenu: true
  2843. });
  2844. scriptMenu.addHeader(GM_info.script.name, justInfo);
  2845. scriptMenu.addHeader('v' + GM_info.script.version);
  2846. }
  2847.  
  2848. function addControls() {
  2849. const checkboxDetails = scriptMenu.addDetails(I18N('SETTINGS'));
  2850. for (let name in checkboxes) {
  2851. checkboxes[name].cbox = scriptMenu.addCheckbox(checkboxes[name].label, checkboxes[name].title, checkboxDetails);
  2852. /**
  2853. * Getting the state of checkboxes from storage
  2854. * Получаем состояние чекбоксов из storage
  2855. */
  2856. let val = storage.get(name, null);
  2857. if (val != null) {
  2858. checkboxes[name].cbox.checked = val;
  2859. } else {
  2860. storage.set(name, checkboxes[name].default);
  2861. checkboxes[name].cbox.checked = checkboxes[name].default;
  2862. }
  2863. /**
  2864. * Tracing the change event of the checkbox for writing to storage
  2865. * Отсеживание события изменения чекбокса для записи в storage
  2866. */
  2867. checkboxes[name].cbox.dataset['name'] = name;
  2868. checkboxes[name].cbox.addEventListener('change', async function (event) {
  2869. const nameCheckbox = this.dataset['name'];
  2870. /*
  2871. if (this.checked && nameCheckbox == 'cancelBattle') {
  2872. this.checked = false;
  2873. if (await popup.confirm(I18N('MSG_BAN_ATTENTION'), [
  2874. { msg: I18N('BTN_NO_I_AM_AGAINST'), result: true },
  2875. { msg: I18N('BTN_YES_I_AGREE'), result: false },
  2876. ])) {
  2877. return;
  2878. }
  2879. this.checked = true;
  2880. }
  2881. */
  2882. storage.set(nameCheckbox, this.checked);
  2883. })
  2884. }
  2885.  
  2886. const inputDetails = scriptMenu.addDetails(I18N('VALUES'));
  2887. for (let name in inputs) {
  2888. inputs[name].input = scriptMenu.addInputText(inputs[name].title, false, inputDetails);
  2889. /**
  2890. * Get inputText state from storage
  2891. * Получаем состояние inputText из storage
  2892. */
  2893. let val = storage.get(name, null);
  2894. if (val != null) {
  2895. inputs[name].input.value = val;
  2896. } else {
  2897. storage.set(name, inputs[name].default);
  2898. inputs[name].input.value = inputs[name].default;
  2899. }
  2900. /**
  2901. * Tracing a field change event for a record in storage
  2902. * Отсеживание события изменения поля для записи в storage
  2903. */
  2904. inputs[name].input.dataset['name'] = name;
  2905. inputs[name].input.addEventListener('input', function () {
  2906. const inputName = this.dataset['name'];
  2907. let value = +this.value;
  2908. if (!value || Number.isNaN(value)) {
  2909. value = storage.get(inputName, inputs[inputName].default);
  2910. inputs[name].input.value = value;
  2911. }
  2912. storage.set(inputName, value);
  2913. })
  2914. }
  2915. }
  2916.  
  2917. /**
  2918. * Sending a request
  2919. *
  2920. * Отправка запроса
  2921. */
  2922. function send(json, callback, pr) {
  2923. if (typeof json == 'string') {
  2924. json = JSON.parse(json);
  2925. }
  2926. for (const call of json.calls) {
  2927. if (!call?.context?.actionTs) {
  2928. call.context = {
  2929. actionTs: performance.now()
  2930. }
  2931. }
  2932. }
  2933. json = JSON.stringify(json);
  2934. /**
  2935. * We get the headlines of the previous intercepted request
  2936. * Получаем заголовки предыдущего перехваченого запроса
  2937. */
  2938. let headers = lastHeaders;
  2939. /**
  2940. * We increase the header of the query Certifier by 1
  2941. * Увеличиваем заголовок идетификатора запроса на 1
  2942. */
  2943. headers["X-Request-Id"]++;
  2944. /**
  2945. * We calculate the title with the signature
  2946. * Расчитываем заголовок с сигнатурой
  2947. */
  2948. headers["X-Auth-Signature"] = getSignature(headers, json);
  2949. /**
  2950. * Create a new ajax request
  2951. * Создаем новый AJAX запрос
  2952. */
  2953. let xhr = new XMLHttpRequest;
  2954. /**
  2955. * Indicate the previously saved URL for API queries
  2956. * Указываем ранее сохраненный URL для API запросов
  2957. */
  2958. xhr.open('POST', apiUrl, true);
  2959. /**
  2960. * Add the function to the event change event
  2961. * Добавляем функцию к событию смены статуса запроса
  2962. */
  2963. xhr.onreadystatechange = function() {
  2964. /**
  2965. * If the result of the request is obtained, we call the flask function
  2966. * Если результат запроса получен вызываем колбек функцию
  2967. */
  2968. if(xhr.readyState == 4) {
  2969. let randTimeout = Math.random() * 200 + 200;
  2970. setTimeout(callback, randTimeout, xhr.response, pr);
  2971. }
  2972. };
  2973. /**
  2974. * Indicate the type of request
  2975. * Указываем тип запроса
  2976. */
  2977. xhr.responseType = 'json';
  2978. /**
  2979. * We set the request headers
  2980. * Задаем заголовки запроса
  2981. */
  2982. for(let nameHeader in headers) {
  2983. let head = headers[nameHeader];
  2984. xhr.setRequestHeader(nameHeader, head);
  2985. }
  2986. /**
  2987. * Sending a request
  2988. * Отправляем запрос
  2989. */
  2990. xhr.send(json);
  2991. }
  2992.  
  2993. let hideTimeoutProgress = 0;
  2994. /**
  2995. * Hide progress
  2996. *
  2997. * Скрыть прогресс
  2998. */
  2999. function hideProgress(timeout) {
  3000. timeout = timeout || 0;
  3001. clearTimeout(hideTimeoutProgress);
  3002. hideTimeoutProgress = setTimeout(function () {
  3003. scriptMenu.setStatus('');
  3004. }, timeout);
  3005. }
  3006. /**
  3007. * Progress display
  3008. *
  3009. * Отображение прогресса
  3010. */
  3011. function setProgress(text, hide, onclick) {
  3012. scriptMenu.setStatus(text, onclick);
  3013. hide = hide || false;
  3014. if (hide) {
  3015. hideProgress(3000);
  3016. }
  3017. }
  3018.  
  3019. /**
  3020. * Returns the timer value depending on the subscription
  3021. *
  3022. * Возвращает значение таймера в зависимости от подписки
  3023. */
  3024. function getTimer(time) {
  3025. let speedDiv = 5;
  3026. if (subEndTime < Date.now()) {
  3027. speedDiv = 1.5;
  3028. }
  3029. return Math.max(time / speedDiv + 1.5, 4);
  3030. }
  3031.  
  3032.  
  3033. /**
  3034. * Calculates HASH MD5 from string
  3035. *
  3036. * Расчитывает HASH MD5 из строки
  3037. *
  3038. * [js-md5]{@link https://github.com/emn178/js-md5}
  3039. *
  3040. * @namespace md5
  3041. * @version 0.7.3
  3042. * @author Chen, Yi-Cyuan [emn178@gmail.com]
  3043. * @copyright Chen, Yi-Cyuan 2014-2017
  3044. * @license MIT
  3045. */
  3046. !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 _}))}();
  3047.  
  3048. /**
  3049. * Script for beautiful dialog boxes
  3050. *
  3051. * Скрипт для красивых диалоговых окошек
  3052. */
  3053. const popup = new (function () {
  3054. this.popUp,
  3055. this.downer,
  3056. this.middle,
  3057. this.msgText,
  3058. this.buttons = [];
  3059. this.checkboxes = [];
  3060. this.dialogPromice = null;
  3061.  
  3062. function init() {
  3063. addStyle();
  3064. addBlocks();
  3065. addEventListeners();
  3066. }
  3067.  
  3068. const addEventListeners = () => {
  3069. document.addEventListener('keyup', (e) => {
  3070. if (e.key == 'Escape') {
  3071. if (this.dialogPromice) {
  3072. const { func, result } = this.dialogPromice;
  3073. this.dialogPromice = null;
  3074. popup.hide();
  3075. func(result);
  3076. }
  3077. }
  3078. });
  3079. }
  3080.  
  3081. const addStyle = () => {
  3082. let style = document.createElement('style');
  3083. style.innerText = `
  3084. .PopUp_ {
  3085. position: absolute;
  3086. min-width: 300px;
  3087. max-width: 500px;
  3088. max-height: 600px;
  3089. background-color: #190e08e6;
  3090. z-index: 10001;
  3091. top: 169px;
  3092. left: 345px;
  3093. border: 3px #ce9767 solid;
  3094. border-radius: 10px;
  3095. display: flex;
  3096. flex-direction: column;
  3097. justify-content: space-around;
  3098. padding: 15px 9px;
  3099. box-sizing: border-box;
  3100. }
  3101.  
  3102. .PopUp_back {
  3103. position: absolute;
  3104. background-color: #00000066;
  3105. width: 100%;
  3106. height: 100%;
  3107. z-index: 10000;
  3108. top: 0;
  3109. left: 0;
  3110. }
  3111.  
  3112. .PopUp_close {
  3113. width: 40px;
  3114. height: 40px;
  3115. position: absolute;
  3116. right: -18px;
  3117. top: -18px;
  3118. border: 3px solid #c18550;
  3119. border-radius: 20px;
  3120. background: radial-gradient(circle, rgba(190,30,35,1) 0%, rgba(0,0,0,1) 100%);
  3121. background-position-y: 3px;
  3122. box-shadow: -1px 1px 3px black;
  3123. cursor: pointer;
  3124. box-sizing: border-box;
  3125. }
  3126.  
  3127. .PopUp_close:hover {
  3128. filter: brightness(1.2);
  3129. }
  3130.  
  3131. .PopUp_crossClose {
  3132. width: 100%;
  3133. height: 100%;
  3134. background-size: 65%;
  3135. background-position: center;
  3136. background-repeat: no-repeat;
  3137. 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")
  3138. }
  3139.  
  3140. .PopUp_blocks {
  3141. width: 100%;
  3142. height: 50%;
  3143. display: flex;
  3144. justify-content: space-evenly;
  3145. align-items: center;
  3146. flex-wrap: wrap;
  3147. justify-content: center;
  3148. }
  3149.  
  3150. .PopUp_blocks:last-child {
  3151. margin-top: 25px;
  3152. }
  3153.  
  3154. .PopUp_buttons {
  3155. display: flex;
  3156. margin: 7px 10px;
  3157. flex-direction: column;
  3158. }
  3159.  
  3160. .PopUp_button {
  3161. background-color: #52A81C;
  3162. border-radius: 5px;
  3163. box-shadow: inset 0px -4px 10px, inset 0px 3px 2px #99fe20, 0px 0px 4px, 0px -3px 1px #d7b275, 0px 0px 0px 3px #ce9767;
  3164. cursor: pointer;
  3165. padding: 4px 12px 6px;
  3166. }
  3167.  
  3168. .PopUp_input {
  3169. text-align: center;
  3170. font-size: 16px;
  3171. height: 27px;
  3172. border: 1px solid #cf9250;
  3173. border-radius: 9px 9px 0px 0px;
  3174. background: transparent;
  3175. color: #fce1ac;
  3176. padding: 1px 10px;
  3177. box-sizing: border-box;
  3178. box-shadow: 0px 0px 4px, 0px 0px 0px 3px #ce9767;
  3179. }
  3180.  
  3181. .PopUp_checkboxes {
  3182. display: flex;
  3183. flex-direction: column;
  3184. margin: 15px 15px -5px 15px;
  3185. align-items: flex-start;
  3186. }
  3187.  
  3188. .PopUp_ContCheckbox {
  3189. margin: 2px 0px;
  3190. }
  3191.  
  3192. .PopUp_checkbox {
  3193. position: absolute;
  3194. z-index: -1;
  3195. opacity: 0;
  3196. }
  3197. .PopUp_checkbox+label {
  3198. display: inline-flex;
  3199. align-items: center;
  3200. user-select: none;
  3201.  
  3202. font-size: 15px;
  3203. font-family: sans-serif;
  3204. font-weight: 600;
  3205. font-stretch: condensed;
  3206. letter-spacing: 1px;
  3207. color: #fce1ac;
  3208. text-shadow: 0px 0px 1px;
  3209. }
  3210. .PopUp_checkbox+label::before {
  3211. content: '';
  3212. display: inline-block;
  3213. width: 20px;
  3214. height: 20px;
  3215. border: 1px solid #cf9250;
  3216. border-radius: 7px;
  3217. margin-right: 7px;
  3218. }
  3219. .PopUp_checkbox:checked+label::before {
  3220. 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");
  3221. }
  3222.  
  3223. .PopUp_input::placeholder {
  3224. color: #fce1ac75;
  3225. }
  3226.  
  3227. .PopUp_input:focus {
  3228. outline: 0;
  3229. }
  3230.  
  3231. .PopUp_input + .PopUp_button {
  3232. border-radius: 0px 0px 5px 5px;
  3233. padding: 2px 18px 5px;
  3234. }
  3235.  
  3236. .PopUp_button:hover {
  3237. filter: brightness(1.2);
  3238. }
  3239.  
  3240. .PopUp_button:active {
  3241. box-shadow: inset 0px 5px 10px, inset 0px 1px 2px #99fe20, 0px 0px 4px, 0px -3px 1px #d7b275, 0px 0px 0px 3px #ce9767;
  3242. }
  3243.  
  3244. .PopUp_text {
  3245. font-size: 22px;
  3246. font-family: sans-serif;
  3247. font-weight: 600;
  3248. font-stretch: condensed;
  3249. letter-spacing: 1px;
  3250. text-align: center;
  3251. }
  3252.  
  3253. .PopUp_buttonText {
  3254. color: #E4FF4C;
  3255. text-shadow: 0px 1px 2px black;
  3256. }
  3257.  
  3258. .PopUp_msgText {
  3259. color: #FDE5B6;
  3260. text-shadow: 0px 0px 2px;
  3261. }
  3262.  
  3263. .PopUp_hideBlock {
  3264. display: none;
  3265. }
  3266. `;
  3267. document.head.appendChild(style);
  3268. }
  3269.  
  3270. const addBlocks = () => {
  3271. this.back = document.createElement('div');
  3272. this.back.classList.add('PopUp_back');
  3273. this.back.classList.add('PopUp_hideBlock');
  3274. document.body.append(this.back);
  3275.  
  3276. this.popUp = document.createElement('div');
  3277. this.popUp.classList.add('PopUp_');
  3278. this.back.append(this.popUp);
  3279.  
  3280. let upper = document.createElement('div')
  3281. upper.classList.add('PopUp_blocks');
  3282. this.popUp.append(upper);
  3283.  
  3284. this.middle = document.createElement('div')
  3285. this.middle.classList.add('PopUp_blocks');
  3286. this.middle.classList.add('PopUp_checkboxes');
  3287. this.popUp.append(this.middle);
  3288.  
  3289. this.downer = document.createElement('div')
  3290. this.downer.classList.add('PopUp_blocks');
  3291. this.popUp.append(this.downer);
  3292.  
  3293. this.msgText = document.createElement('div');
  3294. this.msgText.classList.add('PopUp_text', 'PopUp_msgText');
  3295. upper.append(this.msgText);
  3296. }
  3297.  
  3298. this.showBack = function () {
  3299. this.back.classList.remove('PopUp_hideBlock');
  3300. }
  3301.  
  3302. this.hideBack = function () {
  3303. this.back.classList.add('PopUp_hideBlock');
  3304. }
  3305.  
  3306. this.show = function () {
  3307. if (this.checkboxes.length) {
  3308. this.middle.classList.remove('PopUp_hideBlock');
  3309. }
  3310. this.showBack();
  3311. this.popUp.classList.remove('PopUp_hideBlock');
  3312. this.popUp.style.left = (window.innerWidth - this.popUp.offsetWidth) / 2 + 'px';
  3313. this.popUp.style.top = (window.innerHeight - this.popUp.offsetHeight) / 3 + 'px';
  3314. }
  3315.  
  3316. this.hide = function () {
  3317. this.hideBack();
  3318. this.popUp.classList.add('PopUp_hideBlock');
  3319. }
  3320.  
  3321. this.addAnyButton = (option) => {
  3322. const contButton = document.createElement('div');
  3323. contButton.classList.add('PopUp_buttons');
  3324. this.downer.append(contButton);
  3325.  
  3326. let inputField = {
  3327. value: option.result || option.default
  3328. }
  3329. if (option.isInput) {
  3330. inputField = document.createElement('input');
  3331. inputField.type = 'text';
  3332. if (option.placeholder) {
  3333. inputField.placeholder = option.placeholder;
  3334. }
  3335. if (option.default) {
  3336. inputField.value = option.default;
  3337. }
  3338. inputField.classList.add('PopUp_input');
  3339. contButton.append(inputField);
  3340. }
  3341.  
  3342. const button = document.createElement('div');
  3343. button.classList.add('PopUp_button');
  3344. button.title = option.title || '';
  3345. contButton.append(button);
  3346.  
  3347. const buttonText = document.createElement('div');
  3348. buttonText.classList.add('PopUp_text', 'PopUp_buttonText');
  3349. buttonText.innerText = option.msg;
  3350. button.append(buttonText);
  3351.  
  3352. return { button, contButton, inputField };
  3353. }
  3354.  
  3355. this.addCloseButton = () => {
  3356. let button = document.createElement('div')
  3357. button.classList.add('PopUp_close');
  3358. this.popUp.append(button);
  3359.  
  3360. let crossClose = document.createElement('div')
  3361. crossClose.classList.add('PopUp_crossClose');
  3362. button.append(crossClose);
  3363.  
  3364. return { button, contButton: button };
  3365. }
  3366.  
  3367. this.addButton = (option, buttonClick) => {
  3368.  
  3369. const { button, contButton, inputField } = option.isClose ? this.addCloseButton() : this.addAnyButton(option);
  3370. if (option.isClose) {
  3371. this.dialogPromice = {func: buttonClick, result: option.result};
  3372. }
  3373. button.addEventListener('click', () => {
  3374. let result = '';
  3375. if (option.isInput) {
  3376. result = inputField.value;
  3377. }
  3378. if (option.isClose || option.isCancel) {
  3379. this.dialogPromice = null;
  3380. }
  3381. buttonClick(result);
  3382. });
  3383.  
  3384. this.buttons.push(contButton);
  3385. }
  3386.  
  3387. this.clearButtons = () => {
  3388. while (this.buttons.length) {
  3389. this.buttons.pop().remove();
  3390. }
  3391. }
  3392.  
  3393. this.addCheckBox = (checkBox) => {
  3394. const contCheckbox = document.createElement('div');
  3395. contCheckbox.classList.add('PopUp_ContCheckbox');
  3396. this.middle.append(contCheckbox);
  3397.  
  3398. const checkbox = document.createElement('input');
  3399. checkbox.type = 'checkbox';
  3400. checkbox.id = 'PopUpCheckbox' + this.checkboxes.length;
  3401. checkbox.dataset.name = checkBox.name;
  3402. checkbox.checked = checkBox.checked;
  3403. checkbox.label = checkBox.label;
  3404. checkbox.title = checkBox.title || '';
  3405. checkbox.classList.add('PopUp_checkbox');
  3406. contCheckbox.appendChild(checkbox)
  3407.  
  3408. const checkboxLabel = document.createElement('label');
  3409. checkboxLabel.innerText = checkBox.label;
  3410. checkboxLabel.title = checkBox.title || '';
  3411. checkboxLabel.setAttribute('for', checkbox.id);
  3412. contCheckbox.appendChild(checkboxLabel);
  3413.  
  3414. this.checkboxes.push(checkbox);
  3415. }
  3416.  
  3417. this.clearCheckBox = () => {
  3418. this.middle.classList.add('PopUp_hideBlock');
  3419. while (this.checkboxes.length) {
  3420. this.checkboxes.pop().parentNode.remove();
  3421. }
  3422. }
  3423.  
  3424. this.setMsgText = (text) => {
  3425. this.msgText.innerHTML = text;
  3426. }
  3427.  
  3428. this.getCheckBoxes = () => {
  3429. const checkBoxes = [];
  3430.  
  3431. for (const checkBox of this.checkboxes) {
  3432. checkBoxes.push({
  3433. name: checkBox.dataset.name,
  3434. label: checkBox.label,
  3435. checked: checkBox.checked
  3436. });
  3437. }
  3438.  
  3439. return checkBoxes;
  3440. }
  3441.  
  3442. this.confirm = async (msg, buttOpt, checkBoxes = []) => {
  3443. this.clearButtons();
  3444. this.clearCheckBox();
  3445. return new Promise((complete, failed) => {
  3446. this.setMsgText(msg);
  3447. if (!buttOpt) {
  3448. buttOpt = [{ msg: 'Ok', result: true, isInput: false }];
  3449. }
  3450. for (const checkBox of checkBoxes) {
  3451. this.addCheckBox(checkBox);
  3452. }
  3453. for (let butt of buttOpt) {
  3454. this.addButton(butt, (result) => {
  3455. result = result || butt.result;
  3456. complete(result);
  3457. popup.hide();
  3458. });
  3459. if (butt.isCancel) {
  3460. this.dialogPromice = {func: complete, result: butt.result};
  3461. }
  3462. }
  3463. this.show();
  3464. });
  3465. }
  3466.  
  3467. document.addEventListener('DOMContentLoaded', init);
  3468. });
  3469.  
  3470. /**
  3471. * Script control panel
  3472. *
  3473. * Панель управления скриптом
  3474. */
  3475. const scriptMenu = new (function () {
  3476.  
  3477. this.mainMenu,
  3478. this.buttons = [],
  3479. this.checkboxes = [];
  3480. this.option = {
  3481. showMenu: false,
  3482. showDetails: {}
  3483. };
  3484.  
  3485. this.init = function (option = {}) {
  3486. this.option = Object.assign(this.option, option);
  3487. this.option.showDetails = this.loadShowDetails();
  3488. addStyle();
  3489. addBlocks();
  3490. }
  3491.  
  3492. const addStyle = () => {
  3493. style = document.createElement('style');
  3494. style.innerText = `
  3495. .scriptMenu_status {
  3496. position: absolute;
  3497. z-index: 10001;
  3498. /* max-height: 30px; */
  3499. top: -1px;
  3500. left: 30%;
  3501. cursor: pointer;
  3502. border-radius: 0px 0px 10px 10px;
  3503. background: #190e08e6;
  3504. border: 1px #ce9767 solid;
  3505. font-size: 18px;
  3506. font-family: sans-serif;
  3507. font-weight: 600;
  3508. font-stretch: condensed;
  3509. letter-spacing: 1px;
  3510. color: #fce1ac;
  3511. text-shadow: 0px 0px 1px;
  3512. transition: 0.5s;
  3513. padding: 2px 10px 3px;
  3514. }
  3515. .scriptMenu_statusHide {
  3516. top: -35px;
  3517. height: 30px;
  3518. overflow: hidden;
  3519. }
  3520. .scriptMenu_label {
  3521. position: absolute;
  3522. top: 30%;
  3523. left: -4px;
  3524. z-index: 9999;
  3525. cursor: pointer;
  3526. width: 30px;
  3527. height: 30px;
  3528. background: radial-gradient(circle, #47a41b 0%, #1a2f04 100%);
  3529. border: 1px solid #1a2f04;
  3530. border-radius: 5px;
  3531. box-shadow:
  3532. inset 0px 2px 4px #83ce26,
  3533. inset 0px -4px 6px #1a2f04,
  3534. 0px 0px 2px black,
  3535. 0px 0px 0px 2px #ce9767;
  3536. }
  3537. .scriptMenu_label:hover {
  3538. filter: brightness(1.2);
  3539. }
  3540. .scriptMenu_arrowLabel {
  3541. width: 100%;
  3542. height: 100%;
  3543. background-size: 75%;
  3544. background-position: center;
  3545. background-repeat: no-repeat;
  3546. 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");
  3547. box-shadow: 0px 1px 2px #000;
  3548. border-radius: 5px;
  3549. filter: drop-shadow(0px 1px 2px #000D);
  3550. }
  3551. .scriptMenu_main {
  3552. position: absolute;
  3553. max-width: 285px;
  3554. z-index: 9999;
  3555. top: 50%;
  3556. transform: translateY(-40%);
  3557. background: #190e08e6;
  3558. border: 1px #ce9767 solid;
  3559. border-radius: 0px 10px 10px 0px;
  3560. border-left: none;
  3561. padding: 5px 10px 5px 5px;
  3562. box-sizing: border-box;
  3563. font-size: 15px;
  3564. font-family: sans-serif;
  3565. font-weight: 600;
  3566. font-stretch: condensed;
  3567. letter-spacing: 1px;
  3568. color: #fce1ac;
  3569. text-shadow: 0px 0px 1px;
  3570. transition: 1s;
  3571. display: flex;
  3572. flex-direction: column;
  3573. flex-wrap: nowrap;
  3574. }
  3575. .scriptMenu_showMenu {
  3576. display: none;
  3577. }
  3578. .scriptMenu_showMenu:checked~.scriptMenu_main {
  3579. left: 0px;
  3580. }
  3581. .scriptMenu_showMenu:not(:checked)~.scriptMenu_main {
  3582. left: -300px;
  3583. }
  3584. .scriptMenu_divInput {
  3585. margin: 2px;
  3586. }
  3587. .scriptMenu_divInputText {
  3588. margin: 2px;
  3589. align-self: center;
  3590. display: flex;
  3591. }
  3592. .scriptMenu_checkbox {
  3593. position: absolute;
  3594. z-index: -1;
  3595. opacity: 0;
  3596. }
  3597. .scriptMenu_checkbox+label {
  3598. display: inline-flex;
  3599. align-items: center;
  3600. user-select: none;
  3601. }
  3602. .scriptMenu_checkbox+label::before {
  3603. content: '';
  3604. display: inline-block;
  3605. width: 20px;
  3606. height: 20px;
  3607. border: 1px solid #cf9250;
  3608. border-radius: 7px;
  3609. margin-right: 7px;
  3610. }
  3611. .scriptMenu_checkbox:checked+label::before {
  3612. 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");
  3613. }
  3614. .scriptMenu_close {
  3615. width: 40px;
  3616. height: 40px;
  3617. position: absolute;
  3618. right: -18px;
  3619. top: -18px;
  3620. border: 3px solid #c18550;
  3621. border-radius: 20px;
  3622. background: radial-gradient(circle, rgba(190,30,35,1) 0%, rgba(0,0,0,1) 100%);
  3623. background-position-y: 3px;
  3624. box-shadow: -1px 1px 3px black;
  3625. cursor: pointer;
  3626. box-sizing: border-box;
  3627. }
  3628. .scriptMenu_close:hover {
  3629. filter: brightness(1.2);
  3630. }
  3631. .scriptMenu_crossClose {
  3632. width: 100%;
  3633. height: 100%;
  3634. background-size: 65%;
  3635. background-position: center;
  3636. background-repeat: no-repeat;
  3637. 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")
  3638. }
  3639. .scriptMenu_button {
  3640. user-select: none;
  3641. border-radius: 5px;
  3642. cursor: pointer;
  3643. padding: 5px 14px 8px;
  3644. margin: 4px;
  3645. background: radial-gradient(circle, rgba(165,120,56,1) 80%, rgba(0,0,0,1) 110%);
  3646. box-shadow: inset 0px -4px 6px #442901, inset 0px 1px 6px #442901, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 2px #ce9767;
  3647. }
  3648. .scriptMenu_button:hover {
  3649. filter: brightness(1.2);
  3650. }
  3651. .scriptMenu_button:active {
  3652. box-shadow: inset 0px 4px 6px #442901, inset 0px 4px 6px #442901, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 2px #ce9767;
  3653. }
  3654. .scriptMenu_buttonText {
  3655. color: #fce5b7;
  3656. text-shadow: 0px 1px 2px black;
  3657. text-align: center;
  3658. }
  3659. .scriptMenu_header {
  3660. text-align: center;
  3661. align-self: center;
  3662. font-size: 15px;
  3663. margin: 0px 15px;
  3664. }
  3665. .scriptMenu_header a {
  3666. color: #fce5b7;
  3667. text-decoration: none;
  3668. }
  3669. .scriptMenu_InputText {
  3670. text-align: center;
  3671. width: 130px;
  3672. height: 24px;
  3673. border: 1px solid #cf9250;
  3674. border-radius: 9px;
  3675. background: transparent;
  3676. color: #fce1ac;
  3677. padding: 0px 10px;
  3678. box-sizing: border-box;
  3679. }
  3680. .scriptMenu_InputText:focus {
  3681. filter: brightness(1.2);
  3682. outline: 0;
  3683. }
  3684. .scriptMenu_InputText::placeholder {
  3685. color: #fce1ac75;
  3686. }
  3687. .scriptMenu_Summary {
  3688. cursor: pointer;
  3689. margin-left: 7px;
  3690. }
  3691. .scriptMenu_Details {
  3692. align-self: center;
  3693. }
  3694. `;
  3695. document.head.appendChild(style);
  3696. }
  3697.  
  3698. const addBlocks = () => {
  3699. const main = document.createElement('div');
  3700. document.body.appendChild(main);
  3701.  
  3702. this.status = document.createElement('div');
  3703. this.status.classList.add('scriptMenu_status');
  3704. this.setStatus('');
  3705. main.appendChild(this.status);
  3706.  
  3707. const label = document.createElement('label');
  3708. label.classList.add('scriptMenu_label');
  3709. label.setAttribute('for', 'checkbox_showMenu');
  3710. main.appendChild(label);
  3711.  
  3712. const arrowLabel = document.createElement('div');
  3713. arrowLabel.classList.add('scriptMenu_arrowLabel');
  3714. label.appendChild(arrowLabel);
  3715.  
  3716. const checkbox = document.createElement('input');
  3717. checkbox.type = 'checkbox';
  3718. checkbox.id = 'checkbox_showMenu';
  3719. checkbox.checked = this.option.showMenu;
  3720. checkbox.classList.add('scriptMenu_showMenu');
  3721. main.appendChild(checkbox);
  3722.  
  3723. this.mainMenu = document.createElement('div');
  3724. this.mainMenu.classList.add('scriptMenu_main');
  3725. main.appendChild(this.mainMenu);
  3726.  
  3727. const closeButton = document.createElement('label');
  3728. closeButton.classList.add('scriptMenu_close');
  3729. closeButton.setAttribute('for', 'checkbox_showMenu');
  3730. this.mainMenu.appendChild(closeButton);
  3731.  
  3732. const crossClose = document.createElement('div');
  3733. crossClose.classList.add('scriptMenu_crossClose');
  3734. closeButton.appendChild(crossClose);
  3735. }
  3736.  
  3737. this.setStatus = (text, onclick) => {
  3738. if (!text) {
  3739. this.status.classList.add('scriptMenu_statusHide');
  3740. } else {
  3741. this.status.classList.remove('scriptMenu_statusHide');
  3742. this.status.innerHTML = text;
  3743. }
  3744.  
  3745. if (typeof onclick == 'function') {
  3746. this.status.addEventListener("click", onclick, {
  3747. once: true
  3748. });
  3749. }
  3750. }
  3751.  
  3752. /**
  3753. * Adding a text element
  3754. *
  3755. * Добавление текстового элемента
  3756. * @param {String} text text // текст
  3757. * @param {Function} func Click function // функция по клику
  3758. * @param {HTMLDivElement} main parent // родитель
  3759. */
  3760. this.addHeader = (text, func, main) => {
  3761. main = main || this.mainMenu;
  3762. const header = document.createElement('div');
  3763. header.classList.add('scriptMenu_header');
  3764. header.innerHTML = text;
  3765. if (typeof func == 'function') {
  3766. header.addEventListener('click', func);
  3767. }
  3768. main.appendChild(header);
  3769. }
  3770.  
  3771. /**
  3772. * Adding a button
  3773. *
  3774. * Добавление кнопки
  3775. * @param {String} text
  3776. * @param {Function} func
  3777. * @param {String} title
  3778. * @param {HTMLDivElement} main parent // родитель
  3779. */
  3780. this.addButton = (text, func, title, main) => {
  3781. main = main || this.mainMenu;
  3782. const button = document.createElement('div');
  3783. button.classList.add('scriptMenu_button');
  3784. button.title = title;
  3785. button.addEventListener('click', func);
  3786. main.appendChild(button);
  3787.  
  3788. const buttonText = document.createElement('div');
  3789. buttonText.classList.add('scriptMenu_buttonText');
  3790. buttonText.innerText = text;
  3791. button.appendChild(buttonText);
  3792. this.buttons.push(button);
  3793.  
  3794. return button;
  3795. }
  3796.  
  3797. /**
  3798. * Adding checkbox
  3799. *
  3800. * Добавление чекбокса
  3801. * @param {String} label
  3802. * @param {String} title
  3803. * @param {HTMLDivElement} main parent // родитель
  3804. * @returns
  3805. */
  3806. this.addCheckbox = (label, title, main) => {
  3807. main = main || this.mainMenu;
  3808. const divCheckbox = document.createElement('div');
  3809. divCheckbox.classList.add('scriptMenu_divInput');
  3810. divCheckbox.title = title;
  3811. main.appendChild(divCheckbox);
  3812.  
  3813. const checkbox = document.createElement('input');
  3814. checkbox.type = 'checkbox';
  3815. checkbox.id = 'scriptMenuCheckbox' + this.checkboxes.length;
  3816. checkbox.classList.add('scriptMenu_checkbox');
  3817. divCheckbox.appendChild(checkbox)
  3818.  
  3819. const checkboxLabel = document.createElement('label');
  3820. checkboxLabel.innerText = label;
  3821. checkboxLabel.setAttribute('for', checkbox.id);
  3822. divCheckbox.appendChild(checkboxLabel);
  3823.  
  3824. this.checkboxes.push(checkbox);
  3825. return checkbox;
  3826. }
  3827.  
  3828. /**
  3829. * Adding input field
  3830. *
  3831. * Добавление поля ввода
  3832. * @param {String} title
  3833. * @param {String} placeholder
  3834. * @param {HTMLDivElement} main parent // родитель
  3835. * @returns
  3836. */
  3837. this.addInputText = (title, placeholder, main) => {
  3838. main = main || this.mainMenu;
  3839. const divInputText = document.createElement('div');
  3840. divInputText.classList.add('scriptMenu_divInputText');
  3841. divInputText.title = title;
  3842. main.appendChild(divInputText);
  3843.  
  3844. const newInputText = document.createElement('input');
  3845. newInputText.type = 'text';
  3846. if (placeholder) {
  3847. newInputText.placeholder = placeholder;
  3848. }
  3849. newInputText.classList.add('scriptMenu_InputText');
  3850. divInputText.appendChild(newInputText)
  3851. return newInputText;
  3852. }
  3853.  
  3854. /**
  3855. * Adds a dropdown block
  3856. *
  3857. * Добавляет раскрывающийся блок
  3858. * @param {String} summary
  3859. * @param {String} name
  3860. * @returns
  3861. */
  3862. this.addDetails = (summaryText, name = null) => {
  3863. const details = document.createElement('details');
  3864. details.classList.add('scriptMenu_Details');
  3865. this.mainMenu.appendChild(details);
  3866.  
  3867. const summary = document.createElement('summary');
  3868. summary.classList.add('scriptMenu_Summary');
  3869. summary.innerText = summaryText;
  3870. if (name) {
  3871. const self = this;
  3872. details.open = this.option.showDetails[name];
  3873. details.dataset.name = name;
  3874. summary.addEventListener('click', () => {
  3875. self.option.showDetails[details.dataset.name] = !details.open;
  3876. self.saveShowDetails(self.option.showDetails);
  3877. });
  3878. }
  3879. details.appendChild(summary);
  3880.  
  3881. return details;
  3882. }
  3883.  
  3884. /**
  3885. * Saving the expanded state of the details blocks
  3886. *
  3887. * Сохранение состояния развенутости блоков details
  3888. * @param {*} value
  3889. */
  3890. this.saveShowDetails = (value) => {
  3891. localStorage.setItem('scriptMenu_showDetails', JSON.stringify(value));
  3892. }
  3893.  
  3894. /**
  3895. * Loading the state of expanded blocks details
  3896. *
  3897. * Загрузка состояния развенутости блоков details
  3898. * @returns
  3899. */
  3900. this.loadShowDetails = () => {
  3901. let showDetails = localStorage.getItem('scriptMenu_showDetails');
  3902.  
  3903. if (!showDetails) {
  3904. return {};
  3905. }
  3906.  
  3907. try {
  3908. showDetails = JSON.parse(showDetails);
  3909. } catch (e) {
  3910. return {};
  3911. }
  3912.  
  3913. return showDetails;
  3914. }
  3915. });
  3916.  
  3917. /**
  3918. * Пример использования
  3919. scriptMenu.init();
  3920. scriptMenu.addHeader('v1.508');
  3921. scriptMenu.addCheckbox('testHack', 'Тестовый взлом игры!');
  3922. scriptMenu.addButton('Запуск!', () => console.log('click'), 'подсказака');
  3923. scriptMenu.addInputText('input подсказака');
  3924. */
  3925. /**
  3926. * Game Library
  3927. *
  3928. * Игровая библиотека
  3929. */
  3930. class Library {
  3931. defaultLibUrl = 'https://heroesru-a.akamaihd.net/vk/v1101/lib/lib.json';
  3932.  
  3933. constructor() {
  3934. if (!Library.instance) {
  3935. Library.instance = this;
  3936. }
  3937.  
  3938. return Library.instance;
  3939. }
  3940.  
  3941. async load() {
  3942. try {
  3943. await this.getUrlLib();
  3944. console.log(this.defaultLibUrl);
  3945. this.data = await fetch(this.defaultLibUrl).then(e => e.json())
  3946. } catch (error) {
  3947. console.error('Не удалось загрузить библиотеку', error)
  3948. }
  3949. }
  3950.  
  3951. async getUrlLib() {
  3952. try {
  3953. const db = new Database('hw_cache', 'cache');
  3954. await db.open();
  3955. const cacheLibFullUrl = await db.get('lib/lib.json.gz', false);
  3956. this.defaultLibUrl = cacheLibFullUrl.fullUrl.split('.gz').shift();
  3957. } catch(e) {}
  3958. }
  3959.  
  3960. getData(id) {
  3961. return this.data[id];
  3962. }
  3963. }
  3964.  
  3965. this.lib = new Library();
  3966. /**
  3967. * Database
  3968. *
  3969. * База данных
  3970. */
  3971. class Database {
  3972. constructor(dbName, storeName) {
  3973. this.dbName = dbName;
  3974. this.storeName = storeName;
  3975. this.db = null;
  3976. }
  3977.  
  3978. async open() {
  3979. return new Promise((resolve, reject) => {
  3980. const request = indexedDB.open(this.dbName);
  3981.  
  3982. request.onerror = () => {
  3983. reject(new Error(`Failed to open database ${this.dbName}`));
  3984. };
  3985.  
  3986. request.onsuccess = () => {
  3987. this.db = request.result;
  3988. resolve();
  3989. };
  3990.  
  3991. request.onupgradeneeded = (event) => {
  3992. const db = event.target.result;
  3993. if (!db.objectStoreNames.contains(this.storeName)) {
  3994. db.createObjectStore(this.storeName);
  3995. }
  3996. };
  3997. });
  3998. }
  3999.  
  4000. async set(key, value) {
  4001. return new Promise((resolve, reject) => {
  4002. const transaction = this.db.transaction([this.storeName], 'readwrite');
  4003. const store = transaction.objectStore(this.storeName);
  4004. const request = store.put(value, key);
  4005.  
  4006. request.onerror = () => {
  4007. reject(new Error(`Failed to save value with key ${key}`));
  4008. };
  4009.  
  4010. request.onsuccess = () => {
  4011. resolve();
  4012. };
  4013. });
  4014. }
  4015.  
  4016. async get(key, def) {
  4017. return new Promise((resolve, reject) => {
  4018. const transaction = this.db.transaction([this.storeName], 'readonly');
  4019. const store = transaction.objectStore(this.storeName);
  4020. const request = store.get(key);
  4021.  
  4022. request.onerror = () => {
  4023. resolve(def);
  4024. };
  4025.  
  4026. request.onsuccess = () => {
  4027. resolve(request.result);
  4028. };
  4029. });
  4030. }
  4031.  
  4032. async delete(key) {
  4033. return new Promise((resolve, reject) => {
  4034. const transaction = this.db.transaction([this.storeName], 'readwrite');
  4035. const store = transaction.objectStore(this.storeName);
  4036. const request = store.delete(key);
  4037.  
  4038. request.onerror = () => {
  4039. reject(new Error(`Failed to delete value with key ${key}`));
  4040. };
  4041.  
  4042. request.onsuccess = () => {
  4043. resolve();
  4044. };
  4045. });
  4046. }
  4047. }
  4048.  
  4049. /**
  4050. * Returns the stored value
  4051. *
  4052. * Возвращает сохраненное значение
  4053. */
  4054. function getSaveVal(saveName, def) {
  4055. const result = storage.get(saveName, def);
  4056. return result;
  4057. }
  4058.  
  4059. /**
  4060. * Stores value
  4061. *
  4062. * Сохраняет значение
  4063. */
  4064. function setSaveVal(saveName, value) {
  4065. storage.set(saveName, value);
  4066. }
  4067.  
  4068. /**
  4069. * Database initialization
  4070. *
  4071. * Инициализация базы данных
  4072. */
  4073. const db = new Database(GM_info.script.name, 'settings');
  4074.  
  4075. /**
  4076. * Data store
  4077. *
  4078. * Хранилище данных
  4079. */
  4080. const storage = {
  4081. userId: 0,
  4082. /**
  4083. * Default values
  4084. *
  4085. * Значения по умолчанию
  4086. */
  4087. values: [
  4088. ...Object.entries(checkboxes).map(e => ({ [e[0]]: e[1].default })),
  4089. ...Object.entries(inputs).map(e => ({ [e[0]]: e[1].default })),
  4090. ].reduce((acc, obj) => ({ ...acc, ...obj }), {}),
  4091. name: GM_info.script.name,
  4092. get: function (key, def) {
  4093. if (key in this.values) {
  4094. return this.values[key];
  4095. }
  4096. return def;
  4097. },
  4098. set: function (key, value) {
  4099. this.values[key] = value;
  4100. db.set(this.userId, this.values).catch(
  4101. e => null
  4102. );
  4103. localStorage[this.name + ':' + key] = value;
  4104. },
  4105. delete: function (key) {
  4106. delete this.values[key];
  4107. db.set(this.userId, this.values);
  4108. delete localStorage[this.name + ':' + key];
  4109. }
  4110. }
  4111.  
  4112. /**
  4113. * Returns all keys from localStorage that start with prefix (for migration)
  4114. *
  4115. * Возвращает все ключи из localStorage которые начинаются с prefix (для миграции)
  4116. */
  4117. function getAllValuesStartingWith(prefix) {
  4118. const values = [];
  4119. for (let i = 0; i < localStorage.length; i++) {
  4120. const key = localStorage.key(i);
  4121. if (key.startsWith(prefix)) {
  4122. const val = localStorage.getItem(key);
  4123. const keyValue = key.split(':')[1];
  4124. values.push({ key: keyValue, val });
  4125. }
  4126. }
  4127. return values;
  4128. }
  4129.  
  4130. /**
  4131. * Opens or migrates to a database
  4132. *
  4133. * Открывает или мигрирует в базу данных
  4134. */
  4135. async function openOrMigrateDatabase(userId) {
  4136. storage.userId = userId;
  4137. try {
  4138. await db.open();
  4139. } catch(e) {
  4140. return;
  4141. }
  4142. let settings = await db.get(userId, false);
  4143.  
  4144. if (settings) {
  4145. storage.values = settings;
  4146. return;
  4147. }
  4148.  
  4149. const values = getAllValuesStartingWith(GM_info.script.name);
  4150. for (const value of values) {
  4151. let val = null;
  4152. try {
  4153. val = JSON.parse(value.val);
  4154. } catch {
  4155. break;
  4156. }
  4157. storage.values[value.key] = val;
  4158. }
  4159. await db.set(userId, storage.values);
  4160. }
  4161.  
  4162. /**
  4163. * Sending expeditions
  4164. *
  4165. * Отправка экспедиций
  4166. */
  4167. function checkExpedition() {
  4168. return new Promise((resolve, reject) => {
  4169. const expedition = new Expedition(resolve, reject);
  4170. expedition.start();
  4171. });
  4172. }
  4173.  
  4174. class Expedition {
  4175. checkExpedInfo = {
  4176. calls: [{
  4177. name: "expeditionGet",
  4178. args: {},
  4179. ident: "expeditionGet"
  4180. }, {
  4181. name: "heroGetAll",
  4182. args: {},
  4183. ident: "heroGetAll"
  4184. }]
  4185. }
  4186.  
  4187. constructor(resolve, reject) {
  4188. this.resolve = resolve;
  4189. this.reject = reject;
  4190. }
  4191.  
  4192. async start() {
  4193. const data = await Send(JSON.stringify(this.checkExpedInfo));
  4194.  
  4195. const expedInfo = data.results[0].result.response;
  4196. const dataHeroes = data.results[1].result.response;
  4197. const dataExped = { useHeroes: [], exped: [] };
  4198. const calls = [];
  4199.  
  4200. /**
  4201. * Adding expeditions to collect
  4202. * Добавляем экспедиции для сбора
  4203. */
  4204. for (var n in expedInfo) {
  4205. const exped = expedInfo[n];
  4206. const dateNow = (Date.now() / 1000);
  4207. if (exped.status == 2 && exped.endTime != 0 && dateNow > exped.endTime) {
  4208. calls.push({
  4209. name: "expeditionFarm",
  4210. args: { expeditionId: exped.id },
  4211. ident: "expeditionFarm_" + exped.id
  4212. });
  4213. } else {
  4214. dataExped.useHeroes = dataExped.useHeroes.concat(exped.heroes);
  4215. }
  4216. if (exped.status == 1) {
  4217. dataExped.exped.push({ id: exped.id, power: exped.power });
  4218. }
  4219. }
  4220. dataExped.exped = dataExped.exped.sort((a, b) => (b.power - a.power));
  4221.  
  4222. /**
  4223. * Putting together a list of heroes
  4224. * Собираем список героев
  4225. */
  4226. const heroesArr = [];
  4227. for (let n in dataHeroes) {
  4228. const hero = dataHeroes[n];
  4229. if (hero.xp > 0 && !dataExped.useHeroes.includes(hero.id)) {
  4230. heroesArr.push({ id: hero.id, power: hero.power })
  4231. }
  4232. }
  4233.  
  4234. /**
  4235. * Adding expeditions to send
  4236. * Добавляем экспедиции для отправки
  4237. */
  4238. heroesArr.sort((a, b) => (a.power - b.power));
  4239. for (const exped of dataExped.exped) {
  4240. let heroesIds = this.selectionHeroes(heroesArr, exped.power);
  4241. if (heroesIds && heroesIds.length > 4) {
  4242. for (let q in heroesArr) {
  4243. if (heroesIds.includes(heroesArr[q].id)) {
  4244. delete heroesArr[q];
  4245. }
  4246. }
  4247. calls.push({
  4248. name: "expeditionSendHeroes",
  4249. args: {
  4250. expeditionId: exped.id,
  4251. heroes: heroesIds
  4252. },
  4253. ident: "expeditionSendHeroes_" + exped.id
  4254. });
  4255. }
  4256. }
  4257.  
  4258. await Send(JSON.stringify({ calls }));
  4259. this.end();
  4260. }
  4261.  
  4262. /**
  4263. * Selection of heroes for expeditions
  4264. *
  4265. * Подбор героев для экспедиций
  4266. */
  4267. selectionHeroes(heroes, power) {
  4268. const resultHeroers = [];
  4269. const heroesIds = [];
  4270. for (let q = 0; q < 5; q++) {
  4271. for (let i in heroes) {
  4272. let hero = heroes[i];
  4273. if (heroesIds.includes(hero.id)) {
  4274. continue;
  4275. }
  4276.  
  4277. const summ = resultHeroers.reduce((acc, hero) => acc + hero.power, 0);
  4278. const need = Math.round((power - summ) / (5 - resultHeroers.length));
  4279. if (hero.power > need) {
  4280. resultHeroers.push(hero);
  4281. heroesIds.push(hero.id);
  4282. break;
  4283. }
  4284. }
  4285. }
  4286.  
  4287. const summ = resultHeroers.reduce((acc, hero) => acc + hero.power, 0);
  4288. if (summ < power) {
  4289. return false;
  4290. }
  4291. return heroesIds;
  4292. }
  4293.  
  4294. /**
  4295. * Ends expedition script
  4296. *
  4297. * Завершает скрипт экспедиции
  4298. */
  4299. end() {
  4300. setProgress(I18N('EXPEDITIONS_SENT'), true);
  4301. this.resolve()
  4302. }
  4303. }
  4304.  
  4305. /**
  4306. * Walkthrough of the dungeon
  4307. *
  4308. * Прохождение подземелья
  4309. */
  4310. function testDungeon() {
  4311. return new Promise((resolve, reject) => {
  4312. const dung = new executeDungeon(resolve, reject);
  4313. const titanit = getInput('countTitanit');
  4314. dung.start(titanit);
  4315. });
  4316. }
  4317.  
  4318. /**
  4319. * Walkthrough of the dungeon
  4320. *
  4321. * Прохождение подземелья
  4322. */
  4323. function executeDungeon(resolve, reject) {
  4324. dungeonActivity = 0;
  4325. maxDungeonActivity = 150;
  4326.  
  4327. titanGetAll = [];
  4328.  
  4329. teams = {
  4330. heroes: [],
  4331. earth: [],
  4332. fire: [],
  4333. neutral: [],
  4334. water: [],
  4335. }
  4336.  
  4337. titanStats = [];
  4338.  
  4339. titansStates = {};
  4340.  
  4341. callsExecuteDungeon = {
  4342. calls: [{
  4343. name: "dungeonGetInfo",
  4344. args: {},
  4345. ident: "dungeonGetInfo"
  4346. }, {
  4347. name: "teamGetAll",
  4348. args: {},
  4349. ident: "teamGetAll"
  4350. }, {
  4351. name: "teamGetFavor",
  4352. args: {},
  4353. ident: "teamGetFavor"
  4354. }, {
  4355. name: "clanGetInfo",
  4356. args: {},
  4357. ident: "clanGetInfo"
  4358. }, {
  4359. name: "titanGetAll",
  4360. args: {},
  4361. ident: "titanGetAll"
  4362. }, {
  4363. name: "inventoryGet",
  4364. args: {},
  4365. ident: "inventoryGet"
  4366. }]
  4367. }
  4368.  
  4369. this.start = function(titanit) {
  4370. maxDungeonActivity = titanit || getInput('countTitanit');
  4371. send(JSON.stringify(callsExecuteDungeon), startDungeon);
  4372. }
  4373.  
  4374. /**
  4375. * Getting data on the dungeon
  4376. *
  4377. * Получаем данные по подземелью
  4378. */
  4379. function startDungeon(e) {
  4380. res = e.results;
  4381. dungeonGetInfo = res[0].result.response;
  4382. if (!dungeonGetInfo) {
  4383. endDungeon('noDungeon', res);
  4384. return;
  4385. }
  4386. teamGetAll = res[1].result.response;
  4387. teamGetFavor = res[2].result.response;
  4388. dungeonActivity = res[3].result.response.stat.todayDungeonActivity;
  4389. titanGetAll = Object.values(res[4].result.response);
  4390. countPredictionCard = res[5].result.response.consumable[81];
  4391.  
  4392. teams.hero = {
  4393. favor: teamGetFavor.dungeon_hero,
  4394. heroes: teamGetAll.dungeon_hero.filter(id => id < 6000),
  4395. teamNum: 0,
  4396. }
  4397. heroPet = teamGetAll.dungeon_hero.filter(id => id >= 6000).pop();
  4398. if (heroPet) {
  4399. teams.hero.pet = heroPet;
  4400. }
  4401.  
  4402. teams.neutral = {
  4403. favor: {},
  4404. heroes: getTitanTeam(titanGetAll, 'neutral'),
  4405. teamNum: 0,
  4406. };
  4407. teams.water = {
  4408. favor: {},
  4409. heroes: getTitanTeam(titanGetAll, 'water'),
  4410. teamNum: 0,
  4411. };
  4412. teams.fire = {
  4413. favor: {},
  4414. heroes: getTitanTeam(titanGetAll, 'fire'),
  4415. teamNum: 0,
  4416. };
  4417. teams.earth = {
  4418. favor: {},
  4419. heroes: getTitanTeam(titanGetAll, 'earth'),
  4420. teamNum: 0,
  4421. };
  4422.  
  4423.  
  4424. checkFloor(dungeonGetInfo);
  4425. }
  4426.  
  4427. function getTitanTeam(titans, type) {
  4428. switch (type) {
  4429. case 'neutral':
  4430. return titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  4431. case 'water':
  4432. return titans.filter(e => e.id.toString().slice(2, 3) == '0').map(e => e.id);
  4433. case 'fire':
  4434. return titans.filter(e => e.id.toString().slice(2, 3) == '1').map(e => e.id);
  4435. case 'earth':
  4436. return titans.filter(e => e.id.toString().slice(2, 3) == '2').map(e => e.id);
  4437. }
  4438. }
  4439.  
  4440. function getNeutralTeam() {
  4441. const titans = titanGetAll.filter(e => !titansStates[e.id]?.isDead)
  4442. return titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  4443. }
  4444.  
  4445. function fixTitanTeam(titans) {
  4446. titans.heroes = titans.heroes.filter(e => !titansStates[e]?.isDead);
  4447. return titans;
  4448. }
  4449.  
  4450. /**
  4451. * Checking the floor
  4452. *
  4453. * Проверяем этаж
  4454. */
  4455. async function checkFloor(dungeonInfo) {
  4456. if (!('floor' in dungeonInfo) || dungeonInfo.floor?.state == 2) {
  4457. saveProgress();
  4458. return;
  4459. }
  4460. // console.log(dungeonInfo, dungeonActivity);
  4461. setProgress(`${I18N('DUNGEON')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity}`);
  4462. if (dungeonActivity >= maxDungeonActivity) {
  4463. endDungeon('endDungeon', 'maxActive ' + dungeonActivity + '/' + maxDungeonActivity);
  4464. return;
  4465. }
  4466. titansStates = dungeonInfo.states.titans;
  4467. titanStats = titanObjToArray(titansStates);
  4468. const floorChoices = dungeonInfo.floor.userData;
  4469. const floorType = dungeonInfo.floorType;
  4470. //const primeElement = dungeonInfo.elements.prime;
  4471. if (floorType == "battle") {
  4472. const calls = [];
  4473. for (let teamNum in floorChoices) {
  4474. attackerType = floorChoices[teamNum].attackerType;
  4475. const args = fixTitanTeam(teams[attackerType]);
  4476. if (attackerType == 'neutral') {
  4477. args.heroes = getNeutralTeam();
  4478. }
  4479. if (!args.heroes.length) {
  4480. continue;
  4481. }
  4482. args.teamNum = teamNum;
  4483. calls.push({
  4484. name: "dungeonStartBattle",
  4485. args,
  4486. ident: "body_" + teamNum
  4487. })
  4488. }
  4489. if (!calls.length) {
  4490. endDungeon('endDungeon', 'All Dead');
  4491. return;
  4492. }
  4493. const battleDatas = await Send(JSON.stringify({ calls }))
  4494. .then(e => e.results.map(n => n.result.response))
  4495. const battleResults = [];
  4496. for (n in battleDatas) {
  4497. battleData = battleDatas[n]
  4498. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  4499. battleResults.push(await Calc(battleData).then(result => {
  4500. result.teamNum = n;
  4501. result.attackerType = floorChoices[n].attackerType;
  4502. return result;
  4503. }));
  4504. }
  4505. processingPromises(battleResults)
  4506. }
  4507. }
  4508.  
  4509. function processingPromises(results) {
  4510. let selectBattle = results[0];
  4511. if (results.length < 2) {
  4512. // console.log(selectBattle);
  4513. if (!selectBattle.result.win) {
  4514. endDungeon('dungeonEndBattle\n', selectBattle);
  4515. return;
  4516. }
  4517. endBattle(selectBattle);
  4518. return;
  4519. }
  4520.  
  4521. selectBattle = false;
  4522. let bestState = -1000;
  4523. for (const result of results) {
  4524. const recovery = getState(result);
  4525. if (recovery > bestState) {
  4526. bestState = recovery;
  4527. selectBattle = result
  4528. }
  4529. }
  4530. // console.log(selectBattle.teamNum, results);
  4531. if (!selectBattle || bestState <= -1000) {
  4532. endDungeon('dungeonEndBattle\n', results);
  4533. return;
  4534. }
  4535.  
  4536. startBattle(selectBattle.teamNum, selectBattle.attackerType)
  4537. .then(endBattle);
  4538. }
  4539.  
  4540. /**
  4541. * Let's start the fight
  4542. *
  4543. * Начинаем бой
  4544. */
  4545. function startBattle(teamNum, attackerType) {
  4546. return new Promise(function (resolve, reject) {
  4547. args = fixTitanTeam(teams[attackerType]);
  4548. args.teamNum = teamNum;
  4549. if (attackerType == 'neutral') {
  4550. const titans = titanGetAll.filter(e => !titansStates[e.id]?.isDead)
  4551. args.heroes = titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  4552. }
  4553. startBattleCall = {
  4554. calls: [{
  4555. name: "dungeonStartBattle",
  4556. args,
  4557. ident: "body"
  4558. }]
  4559. }
  4560. send(JSON.stringify(startBattleCall), resultBattle, {
  4561. resolve,
  4562. teamNum,
  4563. attackerType
  4564. });
  4565. });
  4566. }
  4567. /**
  4568. * Returns the result of the battle in a promise
  4569. *
  4570. * Возращает резульат боя в промис
  4571. */
  4572. function resultBattle(resultBattles, args) {
  4573. battleData = resultBattles.results[0].result.response;
  4574. battleType = "get_tower";
  4575. if (battleData.type == "dungeon_titan") {
  4576. battleType = "get_titan";
  4577. }
  4578. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  4579. BattleCalc(battleData, battleType, function (result) {
  4580. result.teamNum = args.teamNum;
  4581. result.attackerType = args.attackerType;
  4582. args.resolve(result);
  4583. });
  4584. }
  4585. /**
  4586. * Finishing the fight
  4587. *
  4588. * Заканчиваем бой
  4589. */
  4590. async function endBattle(battleInfo) {
  4591. if (battleInfo.result.win) {
  4592. const args = {
  4593. result: battleInfo.result,
  4594. progress: battleInfo.progress,
  4595. }
  4596. if (countPredictionCard > 0) {
  4597. args.isRaid = true;
  4598. } else {
  4599. const timer = getTimer(battleInfo.battleTime);
  4600. console.log(timer);
  4601. await countdownTimer(timer, `${I18N('DUNGEON')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity}`);
  4602. }
  4603. const calls = [{
  4604. name: "dungeonEndBattle",
  4605. args,
  4606. ident: "body"
  4607. }];
  4608. lastDungeonBattleData = null;
  4609. send(JSON.stringify({ calls }), resultEndBattle);
  4610. } else {
  4611. endDungeon('dungeonEndBattle win: false\n', battleInfo);
  4612. }
  4613. }
  4614.  
  4615. /**
  4616. * Getting and processing battle results
  4617. *
  4618. * Получаем и обрабатываем результаты боя
  4619. */
  4620. function resultEndBattle(e) {
  4621. if ('error' in e) {
  4622. popup.confirm(I18N('ERROR_MSG', {
  4623. name: e.error.name,
  4624. description: e.error.description,
  4625. }));
  4626. endDungeon('errorRequest', e);
  4627. return;
  4628. }
  4629. battleResult = e.results[0].result.response;
  4630. if ('error' in battleResult) {
  4631. endDungeon('errorBattleResult', battleResult);
  4632. return;
  4633. }
  4634. dungeonGetInfo = battleResult.dungeon ?? battleResult;
  4635. dungeonActivity += battleResult.reward.dungeonActivity ?? 0;
  4636. checkFloor(dungeonGetInfo);
  4637. }
  4638.  
  4639. /**
  4640. * Returns the coefficient of condition of the
  4641. * difference in titanium before and after the battle
  4642. *
  4643. * Возвращает коэффициент состояния титанов после боя
  4644. */
  4645. function getState(result) {
  4646. if (!result.result.win) {
  4647. return -1000;
  4648. }
  4649.  
  4650. let beforeSumFactor = 0;
  4651. const beforeTitans = result.battleData.attackers;
  4652. for (let titanId in beforeTitans) {
  4653. const titan = beforeTitans[titanId];
  4654. const state = titan.state;
  4655. let factor = 1;
  4656. if (state) {
  4657. const hp = state.hp / titan.hp;
  4658. const energy = state.energy / 1e3;
  4659. factor = hp + energy / 20
  4660. }
  4661. beforeSumFactor += factor;
  4662. }
  4663.  
  4664. let afterSumFactor = 0;
  4665. const afterTitans = result.progress[0].attackers.heroes;
  4666. for (let titanId in afterTitans) {
  4667. const titan = afterTitans[titanId];
  4668. const hp = titan.hp / beforeTitans[titanId].hp;
  4669. const energy = titan.energy / 1e3;
  4670. const factor = hp + energy / 20;
  4671. afterSumFactor += factor;
  4672. }
  4673. return afterSumFactor - beforeSumFactor;
  4674. }
  4675.  
  4676. /**
  4677. * Converts an object with IDs to an array with IDs
  4678. *
  4679. * Преобразует объект с идетификаторами в массив с идетификаторами
  4680. */
  4681. function titanObjToArray(obj) {
  4682. let titans = [];
  4683. for (let id in obj) {
  4684. obj[id].id = id;
  4685. titans.push(obj[id]);
  4686. }
  4687. return titans;
  4688. }
  4689.  
  4690. function saveProgress() {
  4691. let saveProgressCall = {
  4692. calls: [{
  4693. name: "dungeonSaveProgress",
  4694. args: {},
  4695. ident: "body"
  4696. }]
  4697. }
  4698. send(JSON.stringify(saveProgressCall), resultEndBattle);
  4699. }
  4700.  
  4701. function endDungeon(reason, info) {
  4702. console.warn(reason, info);
  4703. setProgress(`${I18N('DUNGEON')} ${I18N('COMPLETED')}`, true);
  4704. resolve();
  4705. }
  4706. }
  4707.  
  4708. /**
  4709. * Passing the tower
  4710. *
  4711. * Прохождение башни
  4712. */
  4713. function testTower() {
  4714. return new Promise((resolve, reject) => {
  4715. tower = new executeTower(resolve, reject);
  4716. tower.start();
  4717. });
  4718. }
  4719.  
  4720. /**
  4721. * Passing the tower
  4722. *
  4723. * Прохождение башни
  4724. */
  4725. function executeTower(resolve, reject) {
  4726. lastTowerInfo = {};
  4727.  
  4728. scullCoin = 0;
  4729.  
  4730. heroGetAll = [];
  4731.  
  4732. heroesStates = {};
  4733.  
  4734. argsBattle = {
  4735. heroes: [],
  4736. favor: {},
  4737. };
  4738.  
  4739. callsExecuteTower = {
  4740. calls: [{
  4741. name: "towerGetInfo",
  4742. args: {},
  4743. ident: "towerGetInfo"
  4744. }, {
  4745. name: "teamGetAll",
  4746. args: {},
  4747. ident: "teamGetAll"
  4748. }, {
  4749. name: "teamGetFavor",
  4750. args: {},
  4751. ident: "teamGetFavor"
  4752. }, {
  4753. name: "inventoryGet",
  4754. args: {},
  4755. ident: "inventoryGet"
  4756. }, {
  4757. name: "heroGetAll",
  4758. args: {},
  4759. ident: "heroGetAll"
  4760. }]
  4761. }
  4762.  
  4763. buffIds = [
  4764. {id: 0, cost: 0, isBuy: false}, // plug // заглушка
  4765. {id: 1, cost: 1, isBuy: true}, // 3% attack // 3% атака
  4766. {id: 2, cost: 6, isBuy: true}, // 2% attack // 2% атака
  4767. {id: 3, cost: 16, isBuy: true}, // 4% attack // 4% атака
  4768. {id: 4, cost: 40, isBuy: true}, // 8% attack // 8% атака
  4769. {id: 5, cost: 1, isBuy: true}, // 10% armor // 10% броня
  4770. {id: 6, cost: 6, isBuy: true}, // 5% armor // 5% броня
  4771. {id: 7, cost: 16, isBuy: true}, // 10% armor // 10% броня
  4772. {id: 8, cost: 40, isBuy: true}, // 20% armor // 20% броня
  4773. { id: 9, cost: 1, isBuy: true }, // 10% protection from magic // 10% защита от магии
  4774. { id: 10, cost: 6, isBuy: true }, // 5% protection from magic // 5% защита от магии
  4775. { id: 11, cost: 16, isBuy: true }, // 10% protection from magic // 10% защита от магии
  4776. { id: 12, cost: 40, isBuy: true }, // 20% protection from magic // 20% защита от магии
  4777. { id: 13, cost: 1, isBuy: false }, // 40% health hero // 40% здоровья герою
  4778. { id: 14, cost: 6, isBuy: false }, // 40% health hero // 40% здоровья герою
  4779. { id: 15, cost: 16, isBuy: false }, // 80% health hero // 80% здоровья герою
  4780. { id: 16, cost: 40, isBuy: false }, // 40% health to all heroes // 40% здоровья всем героям
  4781. { id: 17, cost: 1, isBuy: false }, // 40% energy to the hero // 40% энергии герою
  4782. { id: 18, cost: 3, isBuy: false }, // 40% energy to the hero // 40% энергии герою
  4783. { id: 19, cost: 8, isBuy: false }, // 80% energy to the hero // 80% энергии герою
  4784. { id: 20, cost: 20, isBuy: false }, // 40% energy to all heroes // 40% энергии всем героям
  4785. { id: 21, cost: 40, isBuy: false }, // Hero Resurrection // Воскрешение героя
  4786. ]
  4787.  
  4788. this.start = function () {
  4789. send(JSON.stringify(callsExecuteTower), startTower);
  4790. }
  4791.  
  4792. /**
  4793. * Getting data on the Tower
  4794. *
  4795. * Получаем данные по башне
  4796. */
  4797. function startTower(e) {
  4798. res = e.results;
  4799. towerGetInfo = res[0].result.response;
  4800. if (!towerGetInfo) {
  4801. endTower('noTower', res);
  4802. return;
  4803. }
  4804. teamGetAll = res[1].result.response;
  4805. teamGetFavor = res[2].result.response;
  4806. inventoryGet = res[3].result.response;
  4807. heroGetAll = Object.values(res[4].result.response);
  4808.  
  4809. scullCoin = inventoryGet.coin[7] ?? 0;
  4810.  
  4811. argsBattle.favor = teamGetFavor.tower;
  4812. argsBattle.heroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  4813. pet = teamGetAll.tower.filter(id => id >= 6000).pop();
  4814. if (pet) {
  4815. argsBattle.pet = pet;
  4816. }
  4817.  
  4818. checkFloor(towerGetInfo);
  4819. }
  4820.  
  4821. function fixHeroesTeam(argsBattle) {
  4822. let fixHeroes = argsBattle.heroes.filter(e => !heroesStates[e]?.isDead);
  4823. if (fixHeroes.length < 5) {
  4824. heroGetAll = heroGetAll.filter(e => !heroesStates[e.id]?.isDead);
  4825. fixHeroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  4826. Object.keys(argsBattle.favor).forEach(e => {
  4827. if (!fixHeroes.includes(+e)) {
  4828. delete argsBattle.favor[e];
  4829. }
  4830. })
  4831. }
  4832. argsBattle.heroes = fixHeroes;
  4833. return argsBattle;
  4834. }
  4835.  
  4836. /**
  4837. * Check the floor
  4838. *
  4839. * Проверяем этаж
  4840. */
  4841. function checkFloor(towerInfo) {
  4842. lastTowerInfo = towerInfo;
  4843. maySkipFloor = +towerInfo.maySkipFloor;
  4844. floorNumber = +towerInfo.floorNumber;
  4845. heroesStates = towerInfo.states.heroes;
  4846. floorInfo = towerInfo.floor;
  4847.  
  4848. /**
  4849. * Is there at least one chest open on the floor
  4850. * Открыт ли на этаже хоть один сундук
  4851. */
  4852. isOpenChest = false;
  4853. if (towerInfo.floorType == "chest") {
  4854. isOpenChest = towerInfo.floor.chests.reduce((n, e) => n + e.opened, 0);
  4855. }
  4856.  
  4857. setProgress(`${I18N('TOWER')}: ${I18N('FLOOR')} ${floorNumber}`);
  4858. if (floorNumber > 49) {
  4859. if (isOpenChest) {
  4860. endTower('alreadyOpenChest 50 floor', floorNumber);
  4861. return;
  4862. }
  4863. }
  4864. /**
  4865. * If the chest is open and you can skip floors, then move on
  4866. * Если сундук открыт и можно скипать этажи, то переходим дальше
  4867. */
  4868. if (towerInfo.mayFullSkip && +towerInfo.teamLevel == 130) {
  4869. if (isOpenChest) {
  4870. nextOpenChest(floorNumber);
  4871. } else {
  4872. nextChestOpen(floorNumber);
  4873. }
  4874. return;
  4875. }
  4876.  
  4877. // console.log(towerInfo, scullCoin);
  4878. switch (towerInfo.floorType) {
  4879. case "battle":
  4880. if (floorNumber <= maySkipFloor) {
  4881. skipFloor();
  4882. return;
  4883. }
  4884. if (floorInfo.state == 2) {
  4885. nextFloor();
  4886. return;
  4887. }
  4888. startBattle().then(endBattle);
  4889. return;
  4890. case "buff":
  4891. checkBuff(towerInfo);
  4892. return;
  4893. case "chest":
  4894. openChest(floorNumber);
  4895. return;
  4896. default:
  4897. console.log('!', towerInfo.floorType, towerInfo);
  4898. break;
  4899. }
  4900. }
  4901.  
  4902. /**
  4903. * Let's start the fight
  4904. *
  4905. * Начинаем бой
  4906. */
  4907. function startBattle() {
  4908. return new Promise(function (resolve, reject) {
  4909. towerStartBattle = {
  4910. calls: [{
  4911. name: "towerStartBattle",
  4912. args: fixHeroesTeam(argsBattle),
  4913. ident: "body"
  4914. }]
  4915. }
  4916. send(JSON.stringify(towerStartBattle), resultBattle, resolve);
  4917. });
  4918. }
  4919. /**
  4920. * Returns the result of the battle in a promise
  4921. *
  4922. * Возращает резульат боя в промис
  4923. */
  4924. function resultBattle(resultBattles, resolve) {
  4925. battleData = resultBattles.results[0].result.response;
  4926. battleType = "get_tower";
  4927. BattleCalc(battleData, battleType, function (result) {
  4928. resolve(result);
  4929. });
  4930. }
  4931. /**
  4932. * Finishing the fight
  4933. *
  4934. * Заканчиваем бой
  4935. */
  4936. function endBattle(battleInfo) {
  4937. if (battleInfo.result.stars >= 3) {
  4938. endBattleCall = {
  4939. calls: [{
  4940. name: "towerEndBattle",
  4941. args: {
  4942. result: battleInfo.result,
  4943. progress: battleInfo.progress,
  4944. },
  4945. ident: "body"
  4946. }]
  4947. }
  4948. send(JSON.stringify(endBattleCall), resultEndBattle);
  4949. } else {
  4950. endTower('towerEndBattle win: false\n', battleInfo);
  4951. }
  4952. }
  4953.  
  4954. /**
  4955. * Getting and processing battle results
  4956. *
  4957. * Получаем и обрабатываем результаты боя
  4958. */
  4959. function resultEndBattle(e) {
  4960. battleResult = e.results[0].result.response;
  4961. if ('error' in battleResult) {
  4962. endTower('errorBattleResult', battleResult);
  4963. return;
  4964. }
  4965. if ('reward' in battleResult) {
  4966. scullCoin += battleResult.reward?.coin[7] ?? 0;
  4967. }
  4968. nextFloor();
  4969. }
  4970.  
  4971. function nextFloor() {
  4972. nextFloorCall = {
  4973. calls: [{
  4974. name: "towerNextFloor",
  4975. args: {},
  4976. ident: "body"
  4977. }]
  4978. }
  4979. send(JSON.stringify(nextFloorCall), checkDataFloor);
  4980. }
  4981.  
  4982. function openChest(floorNumber) {
  4983. floorNumber = floorNumber || 0;
  4984. openChestCall = {
  4985. calls: [{
  4986. name: "towerOpenChest",
  4987. args: {
  4988. num: 2
  4989. },
  4990. ident: "body"
  4991. }]
  4992. }
  4993. send(JSON.stringify(openChestCall), floorNumber < 50 ? nextFloor : lastChest);
  4994. }
  4995.  
  4996. function lastChest() {
  4997. endTower('openChest 50 floor', floorNumber);
  4998. }
  4999.  
  5000. function skipFloor() {
  5001. skipFloorCall = {
  5002. calls: [{
  5003. name: "towerSkipFloor",
  5004. args: {},
  5005. ident: "body"
  5006. }]
  5007. }
  5008. send(JSON.stringify(skipFloorCall), checkDataFloor);
  5009. }
  5010.  
  5011. function checkBuff(towerInfo) {
  5012. buffArr = towerInfo.floor;
  5013. promises = [];
  5014. for (let buff of buffArr) {
  5015. buffInfo = buffIds[buff.id];
  5016. if (buffInfo.isBuy && buffInfo.cost <= scullCoin) {
  5017. scullCoin -= buffInfo.cost;
  5018. promises.push(buyBuff(buff.id));
  5019. }
  5020. }
  5021. Promise.all(promises).then(nextFloor);
  5022. }
  5023.  
  5024. function buyBuff(buffId) {
  5025. return new Promise(function (resolve, reject) {
  5026. buyBuffCall = {
  5027. calls: [{
  5028. name: "towerBuyBuff",
  5029. args: {
  5030. buffId
  5031. },
  5032. ident: "body"
  5033. }]
  5034. }
  5035. send(JSON.stringify(buyBuffCall), resolve);
  5036. });
  5037. }
  5038.  
  5039. function checkDataFloor(result) {
  5040. towerInfo = result.results[0].result.response;
  5041. if ('reward' in towerInfo && towerInfo.reward?.coin) {
  5042. scullCoin += towerInfo.reward?.coin[7] ?? 0;
  5043. }
  5044. if ('tower' in towerInfo) {
  5045. towerInfo = towerInfo.tower;
  5046. }
  5047. if ('skullReward' in towerInfo) {
  5048. scullCoin += towerInfo.skullReward?.coin[7] ?? 0;
  5049. }
  5050. checkFloor(towerInfo);
  5051. }
  5052. /**
  5053. * Getting tower rewards
  5054. *
  5055. * Получаем награды башни
  5056. */
  5057. function farmTowerRewards(reason) {
  5058. let { pointRewards, points } = lastTowerInfo;
  5059. let pointsAll = Object.getOwnPropertyNames(pointRewards);
  5060. let farmPoints = pointsAll.filter(e => +e <= +points && !pointRewards[e]);
  5061. if (!farmPoints.length) {
  5062. return;
  5063. }
  5064. let farmTowerRewardsCall = {
  5065. calls: [{
  5066. name: "tower_farmPointRewards",
  5067. args: {
  5068. points: farmPoints
  5069. },
  5070. ident: "tower_farmPointRewards"
  5071. }]
  5072. }
  5073.  
  5074. if (scullCoin > 0 && reason == 'openChest 50 floor') {
  5075. farmTowerRewardsCall.calls.push({
  5076. name: "tower_farmSkullReward",
  5077. args: {},
  5078. ident: "tower_farmSkullReward"
  5079. });
  5080. }
  5081.  
  5082. send(JSON.stringify(farmTowerRewardsCall), () => { });
  5083. }
  5084.  
  5085. function fullSkipTower() {
  5086. /**
  5087. * Next chest
  5088. *
  5089. * Следующий сундук
  5090. */
  5091. function nextChest(n) {
  5092. return {
  5093. name: "towerNextChest",
  5094. args: {},
  5095. ident: "group_" + n + "_body"
  5096. }
  5097. }
  5098. /**
  5099. * Open chest
  5100. *
  5101. * Открыть сундук
  5102. */
  5103. function openChest(n) {
  5104. return {
  5105. name: "towerOpenChest",
  5106. args: {
  5107. "num": 2
  5108. },
  5109. ident: "group_" + n + "_body"
  5110. }
  5111. }
  5112.  
  5113. const fullSkipTowerCall = {
  5114. calls: []
  5115. }
  5116.  
  5117. let n = 0;
  5118. for (let i = 0; i < 15; i++) {
  5119. fullSkipTowerCall.calls.push(nextChest(++n));
  5120. fullSkipTowerCall.calls.push(openChest(++n));
  5121. }
  5122.  
  5123. send(JSON.stringify(fullSkipTowerCall), data => {
  5124. data.results[0] = data.results[28];
  5125. checkDataFloor(data);
  5126. });
  5127. }
  5128.  
  5129. function nextChestOpen(floorNumber) {
  5130. const calls = [{
  5131. name: "towerOpenChest",
  5132. args: {
  5133. num: 2
  5134. },
  5135. ident: "towerOpenChest"
  5136. }];
  5137.  
  5138. Send(JSON.stringify({ calls })).then(e => {
  5139. nextOpenChest(floorNumber);
  5140. });
  5141. }
  5142.  
  5143. function nextOpenChest(floorNumber) {
  5144. if (floorNumber > 49) {
  5145. endTower('openChest 50 floor', floorNumber);
  5146. return;
  5147. }
  5148. if (floorNumber == 1) {
  5149. fullSkipTower();
  5150. return;
  5151. }
  5152.  
  5153. let nextOpenChestCall = {
  5154. calls: [{
  5155. name: "towerNextChest",
  5156. args: {},
  5157. ident: "towerNextChest"
  5158. }, {
  5159. name: "towerOpenChest",
  5160. args: {
  5161. num: 2
  5162. },
  5163. ident: "towerOpenChest"
  5164. }]
  5165. }
  5166. send(JSON.stringify(nextOpenChestCall), checkDataFloor);
  5167. }
  5168.  
  5169. function endTower(reason, info) {
  5170. console.log(reason, info);
  5171. if (reason != 'noTower') {
  5172. farmTowerRewards(reason);
  5173. }
  5174. setProgress(`${I18N('TOWER')} ${I18N('COMPLETED')}!`, true);
  5175. resolve();
  5176. }
  5177. }
  5178.  
  5179. /**
  5180. * Passage of the arena of the titans
  5181. *
  5182. * Прохождение арены титанов
  5183. */
  5184. function testTitanArena() {
  5185. return new Promise((resolve, reject) => {
  5186. titAren = new executeTitanArena(resolve, reject);
  5187. titAren.start();
  5188. });
  5189. }
  5190.  
  5191. /**
  5192. * Passage of the arena of the titans
  5193. *
  5194. * Прохождение арены титанов
  5195. */
  5196. function executeTitanArena(resolve, reject) {
  5197. let titan_arena = [];
  5198. let finishListBattle = [];
  5199. /**
  5200. * ID of the current batch
  5201. *
  5202. * Идетификатор текущей пачки
  5203. */
  5204. let currentRival = 0;
  5205. /**
  5206. * Number of attempts to finish off the pack
  5207. *
  5208. * Количество попыток добития пачки
  5209. */
  5210. let attempts = 0;
  5211. /**
  5212. * Was there an attempt to finish off the current shooting range
  5213. *
  5214. * Была ли попытка добития текущего тира
  5215. */
  5216. let isCheckCurrentTier = false;
  5217. /**
  5218. * Current shooting range
  5219. *
  5220. * Текущий тир
  5221. */
  5222. let currTier = 0;
  5223. /**
  5224. * Number of battles on the current dash
  5225. *
  5226. * Количество битв на текущем тире
  5227. */
  5228. let countRivalsTier = 0;
  5229.  
  5230. let callsStart = {
  5231. calls: [{
  5232. name: "titanArenaGetStatus",
  5233. args: {},
  5234. ident: "titanArenaGetStatus"
  5235. }, {
  5236. name: "teamGetAll",
  5237. args: {},
  5238. ident: "teamGetAll"
  5239. }]
  5240. }
  5241.  
  5242. this.start = function () {
  5243. send(JSON.stringify(callsStart), startTitanArena);
  5244. }
  5245.  
  5246. function startTitanArena(data) {
  5247. let titanArena = data.results[0].result.response;
  5248. if (titanArena.status == 'disabled') {
  5249. endTitanArena('disabled', titanArena);
  5250. return;
  5251. }
  5252.  
  5253. let teamGetAll = data.results[1].result.response;
  5254. titan_arena = teamGetAll.titan_arena;
  5255.  
  5256. checkTier(titanArena)
  5257. }
  5258.  
  5259. function checkTier(titanArena) {
  5260. if (titanArena.status == "peace_time") {
  5261. endTitanArena('Peace_time', titanArena);
  5262. return;
  5263. }
  5264. currTier = titanArena.tier;
  5265. if (currTier) {
  5266. setProgress(`${I18N('TITAN_ARENA')}: ${I18N('LEVEL')} ${currTier}`);
  5267. }
  5268.  
  5269. if (titanArena.status == "completed_tier") {
  5270. titanArenaCompleteTier();
  5271. return;
  5272. }
  5273. /**
  5274. * Checking for the possibility of a raid
  5275. * Проверка на возможность рейда
  5276. */
  5277. if (titanArena.canRaid) {
  5278. titanArenaStartRaid();
  5279. return;
  5280. }
  5281. /**
  5282. * Check was an attempt to achieve the current shooting range
  5283. * Проверка была ли попытка добития текущего тира
  5284. */
  5285. if (!isCheckCurrentTier) {
  5286. checkRivals(titanArena.rivals);
  5287. return;
  5288. }
  5289.  
  5290. endTitanArena('Done or not canRaid', titanArena);
  5291. }
  5292. /**
  5293. * Submit dash information for verification
  5294. *
  5295. * Отправка информации о тире на проверку
  5296. */
  5297. function checkResultInfo(data) {
  5298. let titanArena = data.results[0].result.response;
  5299. checkTier(titanArena);
  5300. }
  5301. /**
  5302. * Finish the current tier
  5303. *
  5304. * Завершить текущий тир
  5305. */
  5306. function titanArenaCompleteTier() {
  5307. isCheckCurrentTier = false;
  5308. let calls = [{
  5309. name: "titanArenaCompleteTier",
  5310. args: {},
  5311. ident: "body"
  5312. }];
  5313. send(JSON.stringify({calls}), checkResultInfo);
  5314. }
  5315. /**
  5316. * Gathering points to be completed
  5317. *
  5318. * Собираем точки которые нужно добить
  5319. */
  5320. function checkRivals(rivals) {
  5321. finishListBattle = [];
  5322. for (let n in rivals) {
  5323. if (rivals[n].attackScore < 250) {
  5324. finishListBattle.push(n);
  5325. }
  5326. }
  5327. console.log('checkRivals', finishListBattle);
  5328. countRivalsTier = finishListBattle.length;
  5329. roundRivals();
  5330. }
  5331. /**
  5332. * Selecting the next point to finish off
  5333. *
  5334. * Выбор следующей точки для добития
  5335. */
  5336. function roundRivals() {
  5337. let countRivals = finishListBattle.length;
  5338. if (!countRivals) {
  5339. /**
  5340. * Whole range checked
  5341. *
  5342. * Весь тир проверен
  5343. */
  5344. isCheckCurrentTier = true;
  5345. titanArenaGetStatus();
  5346. return;
  5347. }
  5348. // setProgress('TitanArena: Уровень ' + currTier + ' Бои: ' + (countRivalsTier - countRivals + 1) + '/' + countRivalsTier);
  5349. currentRival = finishListBattle.pop();
  5350. attempts = +currentRival;
  5351. // console.log('roundRivals', currentRival);
  5352. titanArenaStartBattle(currentRival);
  5353. }
  5354. /**
  5355. * The start of a solo battle
  5356. *
  5357. * Начало одиночной битвы
  5358. */
  5359. function titanArenaStartBattle(rivalId) {
  5360. let calls = [{
  5361. name: "titanArenaStartBattle",
  5362. args: {
  5363. rivalId: rivalId,
  5364. titans: titan_arena
  5365. },
  5366. ident: "body"
  5367. }];
  5368. send(JSON.stringify({calls}), calcResult);
  5369. }
  5370. /**
  5371. * Calculation of the results of the battle
  5372. *
  5373. * Расчет результатов боя
  5374. */
  5375. function calcResult(data) {
  5376. let battlesInfo = data.results[0].result.response.battle;
  5377. /**
  5378. * If attempts are equal to the current battle number we make
  5379. * Если попытки равны номеру текущего боя делаем прерасчет
  5380. */
  5381. if (attempts == currentRival) {
  5382. preCalcBattle(battlesInfo);
  5383. return;
  5384. }
  5385. /**
  5386. * If there are still attempts, we calculate a new battle
  5387. * Если попытки еще есть делаем расчет нового боя
  5388. */
  5389. if (attempts > 0) {
  5390. attempts--;
  5391. calcBattleResult(battlesInfo)
  5392. .then(resultCalcBattle);
  5393. return;
  5394. }
  5395. /**
  5396. * Otherwise, go to the next opponent
  5397. * Иначе переходим к следующему сопернику
  5398. */
  5399. roundRivals();
  5400. }
  5401. /**
  5402. * Processing the results of the battle calculation
  5403. *
  5404. * Обработка результатов расчета битвы
  5405. */
  5406. function resultCalcBattle(resultBattle) {
  5407. // console.log('resultCalcBattle', currentRival, attempts, resultBattle.result.win);
  5408. /**
  5409. * If the current calculation of victory is not a chance or the attempt ended with the finish the battle
  5410. * Если текущий расчет победа или шансов нет или попытки кончились завершаем бой
  5411. */
  5412. if (resultBattle.result.win || !attempts) {
  5413. titanArenaEndBattle({
  5414. progress: resultBattle.progress,
  5415. result: resultBattle.result,
  5416. rivalId: resultBattle.battleData.typeId
  5417. });
  5418. return;
  5419. }
  5420. /**
  5421. * If not victory and there are attempts we start a new battle
  5422. * Если не победа и есть попытки начинаем новый бой
  5423. */
  5424. titanArenaStartBattle(resultBattle.battleData.typeId);
  5425. }
  5426. /**
  5427. * Returns the promise of calculating the results of the battle
  5428. *
  5429. * Возращает промис расчета результатов битвы
  5430. */
  5431. function getBattleInfo(battle, isRandSeed) {
  5432. return new Promise(function (resolve) {
  5433. if (isRandSeed) {
  5434. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  5435. }
  5436. // console.log(battle.seed);
  5437. BattleCalc(battle, "get_titanClanPvp", e => resolve(e));
  5438. });
  5439. }
  5440. /**
  5441. * Recalculate battles
  5442. *
  5443. * Прерасчтет битвы
  5444. */
  5445. function preCalcBattle(battle) {
  5446. let actions = [getBattleInfo(battle, false)];
  5447. const countTestBattle = getInput('countTestBattle');
  5448. for (let i = 0; i < countTestBattle; i++) {
  5449. actions.push(getBattleInfo(battle, true));
  5450. }
  5451. Promise.all(actions)
  5452. .then(resultPreCalcBattle);
  5453. }
  5454. /**
  5455. * Processing the results of the battle recalculation
  5456. *
  5457. * Обработка результатов прерасчета битвы
  5458. */
  5459. function resultPreCalcBattle(e) {
  5460. let wins = e.map(n => n.result.win);
  5461. let firstBattle = e.shift();
  5462. let countWin = wins.reduce((w, s) => w + s);
  5463. const countTestBattle = getInput('countTestBattle');
  5464. console.log('resultPreCalcBattle', `${countWin}/${countTestBattle}`)
  5465. if (countWin > 0) {
  5466. attempts = getInput('countAutoBattle');
  5467. } else {
  5468. attempts = 0;
  5469. }
  5470. resultCalcBattle(firstBattle);
  5471. }
  5472.  
  5473. /**
  5474. * Complete an arena battle
  5475. *
  5476. * Завершить битву на арене
  5477. */
  5478. function titanArenaEndBattle(args) {
  5479. let calls = [{
  5480. name: "titanArenaEndBattle",
  5481. args,
  5482. ident: "body"
  5483. }];
  5484. send(JSON.stringify({calls}), resultTitanArenaEndBattle);
  5485. }
  5486.  
  5487. function resultTitanArenaEndBattle(e) {
  5488. let attackScore = e.results[0].result.response.attackScore;
  5489. let numReval = countRivalsTier - finishListBattle.length;
  5490. setProgress(`${I18N('TITAN_ARENA')}: ${I18N('LEVEL')} ${currTier} </br>${I18N('BATTLES')}: ${numReval}/${countRivalsTier} - ${attackScore}`);
  5491. /**
  5492. * TODO: Might need to improve the results.
  5493. * TODO: Возможно стоит сделать улучшение результатов
  5494. */
  5495. // console.log('resultTitanArenaEndBattle', e)
  5496. console.log('resultTitanArenaEndBattle', numReval + '/' + countRivalsTier, attempts)
  5497. roundRivals();
  5498. }
  5499. /**
  5500. * Arena State
  5501. *
  5502. * Состояние арены
  5503. */
  5504. function titanArenaGetStatus() {
  5505. let calls = [{
  5506. name: "titanArenaGetStatus",
  5507. args: {},
  5508. ident: "body"
  5509. }];
  5510. send(JSON.stringify({calls}), checkResultInfo);
  5511. }
  5512. /**
  5513. * Arena Raid Request
  5514. *
  5515. * Запрос рейда арены
  5516. */
  5517. function titanArenaStartRaid() {
  5518. let calls = [{
  5519. name: "titanArenaStartRaid",
  5520. args: {
  5521. titans: titan_arena
  5522. },
  5523. ident: "body"
  5524. }];
  5525. send(JSON.stringify({calls}), calcResults);
  5526. }
  5527.  
  5528. function calcResults(data) {
  5529. let battlesInfo = data.results[0].result.response;
  5530. let {attackers, rivals} = battlesInfo;
  5531.  
  5532. let promises = [];
  5533. for (let n in rivals) {
  5534. rival = rivals[n];
  5535. promises.push(calcBattleResult({
  5536. attackers: attackers,
  5537. defenders: [rival.team],
  5538. seed: rival.seed,
  5539. typeId: n,
  5540. }));
  5541. }
  5542.  
  5543. Promise.all(promises)
  5544. .then(results => {
  5545. const endResults = {};
  5546. for (let info of results) {
  5547. let id = info.battleData.typeId;
  5548. endResults[id] = {
  5549. progress: info.progress,
  5550. result: info.result,
  5551. }
  5552. }
  5553. titanArenaEndRaid(endResults);
  5554. });
  5555. }
  5556.  
  5557. function calcBattleResult(battleData) {
  5558. return new Promise(function (resolve, reject) {
  5559. BattleCalc(battleData, "get_titanClanPvp", resolve);
  5560. });
  5561. }
  5562.  
  5563. /**
  5564. * Sending Raid Results
  5565. *
  5566. * Отправка результатов рейда
  5567. */
  5568. function titanArenaEndRaid(results) {
  5569. titanArenaEndRaidCall = {
  5570. calls: [{
  5571. name: "titanArenaEndRaid",
  5572. args: {
  5573. results
  5574. },
  5575. ident: "body"
  5576. }]
  5577. }
  5578. send(JSON.stringify(titanArenaEndRaidCall), checkRaidResults);
  5579. }
  5580.  
  5581. function checkRaidResults(data) {
  5582. results = data.results[0].result.response.results;
  5583. isSucsesRaid = true;
  5584. for (let i in results) {
  5585. isSucsesRaid &&= (results[i].attackScore >= 250);
  5586. }
  5587.  
  5588. if (isSucsesRaid) {
  5589. titanArenaCompleteTier();
  5590. } else {
  5591. titanArenaGetStatus();
  5592. }
  5593. }
  5594.  
  5595. function titanArenaFarmDailyReward() {
  5596. titanArenaFarmDailyRewardCall = {
  5597. calls: [{
  5598. name: "titanArenaFarmDailyReward",
  5599. args: {},
  5600. ident: "body"
  5601. }]
  5602. }
  5603. send(JSON.stringify(titanArenaFarmDailyRewardCall), () => {console.log('Done farm daily reward')});
  5604. }
  5605.  
  5606. function endTitanArena(reason, info) {
  5607. if (!['Peace_time', 'disabled'].includes(reason)) {
  5608. titanArenaFarmDailyReward();
  5609. }
  5610. console.log(reason, info);
  5611. setProgress(`${I18N('TITAN_ARENA')} ${I18N('COMPLETED')}!`, true);
  5612. resolve();
  5613. }
  5614. }
  5615.  
  5616. function hackGame() {
  5617. self = this;
  5618. selfGame = null;
  5619. bindId = 1e9;
  5620. this.libGame = null;
  5621.  
  5622. /**
  5623. * List of correspondence of used classes to their names
  5624. *
  5625. * Список соответствия используемых классов их названиям
  5626. */
  5627. ObjectsList = [
  5628. {name:"BattlePresets", prop:"game.battle.controller.thread.BattlePresets"},
  5629. {name:"DataStorage", prop:"game.data.storage.DataStorage"},
  5630. {name:"BattleConfigStorage", prop:"game.data.storage.battle.BattleConfigStorage"},
  5631. {name:"BattleInstantPlay", prop:"game.battle.controller.instant.BattleInstantPlay"},
  5632. {name:"MultiBattleResult", prop:"game.battle.controller.MultiBattleResult"},
  5633.  
  5634. {name:"PlayerMissionData", prop:"game.model.user.mission.PlayerMissionData"},
  5635. {name:"PlayerMissionBattle", prop:"game.model.user.mission.PlayerMissionBattle"},
  5636. {name:"GameModel", prop:"game.model.GameModel"},
  5637. {name:"CommandManager", prop:"game.command.CommandManager"},
  5638. {name:"MissionCommandList", prop:"game.command.rpc.mission.MissionCommandList"},
  5639. {name:"RPCCommandBase", prop:"game.command.rpc.RPCCommandBase"},
  5640. {name:"PlayerTowerData", prop:"game.model.user.tower.PlayerTowerData"},
  5641. {name:"TowerCommandList", prop:"game.command.tower.TowerCommandList"},
  5642. {name:"PlayerHeroTeamResolver", prop:"game.model.user.hero.PlayerHeroTeamResolver"},
  5643. {name:"BattlePausePopup", prop:"game.view.popup.battle.BattlePausePopup"},
  5644. {name:"BattlePopup", prop:"game.view.popup.battle.BattlePopup"},
  5645. {name:"DisplayObjectContainer", prop:"starling.display.DisplayObjectContainer"},
  5646. {name:"GuiClipContainer", prop:"engine.core.clipgui.GuiClipContainer"},
  5647. {name:"BattlePausePopupClip", prop:"game.view.popup.battle.BattlePausePopupClip"},
  5648. {name:"ClipLabel", prop:"game.view.gui.components.ClipLabel"},
  5649. {name:"ClipLabelBase", prop:"game.view.gui.components.ClipLabelBase"},
  5650. {name:"Translate", prop:"com.progrestar.common.lang.Translate"},
  5651. {name:"ClipButtonLabeledCentered", prop:"game.view.gui.components.ClipButtonLabeledCentered"},
  5652. {name:"BattlePausePopupMediator", prop:"game.mediator.gui.popup.battle.BattlePausePopupMediator"},
  5653. {name:"SettingToggleButton", prop:"game.mechanics.settings.popup.view.SettingToggleButton"},
  5654. {name:"PlayerDungeonData", prop:"game.mechanics.dungeon.model.PlayerDungeonData"},
  5655. {name:"NextDayUpdatedManager", prop:"game.model.user.NextDayUpdatedManager"},
  5656. {name:"BattleController", prop:"game.battle.controller.BattleController"},
  5657. {name:"BattleSettingsModel", prop:"game.battle.controller.BattleSettingsModel"},
  5658. {name:"BooleanProperty", prop:"engine.core.utils.property.BooleanProperty"},
  5659. {name:"RuleStorage", prop:"game.data.storage.rule.RuleStorage"},
  5660. {name:"BattleConfig", prop:"battle.BattleConfig"},
  5661. {name:"SpecialShopModel", prop:"game.model.user.shop.SpecialShopModel"},
  5662. {name:"BattleGuiMediator", prop:"game.battle.gui.BattleGuiMediator"},
  5663. {name:"BooleanPropertyWriteable", prop:"engine.core.utils.property.BooleanPropertyWriteable"},
  5664. { name: "BattleLogEncoder", prop: "battle.log.BattleLogEncoder" },
  5665. { name: "BattleLogReader", prop: "battle.log.BattleLogReader" },
  5666. { name: "PlayerSubscriptionInfoValueObject", prop: "game.model.user.subscription.PlayerSubscriptionInfoValueObject" },
  5667. ];
  5668.  
  5669. /**
  5670. * Contains the game classes needed to write and override game methods
  5671. *
  5672. * Содержит классы игры необходимые для написания и подмены методов игры
  5673. */
  5674. Game = {
  5675. /**
  5676. * Function 'e'
  5677. * Функция 'e'
  5678. */
  5679. bindFunc: function (a, b) {
  5680. if (null == b)
  5681. return null;
  5682. null == b.__id__ && (b.__id__ = bindId++);
  5683. var c;
  5684. null == a.hx__closures__ ? a.hx__closures__ = {} :
  5685. c = a.hx__closures__[b.__id__];
  5686. null == c && (c = b.bind(a), a.hx__closures__[b.__id__] = c);
  5687. return c
  5688. },
  5689. };
  5690.  
  5691. /**
  5692. * Connects to game objects via the object creation event
  5693. *
  5694. * Подключается к объектам игры через событие создания объекта
  5695. */
  5696. function connectGame() {
  5697. for (let obj of ObjectsList) {
  5698. /**
  5699. * https: //stackoverflow.com/questions/42611719/how-to-intercept-and-modify-a-specific-property-for-any-object
  5700. */
  5701. Object.defineProperty(Object.prototype, obj.prop, {
  5702. set: function (value) {
  5703. if (!selfGame) {
  5704. selfGame = this;
  5705. }
  5706. if (!Game[obj.name]) {
  5707. Game[obj.name] = value;
  5708. }
  5709. // console.log('set ' + obj.prop, this, value);
  5710. this[obj.prop + '_'] = value;
  5711. },
  5712. get: function () {
  5713. // console.log('get ' + obj.prop, this);
  5714. return this[obj.prop + '_'];
  5715. }
  5716. });
  5717. }
  5718. }
  5719.  
  5720. /**
  5721. * Game.BattlePresets
  5722. * @param {bool} a isReplay
  5723. * @param {bool} b autoToggleable
  5724. * @param {bool} c auto On Start
  5725. * @param {object} d config
  5726. * @param {bool} f showBothTeams
  5727. */
  5728. /**
  5729. * Returns the results of the battle to the callback function
  5730. * Возвращает в функцию callback результаты боя
  5731. * @param {*} battleData battle data данные боя
  5732. * @param {*} battleConfig combat configuration type options:
  5733. *
  5734. * тип конфигурации боя варианты:
  5735. *
  5736. * "get_invasion", "get_titanPvpManual", "get_titanPvp",
  5737. * "get_titanClanPvp","get_clanPvp","get_titan","get_boss",
  5738. * "get_tower","get_pve","get_pvpManual","get_pvp","get_core"
  5739. *
  5740. * You can specify the xYc function in the game.assets.storage.BattleAssetStorage class
  5741. *
  5742. * Можно уточнить в классе game.assets.storage.BattleAssetStorage функция xYc
  5743. * @param {*} callback функция в которую вернуться результаты боя
  5744. */
  5745. this.BattleCalc = function (battleData, battleConfig, callback) {
  5746. // battleConfig = battleConfig || getBattleType(battleData.type)
  5747. if (!Game.BattlePresets) throw Error('Use connectGame');
  5748. battlePresets = new Game.BattlePresets(!!battleData.progress, !1, !0, Game.DataStorage[getFn(Game.DataStorage, 24)][getF(Game.BattleConfigStorage, battleConfig)](), !1);
  5749. battleInstantPlay = new Game.BattleInstantPlay(battleData, battlePresets);
  5750. battleInstantPlay[getProtoFn(Game.BattleInstantPlay, 8)].add((battleInstant) => {
  5751. const battleResult = battleInstant[getF(Game.BattleInstantPlay, 'get_result')]();
  5752. const battleData = battleInstant[getF(Game.BattleInstantPlay, 'get_rawBattleInfo')]();
  5753. const battleLog = Game.BattleLogEncoder.read(new Game.BattleLogReader(battleResult[getProtoFn(Game.MultiBattleResult, 2)][0]));
  5754. const timeLimit = battlePresets[getF(Game.BattlePresets, 'get_timeLimit')]();
  5755. const battleTime = Math.max(...battleLog.map(e => e.time < timeLimit ? e.time : 0));
  5756. callback({
  5757. battleTime,
  5758. battleData,
  5759. progress: battleResult[getF(Game.MultiBattleResult, 'get_progress')](),
  5760. result: battleResult[getF(Game.MultiBattleResult, 'get_result')]()
  5761. })
  5762. });
  5763. battleInstantPlay.start();
  5764. }
  5765.  
  5766. /**
  5767. * Returns a function with the specified name from the class
  5768. *
  5769. * Возвращает из класса функцию с указанным именем
  5770. * @param {Object} classF Class // класс
  5771. * @param {String} nameF function name // имя функции
  5772. * @param {String} pos name and alias order // порядок имени и псевдонима
  5773. * @returns
  5774. */
  5775. function getF(classF, nameF, pos) {
  5776. pos = pos || false;
  5777. let prop = Object.entries(classF.prototype.__properties__)
  5778. if (!pos) {
  5779. return prop.filter((e) => e[1] == nameF).pop()[0];
  5780. } else {
  5781. return prop.filter((e) => e[0] == nameF).pop()[1];
  5782. }
  5783. }
  5784.  
  5785. /**
  5786. * Returns a function with the specified name from the class
  5787. *
  5788. * Возвращает из класса функцию с указанным именем
  5789. * @param {Object} classF Class // класс
  5790. * @param {String} nameF function name // имя функции
  5791. * @returns
  5792. */
  5793. function getFnP(classF, nameF) {
  5794. let prop = Object.entries(classF.__properties__)
  5795. return prop.filter((e) => e[1] == nameF).pop()[0];
  5796. }
  5797.  
  5798. /**
  5799. * Returns the function name with the specified ordinal from the class
  5800. *
  5801. * Возвращает имя функции с указаным порядковым номером из класса
  5802. * @param {Object} classF Class // класс
  5803. * @param {Number} nF Order number of function // порядковый номер функции
  5804. * @returns
  5805. */
  5806. function getFn(classF, nF) {
  5807. let prop = Object.keys(classF);
  5808. return prop[nF];
  5809. }
  5810.  
  5811. /**
  5812. * Returns the name of the function with the specified serial number from the prototype of the class
  5813. *
  5814. * Возвращает имя функции с указаным порядковым номером из прототипа класса
  5815. * @param {Object} classF Class // класс
  5816. * @param {Number} nF Order number of function // порядковый номер функции
  5817. * @returns
  5818. */
  5819. function getProtoFn(classF, nF) {
  5820. let prop = Object.keys(classF.prototype);
  5821. return prop[nF];
  5822. }
  5823. /**
  5824. * Description of replaced functions
  5825. *
  5826. * Описание подменяемых функций
  5827. */
  5828. replaceFunction = {
  5829. company: function() {
  5830. let PMD_12 = getProtoFn(Game.PlayerMissionData, 12);
  5831. let oldSkipMisson = Game.PlayerMissionData.prototype[PMD_12];
  5832. Game.PlayerMissionData.prototype[PMD_12] = function (a, b, c) {
  5833. if (!isChecked('passBattle')) {
  5834. oldSkipMisson.call(this, a, b, c);
  5835. return;
  5836. }
  5837.  
  5838. try {
  5839. this[getProtoFn(Game.PlayerMissionData, 9)] = new Game.PlayerMissionBattle(a, b, c);
  5840.  
  5841. var a = new Game.BattlePresets(!1, !1, !0, Game.DataStorage[getFn(Game.DataStorage, 24)][getProtoFn(Game.BattleConfigStorage, 17)](), !1);
  5842. a = new Game.BattleInstantPlay(c, a);
  5843. a[getProtoFn(Game.BattleInstantPlay, 8)].add(Game.bindFunc(this, this.P$h));
  5844. a.start()
  5845. } catch (error) {
  5846. console.error('company', error)
  5847. oldSkipMisson.call(this, a, b, c);
  5848. }
  5849. }
  5850.  
  5851. Game.PlayerMissionData.prototype.P$h = function (a) {
  5852. let GM_2 = getFn(Game.GameModel, 2);
  5853. let GM_P2 = getProtoFn(Game.GameModel, 2);
  5854. let CM_20 = getProtoFn(Game.CommandManager, 20);
  5855. let MCL_2 = getProtoFn(Game.MissionCommandList, 2);
  5856. let MBR_15 = getF(Game.MultiBattleResult, "get_result");
  5857. let RPCCB_15 = getProtoFn(Game.RPCCommandBase, 16);
  5858. let PMD_32 = getProtoFn(Game.PlayerMissionData, 32);
  5859. Game.GameModel[GM_2]()[GM_P2][CM_20][MCL_2](a[MBR_15]())[RPCCB_15](Game.bindFunc(this, this[PMD_32]))
  5860. }
  5861. },
  5862. tower: function() {
  5863. let PTD_67 = getProtoFn(Game.PlayerTowerData, 67);
  5864. let oldSkipTower = Game.PlayerTowerData.prototype[PTD_67];
  5865. Game.PlayerTowerData.prototype[PTD_67] = function (a) {
  5866. if (!isChecked('passBattle')) {
  5867. oldSkipTower.call(this, a);
  5868. return;
  5869. }
  5870. try {
  5871. var p = new Game.BattlePresets(!1, !1, !0, Game.DataStorage[getFn(Game.DataStorage, 24)][getProtoFn(Game.BattleConfigStorage,17)](), !1);
  5872. a = new Game.BattleInstantPlay(a, p);
  5873. a[getProtoFn(Game.BattleInstantPlay,8)].add(Game.bindFunc(this, this.P$h));
  5874. a.start()
  5875. } catch (error) {
  5876. console.error('tower', error)
  5877. oldSkipMisson.call(this, a, b, c);
  5878. }
  5879. }
  5880.  
  5881. Game.PlayerTowerData.prototype.P$h = function (a) {
  5882. const GM_2 = getFnP(Game.GameModel, "get_instance");
  5883. const GM_P2 = getProtoFn(Game.GameModel, 2);
  5884. const CM_29 = getProtoFn(Game.CommandManager, 29);
  5885. const TCL_5 = getProtoFn(Game.TowerCommandList, 5);
  5886. const MBR_15 = getF(Game.MultiBattleResult, "get_result");
  5887. const RPCCB_15 = getProtoFn(Game.RPCCommandBase, 17);
  5888. const PTD_78 = getProtoFn(Game.PlayerTowerData, 78);
  5889. Game.GameModel[GM_2]()[GM_P2][CM_29][TCL_5](a[MBR_15]())[RPCCB_15](Game.bindFunc(this, this[PTD_78]));
  5890. }
  5891. },
  5892. // skipSelectHero: function() {
  5893. // if (!HOST) throw Error('Use connectGame');
  5894. // Game.PlayerHeroTeamResolver.prototype[getProtoFn(Game.PlayerHeroTeamResolver, 3)] = () => false;
  5895. // },
  5896. passBattle: function() {
  5897. let BPP_4 = getProtoFn(Game.BattlePausePopup, 4);
  5898. let oldPassBattle = Game.BattlePausePopup.prototype[BPP_4];
  5899. Game.BattlePausePopup.prototype[BPP_4] = function (a) {
  5900. if (!isChecked('passBattle')) {
  5901. oldPassBattle.call(this, a);
  5902. return;
  5903. }
  5904. try {
  5905. Game.BattlePopup.prototype[getProtoFn(Game.BattlePausePopup, 4)].call(this, a);
  5906. this[getProtoFn(Game.BattlePausePopup, 3)]();
  5907. this[getProtoFn(Game.DisplayObjectContainer, 3)](this.clip[getProtoFn(Game.GuiClipContainer, 2)]());
  5908. this.clip[getProtoFn(Game.BattlePausePopupClip, 1)][getProtoFn(Game.ClipLabelBase, 9)](Game.Translate.translate("UI_POPUP_BATTLE_PAUSE"));
  5909.  
  5910. 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)])));
  5911. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 2)](
  5912. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 14)](),
  5913. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 13)]() ?
  5914. (q = this[getProtoFn(Game.BattlePausePopup, 1)], Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 18)])) :
  5915. (q = this[getProtoFn(Game.BattlePausePopup, 1)], Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 18)]))
  5916. );
  5917.  
  5918. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 0)][getProtoFn(Game.ClipLabelBase, 24)]();
  5919. this.clip[getProtoFn(Game.BattlePausePopupClip, 3)][getProtoFn(Game.SettingToggleButton, 3)](this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 9)]());
  5920. this.clip[getProtoFn(Game.BattlePausePopupClip, 4)][getProtoFn(Game.SettingToggleButton, 3)](this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 10)]());
  5921. this.clip[getProtoFn(Game.BattlePausePopupClip, 6)][getProtoFn(Game.SettingToggleButton, 3)](this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 11)]());
  5922. /*
  5923. Какая-то ненужная фигня
  5924. if (!HC.lSb()) {
  5925. this.clip.r6b.g().B(!1);
  5926. a = this.clip.r6b.g().X() + 7;
  5927. var b = this.clip.ba.g();
  5928. b.$(b.X() - a);
  5929. b = this.clip.IS.g();
  5930. b.sa(b.Fa() - a)
  5931. }
  5932. */
  5933. } catch(error) {
  5934. console.error('passBattle', error)
  5935. oldPassBattle.call(this, a);
  5936. }
  5937. }
  5938.  
  5939. let retreatButtonLabel = getF(Game.BattlePausePopupMediator, "get_retreatButtonLabel");
  5940. let oldFunc = Game.BattlePausePopupMediator.prototype[retreatButtonLabel];
  5941. Game.BattlePausePopupMediator.prototype[retreatButtonLabel] = function () {
  5942. if (isChecked('passBattle')) {
  5943. return I18N('BTN_PASS');
  5944. } else {
  5945. return oldFunc.call(this);
  5946. }
  5947. }
  5948. },
  5949. endlessCards: function() {
  5950. let PDD_15 = getProtoFn(Game.PlayerDungeonData, 15);
  5951. let oldEndlessCards = Game.PlayerDungeonData.prototype[PDD_15];
  5952. Game.PlayerDungeonData.prototype[PDD_15] = function () {
  5953. if (countPredictionCard <= 0) {
  5954. return true;
  5955. } else {
  5956. return oldEndlessCards.call(this);
  5957. }
  5958. }
  5959. },
  5960. speedBattle: function () {
  5961. const get_timeScale = getF(Game.BattleController, "get_timeScale");
  5962. const oldSpeedBattle = Game.BattleController.prototype[get_timeScale];
  5963. Game.BattleController.prototype[get_timeScale] = function () {
  5964. const speedBattle = Number.parseFloat(getInput('speedBattle'));
  5965. if (!speedBattle) {
  5966. return oldSpeedBattle.call(this);
  5967. }
  5968. try {
  5969. const BC_12 = getProtoFn(Game.BattleController, 12);
  5970. const BSM_12 = getProtoFn(Game.BattleSettingsModel, 12);
  5971. const BP_get_value = getF(Game.BooleanProperty, "get_value");
  5972. if (this[BC_12][BSM_12][BP_get_value]()) {
  5973. return 0;
  5974. }
  5975. const BSM_2 = getProtoFn(Game.BattleSettingsModel, 2);
  5976. const BC_48 = getProtoFn(Game.BattleController, 48);
  5977. const BSM_1 = getProtoFn(Game.BattleSettingsModel, 1);
  5978. const BC_14 = getProtoFn(Game.BattleController, 14);
  5979. const BC_3 = getFn(Game.BattleController, 3);
  5980. if (this[BC_12][BSM_2][BP_get_value]()) {
  5981. var a = speedBattle * this[BC_48]();
  5982. } else {
  5983. a = this[BC_12][BSM_1][BP_get_value]();
  5984. const maxSpeed = Math.max(...this[BC_14]);
  5985. const multiple = a == this[BC_14].indexOf(maxSpeed) ? (maxSpeed >= 4 ? speedBattle : this[BC_14][a]) : this[BC_14][a];
  5986. a = multiple * Game.BattleController[BC_3][BP_get_value]() * this[BC_48]();
  5987. }
  5988. const BSM_24 = getProtoFn(Game.BattleSettingsModel, 24);
  5989. a > this[BC_12][BSM_24][BP_get_value]() && (a = this[BC_12][BSM_24][BP_get_value]());
  5990. const DS_23 = getFn(Game.DataStorage, 23);
  5991. const get_battleSpeedMultiplier = getF(Game.RuleStorage, "get_battleSpeedMultiplier", true);
  5992. // const RS_167 = getProtoFn(Game.RuleStorage, 167); // get_battleSpeedMultiplier
  5993. var b = Game.DataStorage[DS_23][get_battleSpeedMultiplier]();
  5994. const R_1 = getFn(selfGame.Reflect, 1);
  5995. const BC_1 = getFn(Game.BattleController, 1);
  5996. const get_config = getF(Game.BattlePresets, "get_config");
  5997. // const BC_0 = getProtoFn(Game.BattleConfig, 0); // .ident
  5998. 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"));
  5999. return a
  6000. } catch(error) {
  6001. console.error('passBatspeedBattletle', error)
  6002. return oldSpeedBattle.call(this);
  6003. }
  6004. }
  6005. },
  6006.  
  6007. /**
  6008. * Remove the rare shop
  6009. *
  6010. * Удаление торговца редкими товарами
  6011. */
  6012. /*
  6013. removeWelcomeShop: function () {
  6014. let SSM_3 = getProtoFn(Game.SpecialShopModel, 3);
  6015. const oldWelcomeShop = Game.SpecialShopModel.prototype[SSM_3];
  6016. Game.SpecialShopModel.prototype[SSM_3] = function () {
  6017. if (isChecked('noOfferDonat')) {
  6018. return null;
  6019. } else {
  6020. return oldWelcomeShop.call(this);
  6021. }
  6022. }
  6023. },
  6024. */
  6025.  
  6026. /**
  6027. * Acceleration button without Valkyries favor
  6028. *
  6029. * Кнопка ускорения без Покровительства Валькирий
  6030. */
  6031. battleFastKey: function () {
  6032. const BGM_42 = getProtoFn(Game.BattleGuiMediator, 42);
  6033. const oldBattleFastKey = Game.BattleGuiMediator.prototype[BGM_42];
  6034. Game.BattleGuiMediator.prototype[BGM_42] = function () {
  6035. let flag = true;
  6036. //console.log(flag)
  6037. if (!flag) {
  6038. return oldBattleFastKey.call(this);
  6039. }
  6040. try {
  6041. const BGM_9 = getProtoFn(Game.BattleGuiMediator, 9);
  6042. const BGM_10 = getProtoFn(Game.BattleGuiMediator, 10);
  6043. const BPW_0 = getProtoFn(Game.BooleanPropertyWriteable, 0);
  6044. this[BGM_9][BPW_0](true);
  6045. this[BGM_10][BPW_0](true);
  6046. } catch (error) {
  6047. console.error(error);
  6048. return oldBattleFastKey.call(this);
  6049. }
  6050. }
  6051. },
  6052. fastSeason: function () {
  6053. const GameNavigator = selfGame["game.screen.navigator.GameNavigator"];
  6054. const oldFuncName = getProtoFn(GameNavigator, 16);
  6055. const newFuncName = getProtoFn(GameNavigator, 14);
  6056. const oldFastSeason = GameNavigator.prototype[oldFuncName];
  6057. const newFastSeason = GameNavigator.prototype[newFuncName];
  6058. GameNavigator.prototype[oldFuncName] = function (a, b) {
  6059. if (isChecked('fastSeason')) {
  6060. return newFastSeason.apply(this, [a]);
  6061. } else {
  6062. return oldFastSeason.apply(this, [a, b]);
  6063. }
  6064. }
  6065. },
  6066. ShowChestReward: function () {
  6067. const TitanArtifactChest = selfGame["game.mechanics.titan_arena.mediator.chest.TitanArtifactChestRewardPopupMediator"];
  6068. const getOpenAmountTitan = getF(TitanArtifactChest, "get_openAmount");
  6069. const oldGetOpenAmountTitan = TitanArtifactChest.prototype[getOpenAmountTitan];
  6070. TitanArtifactChest.prototype[getOpenAmountTitan] = function () {
  6071. if (correctShowOpenArtifact) {
  6072. correctShowOpenArtifact--;
  6073. return 100;
  6074. }
  6075. return oldGetOpenAmountTitan.call(this);
  6076. }
  6077.  
  6078. const ArtifactChest = selfGame["game.view.popup.artifactchest.rewardpopup.ArtifactChestRewardPopupMediator"];
  6079. const getOpenAmount = getF(ArtifactChest, "get_openAmount");
  6080. const oldGetOpenAmount = ArtifactChest.prototype[getOpenAmount];
  6081. ArtifactChest.prototype[getOpenAmount] = function () {
  6082. if (correctShowOpenArtifact) {
  6083. correctShowOpenArtifact--;
  6084. return 100;
  6085. }
  6086. return oldGetOpenAmount.call(this);
  6087. }
  6088.  
  6089. }
  6090. }
  6091.  
  6092. /**
  6093. * Starts replacing recorded functions
  6094. *
  6095. * Запускает замену записанных функций
  6096. */
  6097. this.activateHacks = function () {
  6098. if (!selfGame) throw Error('Use connectGame');
  6099. for (let func in replaceFunction) {
  6100. replaceFunction[func]();
  6101. }
  6102. }
  6103.  
  6104. /**
  6105. * Returns the game object
  6106. *
  6107. * Возвращает объект игры
  6108. */
  6109. this.getSelfGame = function () {
  6110. return selfGame;
  6111. }
  6112.  
  6113. /**
  6114. * Updates game data
  6115. *
  6116. * Обновляет данные игры
  6117. */
  6118. this.refreshGame = function () {
  6119. (new Game.NextDayUpdatedManager)[getProtoFn(Game.NextDayUpdatedManager, 5)]();
  6120. try {
  6121. cheats.refreshInventory();
  6122. } catch (e) { }
  6123. }
  6124.  
  6125. /**
  6126. * Update inventory
  6127. *
  6128. * Обновляет инвентарь
  6129. */
  6130. this.refreshInventory = async function () {
  6131. const GM_INST = getFnP(Game.GameModel, "get_instance");
  6132. const GM_0 = getProtoFn(Game.GameModel, 0);
  6133. const P_24 = getProtoFn(selfGame["game.model.user.Player"], 24);
  6134. const Player = Game.GameModel[GM_INST]()[GM_0];
  6135. Player[P_24] = new selfGame["game.model.user.inventory.PlayerInventory"]
  6136. Player[P_24].init(await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"}]}').then(e => e.results[0].result.response))
  6137. }
  6138.  
  6139. /**
  6140. * Change the play screen on windowName
  6141. *
  6142. * Сменить экран игры на windowName
  6143. *
  6144. * Possible options:
  6145. *
  6146. * Возможные варианты:
  6147. *
  6148. * 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
  6149. */
  6150. this.goNavigtor = function (windowName) {
  6151. let mechanicStorage = selfGame["game.data.storage.mechanic.MechanicStorage"];
  6152. let window = mechanicStorage[windowName];
  6153. let event = new selfGame["game.mediator.gui.popup.PopupStashEventParams"];
  6154. let Game = selfGame['Game'];
  6155. let navigator = getF(Game, "get_navigator")
  6156. let navigate = getProtoFn(selfGame["game.screen.navigator.GameNavigator"], 18)
  6157. let instance = getFnP(Game, 'get_instance');
  6158. Game[instance]()[navigator]()[navigate](window, event);
  6159. }
  6160.  
  6161. /**
  6162. * Move to the sanctuary cheats.goSanctuary()
  6163. *
  6164. * Переместиться в святилище cheats.goSanctuary()
  6165. */
  6166. this.goSanctuary = () => {
  6167. this.goNavigtor("SANCTUARY");
  6168. }
  6169.  
  6170. /**
  6171. * Go to Guild War
  6172. *
  6173. * Перейти к Войне Гильдий
  6174. */
  6175. this.goClanWar = function() {
  6176. let instance = getFnP(Game.GameModel, 'get_instance')
  6177. let player = Game.GameModel[instance]().A;
  6178. let clanWarSelect = selfGame["game.mechanics.cross_clan_war.popup.selectMode.CrossClanWarSelectModeMediator"];
  6179. new clanWarSelect(player).open();
  6180. }
  6181.  
  6182. /**
  6183. * Go to BrawlShop
  6184. *
  6185. * Переместиться в BrawlShop
  6186. */
  6187. this.goBrawlShop = () => {
  6188. const instance = getFnP(Game.GameModel, 'get_instance')
  6189. const P_36 = getProtoFn(selfGame["game.model.user.Player"], 36);
  6190. const PSD_0 = getProtoFn(selfGame["game.model.user.shop.PlayerShopData"], 0);
  6191. const IM_0 = getProtoFn(selfGame["haxe.ds.IntMap"], 0);
  6192. const PSDE_4 = getProtoFn(selfGame["game.model.user.shop.PlayerShopDataEntry"], 4);
  6193.  
  6194. const player = Game.GameModel[instance]().A;
  6195. const shop = player[P_36][PSD_0][IM_0][1038][PSDE_4];
  6196. const shopPopup = new selfGame["game.mechanics.brawl.mediator.BrawlShopPopupMediator"](player, shop)
  6197. shopPopup.open(new selfGame["game.mediator.gui.popup.PopupStashEventParams"])
  6198. }
  6199.  
  6200. /**
  6201. * Returns all stores from game data
  6202. *
  6203. * Возвращает все магазины из данных игры
  6204. */
  6205. this.getShops = () => {
  6206. const instance = getFnP(Game.GameModel, 'get_instance')
  6207. const P_36 = getProtoFn(selfGame["game.model.user.Player"], 36);
  6208. const PSD_0 = getProtoFn(selfGame["game.model.user.shop.PlayerShopData"], 0);
  6209. const IM_0 = getProtoFn(selfGame["haxe.ds.IntMap"], 0);
  6210.  
  6211. const player = Game.GameModel[instance]().A;
  6212. return player[P_36][PSD_0][IM_0];
  6213. }
  6214.  
  6215. /**
  6216. * Returns the store from the game data by ID
  6217. *
  6218. * Возвращает магазин из данных игры по идетификатору
  6219. */
  6220. this.getShop = (id) => {
  6221. const PSDE_4 = getProtoFn(selfGame["game.model.user.shop.PlayerShopDataEntry"], 4);
  6222. const shops = this.getShops();
  6223. const shop = shops[id]?.[PSDE_4];
  6224. return shop;
  6225. }
  6226.  
  6227. /**
  6228. * Moves to the store with the specified ID
  6229. *
  6230. * Перемещает к магазину с указанным идетификатором
  6231. */
  6232. this.goShopId = function (id) {
  6233. const shop = this.getShop(id);
  6234. if (!shop) {
  6235. return;
  6236. }
  6237. let event = new selfGame["game.mediator.gui.popup.PopupStashEventParams"];
  6238. let Game = selfGame['Game'];
  6239. let navigator = getF(Game, "get_navigator");
  6240. let navigate = getProtoFn(selfGame["game.screen.navigator.GameNavigator"], 21);
  6241. let instance = getFnP(Game, 'get_instance');
  6242. Game[instance]()[navigator]()[navigate](shop, event);
  6243. }
  6244.  
  6245. /**
  6246. * Opens a list of non-standard stores
  6247. *
  6248. * Открывает список не стандартных магазинов
  6249. */
  6250. this.goCustomShops = async (p = 0) => {
  6251. /** Запрос данных нужных магазинов */
  6252. const calls = [{ name: "shopGetAll", args: {}, ident: "shopGetAll" }];
  6253. const shops = lib.getData('shop');
  6254. for (const id in shops) {
  6255. const check = !shops[id].ident.includes('merchantPromo') &&
  6256. ![1, 4, 5, 6, 7, 8, 9, 10, 11, 1023, 1024].includes(+id);
  6257. if (check) {
  6258. calls.push({
  6259. name: "shopGet", args: { shopId: id }, ident: `shopGet_${id}`
  6260. })
  6261. }
  6262. }
  6263. const result = await Send({ calls }).then(e => e.results.map(n => n.result.response));
  6264. const shopAll = result.shift();
  6265. const DS_32 = getFn(Game.DataStorage, 32)
  6266.  
  6267. const SDS_5 = getProtoFn(selfGame["game.data.storage.shop.ShopDescriptionStorage"], 5)
  6268.  
  6269. const SD_19 = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 19);
  6270. const SD_1 = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 1);
  6271. const SD_9 = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 9);
  6272. const ident = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 11);
  6273.  
  6274. for (let shop of result) {
  6275. shopAll[shop.id] = shop;
  6276. // Снимаем все ограничения с магазинов
  6277. const shopLibData = Game.DataStorage[DS_32][SDS_5](shop.id)
  6278. shopLibData[SD_19] = 1;
  6279. shopLibData[SD_1] = new selfGame["game.model.user.requirement.Requirement"]
  6280. shopLibData[SD_9] = new selfGame["game.data.storage.level.LevelRequirement"]({
  6281. teamLevel: 10
  6282. });
  6283. }
  6284. /** Скрываем все остальные магазины */
  6285. for (let id in shops) {
  6286. const shopLibData = Game.DataStorage[DS_32][SDS_5](id)
  6287. if (shopLibData[ident].includes('merchantPromo')) {
  6288. shopLibData[SD_19] = 0;
  6289. shopLibData[SD_9] = new selfGame["game.data.storage.level.LevelRequirement"]({
  6290. teamLevel: 999
  6291. });
  6292. }
  6293. }
  6294.  
  6295. const instance = getFnP(Game.GameModel, 'get_instance')
  6296. const GM_0 = getProtoFn(Game.GameModel, 0);
  6297. const P_36 = getProtoFn(selfGame["game.model.user.Player"], 36);
  6298. const player = Game.GameModel[instance]()[GM_0];
  6299. /** Пересоздаем объект с магазинами */
  6300. player[P_36] = new selfGame["game.model.user.shop.PlayerShopData"](player);
  6301. player[P_36].init(shopAll);
  6302. /** Даем магазинам новые названия */
  6303. const PSDE_4 = getProtoFn(selfGame["game.model.user.shop.PlayerShopDataEntry"], 4);
  6304.  
  6305. const shopName = getFn(cheats.getShop(1), 14);
  6306. const currentShops = this.getShops();
  6307. let count = 0;
  6308. const start = 9 * p + 1;
  6309. const end = start + 8;
  6310. for (let id in currentShops) {
  6311. const shop = currentShops[id][PSDE_4];
  6312. if ([1, 4, 5, 6, 8, 9, 10, 11].includes(+id)) {
  6313. /** Скрываем стандартные магазины */
  6314. shop[SD_19] = 0;
  6315. } else {
  6316. count++;
  6317. if (count < start || count > end) {
  6318. shop[SD_19] = 0;
  6319. continue;
  6320. }
  6321. shop[SD_19] = 1;
  6322. shop[shopName] = cheats.translate("LIB_SHOP_NAME_" + id) + ' ' + id;
  6323. shop[SD_1] = new selfGame["game.model.user.requirement.Requirement"]
  6324. shop[SD_9] = new selfGame["game.data.storage.level.LevelRequirement"]({
  6325. teamLevel: 10
  6326. });
  6327. }
  6328. }
  6329. console.log(count, start, end)
  6330. /** Отправляемся в городскую лавку */
  6331. this.goShopId(1);
  6332. }
  6333.  
  6334. /**
  6335. * Opens a list of standard stores
  6336. *
  6337. * Открывает список стандартных магазинов
  6338. */
  6339. this.goDefaultShops = async () => {
  6340. const result = await Send({ calls: [{ name: "shopGetAll", args: {}, ident: "shopGetAll" }] })
  6341. .then(e => e.results.map(n => n.result.response));
  6342. const shopAll = result.shift();
  6343. const shops = lib.getData('shop');
  6344.  
  6345. const DS_8 = getFn(Game.DataStorage, 8)
  6346. const DSB_4 = getProtoFn(selfGame["game.data.storage.DescriptionStorageBase"], 4)
  6347.  
  6348. /** Получаем объект валюты магазина для оторажения */
  6349. const coins = Game.DataStorage[DS_8][DSB_4](85);
  6350. coins.__proto__ = selfGame["game.data.storage.resource.ConsumableDescription"].prototype;
  6351.  
  6352. const DS_32 = getFn(Game.DataStorage, 32)
  6353. const SDS_5 = getProtoFn(selfGame["game.data.storage.shop.ShopDescriptionStorage"], 5)
  6354.  
  6355. const SD_19 = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 19);
  6356. for (const id in shops) {
  6357. const shopLibData = Game.DataStorage[DS_32][SDS_5](id)
  6358. if ([1, 4, 5, 6, 8, 9, 10, 11].includes(+id)) {
  6359. shopLibData[SD_19] = 1;
  6360. } else {
  6361. shopLibData[SD_19] = 0;
  6362. }
  6363. }
  6364.  
  6365. const instance = getFnP(Game.GameModel, 'get_instance')
  6366. const GM_0 = getProtoFn(Game.GameModel, 0);
  6367. const P_36 = getProtoFn(selfGame["game.model.user.Player"], 36);
  6368. const player = Game.GameModel[instance]()[GM_0];
  6369. /** Пересоздаем объект с магазинами */
  6370. player[P_36] = new selfGame["game.model.user.shop.PlayerShopData"](player);
  6371. player[P_36].init(shopAll);
  6372.  
  6373. const PSDE_4 = getProtoFn(selfGame["game.model.user.shop.PlayerShopDataEntry"], 4);
  6374. const currentShops = this.getShops();
  6375. for (let id in currentShops) {
  6376. const shop = currentShops[id][PSDE_4];
  6377. if ([1, 4, 5, 6, 8, 9, 10, 11].includes(+id)) {
  6378. shop[SD_19] = 1;
  6379. } else {
  6380. shop[SD_19] = 0;
  6381. }
  6382. }
  6383. this.goShopId(1);
  6384. }
  6385.  
  6386. /**
  6387. * Opens a list of Secret Wealth stores
  6388. *
  6389. * Открывает список магазинов Тайное богатство
  6390. */
  6391. this.goSecretWealthShops = async () => {
  6392. /** Запрос данных нужных магазинов */
  6393. const calls = [{ name: "shopGetAll", args: {}, ident: "shopGetAll" }];
  6394. const shops = lib.getData('shop');
  6395. for (const id in shops) {
  6396. if (shops[id].ident.includes('merchantPromo') && shops[id].teamLevelToUnlock <= 130) {
  6397. calls.push({
  6398. name: "shopGet", args: { shopId: id }, ident: `shopGet_${id}`
  6399. })
  6400. }
  6401. }
  6402. const result = await Send({ calls }).then(e => e.results.map(n => n.result.response));
  6403. const shopAll = result.shift();
  6404. const DS_32 = getFn(Game.DataStorage, 32)
  6405.  
  6406. const SDS_5 = getProtoFn(selfGame["game.data.storage.shop.ShopDescriptionStorage"], 5)
  6407.  
  6408. const SD_19 = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 19);
  6409. const SD_1 = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 1);
  6410. const SD_9 = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 9);
  6411. const ident = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 11);
  6412. const specialCurrency = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 15);
  6413.  
  6414. const DS_8 = getFn(Game.DataStorage, 8)
  6415. const DSB_4 = getProtoFn(selfGame["game.data.storage.DescriptionStorageBase"], 4)
  6416.  
  6417. /** Получаем объект валюты магазина для оторажения */
  6418. const coins = Game.DataStorage[DS_8][DSB_4](85);
  6419. coins.__proto__ = selfGame["game.data.storage.resource.CoinDescription"].prototype;
  6420.  
  6421. for (let shop of result) {
  6422. shopAll[shop.id] = shop;
  6423. /** Снимаем все ограничения с магазинов */
  6424. const shopLibData = Game.DataStorage[DS_32][SDS_5](shop.id)
  6425. if (shopLibData[ident].includes('merchantPromo')) {
  6426. shopLibData[SD_19] = 1;
  6427. shopLibData[SD_1] = new selfGame["game.model.user.requirement.Requirement"]
  6428. shopLibData[SD_9] = new selfGame["game.data.storage.level.LevelRequirement"]({
  6429. teamLevel: 10
  6430. });
  6431. }
  6432. }
  6433.  
  6434. /** Скрываем все остальные магазины */
  6435. for (let id in shops) {
  6436. const shopLibData = Game.DataStorage[DS_32][SDS_5](id)
  6437. if (!shopLibData[ident].includes('merchantPromo')) {
  6438. shopLibData[SD_19] = 0;
  6439. }
  6440. }
  6441.  
  6442. const instance = getFnP(Game.GameModel, 'get_instance')
  6443. const GM_0 = getProtoFn(Game.GameModel, 0);
  6444. const P_36 = getProtoFn(selfGame["game.model.user.Player"], 36);
  6445. const player = Game.GameModel[instance]()[GM_0];
  6446. /** Пересоздаем объект с магазинами */
  6447. player[P_36] = new selfGame["game.model.user.shop.PlayerShopData"](player);
  6448. player[P_36].init(shopAll);
  6449. /** Даем магазинам новые названия */
  6450. const PSDE_4 = getProtoFn(selfGame["game.model.user.shop.PlayerShopDataEntry"], 4);
  6451.  
  6452. const shopName = getFn(cheats.getShop(1), 14);
  6453. const currentShops = this.getShops();
  6454. for (let id in currentShops) {
  6455. const shop = currentShops[id][PSDE_4];
  6456. if (shop[ident].includes('merchantPromo')) {
  6457. shop[SD_19] = 1;
  6458. shop[specialCurrency] = coins;
  6459. shop[shopName] = cheats.translate("LIB_SHOP_NAME_" + id) + ' ' + id;
  6460. } else if ([1, 4, 5, 6, 8, 9, 10, 11].includes(+id)) {
  6461. /** Скрываем стандартные магазины */
  6462. shop[SD_19] = 0;
  6463. }
  6464. }
  6465. /** Отправляемся в городскую лавку */
  6466. this.goShopId(1);
  6467. }
  6468.  
  6469. /**
  6470. * Change island map
  6471. *
  6472. * Сменить карту острова
  6473. */
  6474. this.changeIslandMap = (mapId = 2) => {
  6475. const GameInst = getFnP(selfGame['Game'], 'get_instance');
  6476. const GM_0 = getProtoFn(Game.GameModel, 0);
  6477. const P_59 = getProtoFn(selfGame["game.model.user.Player"], 59);
  6478. const Player = Game.GameModel[GameInst]()[GM_0];
  6479. Player[P_59].$({ id: mapId, seasonAdventure: { id: mapId, startDate: 1701914400, endDate: 1709690400, closed: false } });
  6480.  
  6481. const GN_15 = getProtoFn(selfGame["game.screen.navigator.GameNavigator"], 15)
  6482. const navigator = getF(selfGame['Game'], "get_navigator");
  6483. selfGame['Game'][GameInst]()[navigator]()[GN_15](new selfGame["game.mediator.gui.popup.PopupStashEventParams"]);
  6484. }
  6485.  
  6486. /**
  6487. * Game library availability tracker
  6488. *
  6489. * Отслеживание доступности игровой библиотеки
  6490. */
  6491. function checkLibLoad() {
  6492. timeout = setTimeout(() => {
  6493. if (Game.GameModel) {
  6494. changeLib();
  6495. } else {
  6496. checkLibLoad();
  6497. }
  6498. }, 100)
  6499. }
  6500.  
  6501. /**
  6502. * Game library data spoofing
  6503. *
  6504. * Подмена данных игровой библиотеки
  6505. */
  6506. function changeLib() {
  6507. console.log('lib connect');
  6508. const originalStartFunc = Game.GameModel.prototype.start;
  6509. Game.GameModel.prototype.start = function (a, b, c) {
  6510. self.libGame = b.raw;
  6511. try {
  6512. const levels = b.raw.seasonAdventure.level;
  6513. for (const id in levels) {
  6514. const level = levels[id];
  6515. level.clientData.graphics.fogged[0] = level.clientData.graphics.visible[0]
  6516. }
  6517. // b.raw.shop[26].requirements = null;
  6518. // b.raw.shop[28].requirements = null;
  6519. // b.raw.shop[29].requirements = null;
  6520. } catch (e) {
  6521. console.warn(e);
  6522. }
  6523. originalStartFunc.call(this, a, b, c);
  6524. }
  6525. }
  6526.  
  6527. /**
  6528. * Returns the value of a language constant
  6529. *
  6530. * Возвращает значение языковой константы
  6531. * @param {*} langConst language constant // языковая константа
  6532. * @returns
  6533. */
  6534. this.translate = function (langConst) {
  6535. return Game.Translate.translate(langConst);
  6536. }
  6537.  
  6538. connectGame();
  6539. checkLibLoad();
  6540. }
  6541.  
  6542. /**
  6543. * Auto collection of gifts
  6544. *
  6545. * Автосбор подарков
  6546. */
  6547. function getAutoGifts() {
  6548. let valName = 'giftSendIds_' + userInfo.id;
  6549.  
  6550. if (!localStorage['clearGift' + userInfo.id]) {
  6551. localStorage[valName] = '';
  6552. localStorage['clearGift' + userInfo.id] = '+';
  6553. }
  6554.  
  6555. if (!localStorage[valName]) {
  6556. localStorage[valName] = '';
  6557. }
  6558.  
  6559. /**
  6560. * Submit a request to receive gift codes
  6561. *
  6562. * Отправка запроса для получения кодов подарков
  6563. */
  6564. fetch('https://zingery.ru/heroes/getGifts.php', {
  6565. method: 'POST',
  6566. body: JSON.stringify({scriptInfo, userInfo})
  6567. }).then(
  6568. response => response.json()
  6569. ).then(
  6570. data => {
  6571. let freebieCheckCalls = {
  6572. calls: []
  6573. }
  6574. data.forEach((giftId, n) => {
  6575. if (localStorage[valName].includes(giftId)) return;
  6576. //localStorage[valName] += ';' + giftId;
  6577. freebieCheckCalls.calls.push({
  6578. name: "freebieCheck",
  6579. args: {
  6580. giftId
  6581. },
  6582. ident: giftId
  6583. });
  6584. });
  6585.  
  6586. if (!freebieCheckCalls.calls.length) {
  6587. return;
  6588. }
  6589.  
  6590. send(JSON.stringify(freebieCheckCalls), e => {
  6591. let countGetGifts = 0;
  6592. const gifts = [];
  6593. for (check of e.results) {
  6594. gifts.push(check.ident);
  6595. if (check.result.response != null) {
  6596. countGetGifts++;
  6597. }
  6598. }
  6599. const saveGifts = localStorage[valName].split(';');
  6600. localStorage[valName] = [...saveGifts, ...gifts].slice(-50).join(';');
  6601. console.log(`${I18N('GIFTS')}: ${countGetGifts}`);
  6602. });
  6603. }
  6604. )
  6605. }
  6606.  
  6607. /**
  6608. * To fill the kills in the Forge of Souls
  6609. *
  6610. * Набить килов в горниле душ
  6611. */
  6612. async function bossRatingEvent() {
  6613. const topGet = await Send(JSON.stringify({ calls: [{ name: "topGet", args: { type: "bossRatingTop", extraId: 0 }, ident: "body" }] }));
  6614. if (!topGet) {
  6615. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  6616. return;
  6617. }
  6618. const replayId = topGet.results[0].result.response[0].userData.replayId;
  6619. const result = await Send(JSON.stringify({
  6620. calls: [
  6621. { name: "battleGetReplay", args: { id: replayId }, ident: "battleGetReplay" },
  6622. { name: "heroGetAll", args: {}, ident: "heroGetAll" },
  6623. { name: "pet_getAll", args: {}, ident: "pet_getAll" },
  6624. { name: "offerGetAll", args: {}, ident: "offerGetAll" }
  6625. ]
  6626. }));
  6627. const bossEventInfo = result.results[3].result.response.find(e => e.offerType == "bossEvent");
  6628. if (!bossEventInfo) {
  6629. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  6630. return;
  6631. }
  6632. const usedHeroes = bossEventInfo.progress.usedHeroes;
  6633. const party = Object.values(result.results[0].result.response.replay.attackers);
  6634. const availableHeroes = Object.values(result.results[1].result.response).map(e => e.id);
  6635. const availablePets = Object.values(result.results[2].result.response).map(e => e.id);
  6636. const calls = [];
  6637. /**
  6638. * First pack
  6639. *
  6640. * Первая пачка
  6641. */
  6642. const args = {
  6643. heroes: [],
  6644. favor: {}
  6645. }
  6646. for (let hero of party) {
  6647. if (hero.id >= 6000 && availablePets.includes(hero.id)) {
  6648. args.pet = hero.id;
  6649. continue;
  6650. }
  6651. if (!availableHeroes.includes(hero.id) || usedHeroes.includes(hero.id)) {
  6652. continue;
  6653. }
  6654. args.heroes.push(hero.id);
  6655. if (hero.favorPetId) {
  6656. args.favor[hero.id] = hero.favorPetId;
  6657. }
  6658. }
  6659. if (args.heroes.length) {
  6660. calls.push({
  6661. name: "bossRatingEvent_startBattle",
  6662. args,
  6663. ident: "body_0"
  6664. });
  6665. }
  6666. /**
  6667. * Other packs
  6668. *
  6669. * Другие пачки
  6670. */
  6671. let heroes = [];
  6672. let count = 1;
  6673. while (heroId = availableHeroes.pop()) {
  6674. if (args.heroes.includes(heroId) || usedHeroes.includes(heroId)) {
  6675. continue;
  6676. }
  6677. heroes.push(heroId);
  6678. if (heroes.length == 5) {
  6679. calls.push({
  6680. name: "bossRatingEvent_startBattle",
  6681. args: {
  6682. heroes: [...heroes],
  6683. pet: availablePets[Math.floor(Math.random() * availablePets.length)]
  6684. },
  6685. ident: "body_" + count
  6686. });
  6687. heroes = [];
  6688. count++;
  6689. }
  6690. }
  6691.  
  6692. if (!calls.length) {
  6693. setProgress(`${I18N('NO_HEROES')}`, true);
  6694. return;
  6695. }
  6696.  
  6697. const resultBattles = await Send(JSON.stringify({ calls }));
  6698. console.log(resultBattles);
  6699. rewardBossRatingEvent();
  6700. }
  6701.  
  6702. /**
  6703. * Collecting Rewards from the Forge of Souls
  6704. *
  6705. * Сбор награды из Горнила Душ
  6706. */
  6707. function rewardBossRatingEvent() {
  6708. let rewardBossRatingCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  6709. send(rewardBossRatingCall, function (data) {
  6710. let bossEventInfo = data.results[0].result.response.find(e => e.offerType == "bossEvent");
  6711. if (!bossEventInfo) {
  6712. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  6713. return;
  6714. }
  6715.  
  6716. let farmedChests = bossEventInfo.progress.farmedChests;
  6717. let score = bossEventInfo.progress.score;
  6718. setProgress(`${I18N('DAMAGE_AMOUNT')}: ${score}`);
  6719. let revard = bossEventInfo.reward;
  6720.  
  6721. let getRewardCall = {
  6722. calls: []
  6723. }
  6724.  
  6725. let count = 0;
  6726. for (let i = 1; i < 10; i++) {
  6727. if (farmedChests.includes(i)) {
  6728. continue;
  6729. }
  6730. if (score < revard[i].score) {
  6731. break;
  6732. }
  6733. getRewardCall.calls.push({
  6734. name: "bossRatingEvent_getReward",
  6735. args: {
  6736. rewardId: i
  6737. },
  6738. ident: "body_" + i
  6739. });
  6740. count++;
  6741. }
  6742. if (!count) {
  6743. setProgress(`${I18N('NOTHING_TO_COLLECT')}`, true);
  6744. return;
  6745. }
  6746.  
  6747. send(JSON.stringify(getRewardCall), e => {
  6748. console.log(e);
  6749. setProgress(`${I18N('COLLECTED')} ${e?.results?.length} ${I18N('REWARD')}`, true);
  6750. });
  6751. });
  6752. }
  6753.  
  6754. /**
  6755. * Collect Easter eggs and event rewards
  6756. *
  6757. * Собрать пасхалки и награды событий
  6758. */
  6759. function offerFarmAllReward() {
  6760. const offerGetAllCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  6761. return Send(offerGetAllCall).then((data) => {
  6762. const offerGetAll = data.results[0].result.response.filter(e => e.type == "reward" && !e?.freeRewardObtained && e.reward);
  6763. if (!offerGetAll.length) {
  6764. setProgress(`${I18N('NOTHING_TO_COLLECT')}`, true);
  6765. return;
  6766. }
  6767.  
  6768. const calls = [];
  6769. for (let reward of offerGetAll) {
  6770. calls.push({
  6771. name: "offerFarmReward",
  6772. args: {
  6773. offerId: reward.id
  6774. },
  6775. ident: "offerFarmReward_" + reward.id
  6776. });
  6777. }
  6778.  
  6779. return Send(JSON.stringify({ calls })).then(e => {
  6780. console.log(e);
  6781. setProgress(`${I18N('COLLECTED')} ${e?.results?.length} ${I18N('REWARD')}`, true);
  6782. });
  6783. });
  6784. }
  6785.  
  6786. /**
  6787. * Assemble Outland
  6788. *
  6789. * Собрать запределье
  6790. */
  6791. function getOutland() {
  6792. return new Promise(function (resolve, reject) {
  6793. send('{"calls":[{"name":"bossGetAll","args":{},"ident":"bossGetAll"}]}', e => {
  6794. let bosses = e.results[0].result.response;
  6795.  
  6796. let bossRaidOpenChestCall = {
  6797. calls: []
  6798. };
  6799.  
  6800. for (let boss of bosses) {
  6801. if (boss.mayRaid) {
  6802. bossRaidOpenChestCall.calls.push({
  6803. name: "bossRaid",
  6804. args: {
  6805. bossId: boss.id
  6806. },
  6807. ident: "bossRaid_" + boss.id
  6808. });
  6809. bossRaidOpenChestCall.calls.push({
  6810. name: "bossOpenChest",
  6811. args: {
  6812. bossId: boss.id,
  6813. amount: 1,
  6814. starmoney: 0
  6815. },
  6816. ident: "bossOpenChest_" + boss.id
  6817. });
  6818. } else if (boss.chestId == 1) {
  6819. bossRaidOpenChestCall.calls.push({
  6820. name: "bossOpenChest",
  6821. args: {
  6822. bossId: boss.id,
  6823. amount: 1,
  6824. starmoney: 0
  6825. },
  6826. ident: "bossOpenChest_" + boss.id
  6827. });
  6828. }
  6829. }
  6830.  
  6831. if (!bossRaidOpenChestCall.calls.length) {
  6832. setProgress(`${I18N('OUTLAND')} ${I18N('NOTHING_TO_COLLECT')}`, true);
  6833. resolve();
  6834. return;
  6835. }
  6836.  
  6837. send(JSON.stringify(bossRaidOpenChestCall), e => {
  6838. setProgress(`${I18N('OUTLAND')} ${I18N('COLLECTED')}`, true);
  6839. resolve();
  6840. });
  6841. });
  6842. });
  6843. }
  6844.  
  6845. /**
  6846. * Collect all rewards
  6847. *
  6848. * Собрать все награды
  6849. */
  6850. function questAllFarm() {
  6851. return new Promise(function (resolve, reject) {
  6852. let questGetAllCall = {
  6853. calls: [{
  6854. name: "questGetAll",
  6855. args: {},
  6856. ident: "body"
  6857. }]
  6858. }
  6859. send(JSON.stringify(questGetAllCall), function (data) {
  6860. let questGetAll = data.results[0].result.response;
  6861. const questAllFarmCall = {
  6862. calls: []
  6863. }
  6864. let number = 0;
  6865. for (let quest of questGetAll) {
  6866. if (quest.id < 1e6 && quest.state == 2) {
  6867. questAllFarmCall.calls.push({
  6868. name: "questFarm",
  6869. args: {
  6870. questId: quest.id
  6871. },
  6872. ident: `group_${number}_body`
  6873. });
  6874. number++;
  6875. }
  6876. }
  6877.  
  6878. if (!questAllFarmCall.calls.length) {
  6879. setProgress(`${I18N('COLLECTED')} ${number} ${I18N('REWARD')}`, true);
  6880. resolve();
  6881. return;
  6882. }
  6883.  
  6884. send(JSON.stringify(questAllFarmCall), function (res) {
  6885. console.log(res);
  6886. setProgress(`${I18N('COLLECTED')} ${number} ${I18N('REWARD')}`, true);
  6887. resolve();
  6888. });
  6889. });
  6890. })
  6891. }
  6892.  
  6893. /**
  6894. * Mission auto repeat
  6895. *
  6896. * Автоповтор миссии
  6897. * isStopSendMission = false;
  6898. * isSendsMission = true;
  6899. **/
  6900. this.sendsMission = async function (param) {
  6901. if (isStopSendMission) {
  6902. isSendsMission = false;
  6903. console.log(I18N('STOPPED'));
  6904. setProgress('');
  6905. await popup.confirm(`${I18N('STOPPED')}<br>${I18N('REPETITIONS')}: ${param.count}`, [{
  6906. msg: 'Ok',
  6907. result: true
  6908. }, ])
  6909. return;
  6910. }
  6911.  
  6912. let missionStartCall = {
  6913. "calls": [{
  6914. "name": "missionStart",
  6915. "args": lastMissionStart,
  6916. "ident": "body"
  6917. }]
  6918. }
  6919. /**
  6920. * Mission Request
  6921. *
  6922. * Запрос на выполнение мисии
  6923. */
  6924. SendRequest(JSON.stringify(missionStartCall), async e => {
  6925. if (e['error']) {
  6926. isSendsMission = false;
  6927. console.log(e['error']);
  6928. setProgress('');
  6929. let msg = e['error'].name + ' ' + e['error'].description + `<br>${I18N('REPETITIONS')}: ${param.count}`;
  6930. await popup.confirm(msg, [
  6931. {msg: 'Ok', result: true},
  6932. ])
  6933. return;
  6934. }
  6935. /**
  6936. * Mission data calculation
  6937. *
  6938. * Расчет данных мисии
  6939. */
  6940. BattleCalc(e.results[0].result.response, 'get_tower', async r => {
  6941.  
  6942. let missionEndCall = {
  6943. "calls": [{
  6944. "name": "missionEnd",
  6945. "args": {
  6946. "id": param.id,
  6947. "result": r.result,
  6948. "progress": r.progress
  6949. },
  6950. "ident": "body"
  6951. }]
  6952. }
  6953. /**
  6954. * Mission Completion Request
  6955. *
  6956. * Запрос на завершение миссии
  6957. */
  6958. SendRequest(JSON.stringify(missionEndCall), async (e) => {
  6959. if (e['error']) {
  6960. isSendsMission = false;
  6961. console.log(e['error']);
  6962. setProgress('');
  6963. let msg = e['error'].name + ' ' + e['error'].description + `<br>${I18N('REPETITIONS')}: ${param.count}`;
  6964. await popup.confirm(msg, [
  6965. {msg: 'Ok', result: true},
  6966. ])
  6967. return;
  6968. }
  6969. r = e.results[0].result.response;
  6970. if (r['error']) {
  6971. isSendsMission = false;
  6972. console.log(r['error']);
  6973. setProgress('');
  6974. await popup.confirm(`<br>${I18N('REPETITIONS')}: ${param.count}` + ' 3 ' + r['error'], [
  6975. {msg: 'Ok', result: true},
  6976. ])
  6977. return;
  6978. }
  6979.  
  6980. param.count++;
  6981. setProgress(`${I18N('MISSIONS_PASSED')}: ${param.count} (${I18N('STOP')})`, false, () => {
  6982. isStopSendMission = true;
  6983. });
  6984. setTimeout(sendsMission, 1, param);
  6985. });
  6986. })
  6987. });
  6988. }
  6989.  
  6990. /**
  6991. * Recursive opening of russian dolls
  6992. *
  6993. * Рекурсивное открытие матрешек
  6994. */
  6995. function openRussianDoll(id, count, sum) {
  6996. sum = sum || 0;
  6997. sum += count;
  6998. send('{"calls":[{"name":"consumableUseLootBox","args":{"libId":'+id+',"amount":'+count+'},"ident":"body"}]}', e => {
  6999. setProgress(`${I18N('OPEN')} ${count}`, true);
  7000. let result = e.results[0].result.response;
  7001. let newCount = 0;
  7002. for(let n of result) {
  7003. if (n?.consumable && n.consumable[id]) {
  7004. newCount += n.consumable[id]
  7005. }
  7006. }
  7007. if (newCount) {
  7008. openRussianDoll(id, newCount, sum);
  7009. } else {
  7010. popup.confirm(`${I18N('TOTAL_OPEN')} ${sum}`);
  7011. }
  7012. })
  7013. }
  7014.  
  7015. /**
  7016. * Opening of russian dolls
  7017. *
  7018. * Открытие матрешек
  7019. */
  7020. async function openRussianDolls(libId, amount) {
  7021. let sum = 0;
  7022. let sumResult = [];
  7023.  
  7024. while (amount) {
  7025. sum += amount;
  7026. setProgress(`${I18N('TOTAL_OPEN')} ${sum}`);
  7027. const calls = [{
  7028. name: "consumableUseLootBox",
  7029. args: { libId, amount },
  7030. ident: "body"
  7031. }];
  7032. const result = await Send(JSON.stringify({ calls })).then(e => e.results[0].result.response);
  7033. let newCount = 0;
  7034. for (let n of result) {
  7035. if (n?.consumable && n.consumable[libId]) {
  7036. newCount += n.consumable[libId]
  7037. }
  7038. }
  7039. sumResult = [...sumResult, ...result];
  7040. amount = newCount;
  7041. }
  7042.  
  7043. setProgress(`${I18N('TOTAL_OPEN')} ${sum}`, 5000);
  7044. return sumResult;
  7045. }
  7046.  
  7047. /**
  7048. * Collect all mail, except letters with energy and charges of the portal
  7049. *
  7050. * Собрать всю почту, кроме писем с энергией и зарядами портала
  7051. */
  7052. function mailGetAll() {
  7053. const getMailInfo = '{"calls":[{"name":"mailGetAll","args":{},"ident":"body"}]}';
  7054.  
  7055. return Send(getMailInfo).then(dataMail => {
  7056. const letters = dataMail.results[0].result.response.letters;
  7057. const letterIds = lettersFilter(letters);
  7058. if (!letterIds.length) {
  7059. setProgress(I18N('NOTHING_TO_COLLECT'), true);
  7060. return;
  7061. }
  7062.  
  7063. const calls = [
  7064. { name: "mailFarm", args: { letterIds }, ident: "body" }
  7065. ];
  7066.  
  7067. return Send(JSON.stringify({ calls })).then(res => {
  7068. const lettersIds = res.results[0].result.response;
  7069. if (lettersIds) {
  7070. const countLetters = Object.keys(lettersIds).length;
  7071. setProgress(`${I18N('RECEIVED')} ${countLetters} ${I18N('LETTERS')}`, true);
  7072. }
  7073. });
  7074. });
  7075. }
  7076.  
  7077. /**
  7078. * Filters received emails
  7079. *
  7080. * Фильтрует получаемые письма
  7081. */
  7082. function lettersFilter(letters) {
  7083. const lettersIds = [];
  7084. for (let l in letters) {
  7085. letter = letters[l];
  7086. const reward = letter.reward;
  7087. if (!reward) {
  7088. continue;
  7089. }
  7090. /**
  7091. * Mail Collection Exceptions
  7092. *
  7093. * Исключения на сбор писем
  7094. */
  7095. const isFarmLetter = !(
  7096. /** Portals // сферы портала */
  7097. (reward?.refillable ? reward.refillable[45] : false) ||
  7098. /** Energy // энергия */
  7099. (reward?.stamina ? reward.stamina : false) ||
  7100. /** accelerating energy gain // ускорение набора энергии */
  7101. (reward?.buff ? true : false) ||
  7102. /** VIP Points // вип очки */
  7103. (reward?.vipPoints ? reward.vipPoints : false) ||
  7104. /** souls of heroes // душы героев */
  7105. (reward?.fragmentHero ? true : false) ||
  7106. /** heroes // герои */
  7107. (reward?.bundleHeroReward ? true : false)
  7108. );
  7109. if (isFarmLetter) {
  7110. lettersIds.push(~~letter.id);
  7111. continue;
  7112. }
  7113. /**
  7114. * Если до окончания годности письма менее 24 часов,
  7115. * то оно собирается не смотря на исключения
  7116. */
  7117. const availableUntil = +letter?.availableUntil;
  7118. if (availableUntil) {
  7119. const maxTimeLeft = 24 * 60 * 60 * 1000;
  7120. const timeLeft = (new Date(availableUntil * 1000) - new Date())
  7121. console.log('Time left:', timeLeft)
  7122. if (timeLeft < maxTimeLeft) {
  7123. lettersIds.push(~~letter.id);
  7124. continue;
  7125. }
  7126. }
  7127. }
  7128. return lettersIds;
  7129. }
  7130.  
  7131. /**
  7132. * Displaying information about the areas of the portal and attempts on the VG
  7133. *
  7134. * Отображение информации о сферах портала и попытках на ВГ
  7135. */
  7136. async function justInfo() {
  7137. return new Promise(async (resolve, reject) => {
  7138. const calls = [{
  7139. name: "userGetInfo",
  7140. args: {},
  7141. ident: "userGetInfo"
  7142. },
  7143. {
  7144. name: "clanWarGetInfo",
  7145. args: {},
  7146. ident: "clanWarGetInfo"
  7147. },
  7148. {
  7149. name: "titanArenaGetStatus",
  7150. args: {},
  7151. ident: "titanArenaGetStatus"
  7152. }];
  7153. const result = await Send(JSON.stringify({ calls }));
  7154. const infos = result.results;
  7155. const portalSphere = infos[0].result.response.refillable.find(n => n.id == 45);
  7156. const clanWarMyTries = infos[1].result.response?.myTries ?? 0;
  7157. const arePointsMax = infos[1].result.response?.arePointsMax;
  7158. const titansLevel = +(infos[2].result.response?.tier ?? 0);
  7159. const titansStatus = infos[2].result.response?.status; //peace_time || battle
  7160.  
  7161. const sanctuaryButton = buttons['goToSanctuary'].button;
  7162. const clanWarButton = buttons['goToClanWar'].button;
  7163. const titansArenaButton = buttons['testTitanArena'].button;
  7164.  
  7165. if (portalSphere.amount) {
  7166. sanctuaryButton.style.color = portalSphere.amount >= 3 ? 'red' : 'brown';
  7167. sanctuaryButton.title = `${I18N('SANCTUARY_TITLE')}\n${portalSphere.amount} ${I18N('PORTALS')}`;
  7168. } else {
  7169. sanctuaryButton.style.color = '';
  7170. sanctuaryButton.title = I18N('SANCTUARY_TITLE');
  7171. }
  7172. if (clanWarMyTries && !arePointsMax) {
  7173. clanWarButton.style.color = 'red';
  7174. clanWarButton.title = `${I18N('GUILD_WAR_TITLE')}\n${clanWarMyTries}${I18N('ATTEMPTS')}`;
  7175. } else {
  7176. clanWarButton.style.color = '';
  7177. clanWarButton.title = I18N('GUILD_WAR_TITLE');
  7178. }
  7179.  
  7180. if (titansLevel < 7 && titansStatus == 'battle') {
  7181. const partColor = Math.floor(125 * titansLevel / 7);
  7182. titansArenaButton.style.color = `rgb(255,${partColor},${partColor})`;
  7183. titansArenaButton.title = `${I18N('TITAN_ARENA_TITLE')}\n${titansLevel} ${I18N('LEVEL')}`;
  7184. } else {
  7185. titansArenaButton.style.color = '';
  7186. titansArenaButton.title = I18N('TITAN_ARENA_TITLE');
  7187. }
  7188.  
  7189. setProgress('<img src="https://zingery.ru/heroes/portal.png" style="height: 25px;position: relative;top: 5px;"> ' + `${portalSphere.amount} </br> ${I18N('GUILD_WAR')}: ${clanWarMyTries}`, true);
  7190. resolve();
  7191. });
  7192. }
  7193.  
  7194. async function buyWithPetExperience() {
  7195. const itemLib = lib.getData('inventoryItem');
  7196. 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));
  7197. const inventory = result[0];
  7198. const slot = Object.values(result[1].slots).find(e => e.cost?.consumable?.[85]);
  7199.  
  7200. const currentCount = inventory.consumable[85];
  7201. const price = slot.cost.consumable[85];
  7202.  
  7203. const typeBuyItem = Object.keys(slot.reward).pop();
  7204. const itemIdBuyItem = Object.keys(slot.reward[typeBuyItem]).pop();
  7205. const countBuyItem = slot.reward[typeBuyItem][itemIdBuyItem];
  7206. const itemName = cheats.translate(`LIB_${typeBuyItem.toUpperCase()}_NAME_${itemIdBuyItem}`);
  7207.  
  7208. if (slot.bought) {
  7209. await popup.confirm(I18N('SECRET_WEALTH_ALREADY'), [
  7210. { msg: 'Ok', result: true },
  7211. ]);
  7212. return;
  7213. }
  7214.  
  7215. const purchaseMsg = I18N('SECRET_WEALTH_BUY', { available: currentCount, countBuy: countBuyItem, name: itemName, price })
  7216. const answer = await popup.confirm(purchaseMsg, [
  7217. { msg: I18N('BTN_NO'), result: false },
  7218. { msg: I18N('BTN_YES'), result: true },
  7219. ]);
  7220.  
  7221. if (!answer) {
  7222. setProgress(I18N('SECRET_WEALTH_CANCELED'), true);
  7223. return;
  7224. }
  7225.  
  7226. if (currentCount < price) {
  7227. const msg = I18N('SECRET_WEALTH_NOT_ENOUGH', { available: currentCount, need: price });
  7228. await popup.confirm(msg, [
  7229. { msg: 'Ok', result: true },
  7230. ]);
  7231. return;
  7232. }
  7233.  
  7234. const calls = [{
  7235. name: "shopBuy",
  7236. args: {
  7237. shopId: 26,
  7238. slot: slot.id,
  7239. cost: slot.cost,
  7240. reward: slot.reward
  7241. },
  7242. ident: "body"
  7243. }];
  7244. const bought = await Send(JSON.stringify({ calls })).then(e => e.results[0].result.response);
  7245.  
  7246. const type = Object.keys(bought).pop();
  7247. const itemId = Object.keys(bought[type]).pop();
  7248. const count = bought[type][itemId];
  7249. const resultMsg = I18N('SECRET_WEALTH_PURCHASED', { count, name: itemName });
  7250. await popup.confirm(resultMsg, [
  7251. { msg: 'Ok', result: true },
  7252. ]);
  7253. }
  7254.  
  7255. async function buyWithPetExperienceAuto() {
  7256. const minCount = 450551;
  7257.  
  7258. const startCalls = [{ "name": "inventoryGet", "args": {}, "ident": "inventoryGet" }];
  7259. const libShops = lib.getData('shop');
  7260. for (const id in libShops) {
  7261. if (libShops[id].ident.includes('merchantPromo')) {
  7262. startCalls.push({
  7263. name: "shopGet", args: { shopId: id }, ident: `shopGet_${id}`
  7264. })
  7265. }
  7266. }
  7267.  
  7268. const result = await Send({ calls: startCalls }).then(e => e.results.map(n => n.result.response));
  7269. const inventory = result.shift();
  7270. const shops = result;
  7271. const calls = [];
  7272.  
  7273. for (let shop of shops) {
  7274. const slot = Object.values(shop.slots).find(e => e.cost?.consumable?.[85]);
  7275.  
  7276. if (!slot) {
  7277. continue;
  7278. }
  7279.  
  7280. const currentCount = inventory.consumable[85];
  7281. const price = slot.cost.consumable[85];
  7282. const shopName = I18N('SECRET_WEALTH_SHOP', { name: shop.id });
  7283.  
  7284. if (slot.bought) {
  7285. console.log(shopName + I18N('SECRET_WEALTH_ALREADY'));
  7286. setProgress(shopName + I18N('SECRET_WEALTH_ALREADY'), true);
  7287. continue;
  7288. }
  7289.  
  7290. if (currentCount < price) {
  7291. const msg = shopName + I18N('SECRET_WEALTH_NOT_ENOUGH', { available: currentCount, need: price });
  7292. console.log(msg);
  7293. setProgress(msg, true);
  7294. continue;
  7295. }
  7296.  
  7297. if ((currentCount - price) < minCount) {
  7298. console.log(shopName + I18N('SECRET_WEALTH_UPGRADE_NEW_PET'));
  7299. setProgress(shopName + I18N('SECRET_WEALTH_UPGRADE_NEW_PET'), true);
  7300. continue;
  7301. }
  7302.  
  7303. calls.push({
  7304. name: "shopBuy",
  7305. args: {
  7306. shopId: shop.id,
  7307. slot: slot.id,
  7308. cost: slot.cost,
  7309. reward: slot.reward
  7310. },
  7311. ident: "body_" + shop.id
  7312. });
  7313. }
  7314.  
  7315. if (!calls.length) {
  7316. setProgress(I18N('SECRET_WEALTH') + '<br>' + I18N('NOTHING_BUY'), true);
  7317. return;
  7318. }
  7319.  
  7320. const boughts = await Send(JSON.stringify({ calls })).then(e => e.results);
  7321.  
  7322. let textResult = I18N('SECRET_WEALTH');
  7323. for (const result of boughts) {
  7324. const bought = result.result.response
  7325. const type = Object.keys(bought).pop();
  7326. const itemId = Object.keys(bought[type]).pop();
  7327. const count = bought[type][itemId];
  7328. const itemLib = lib.getData('inventoryItem');
  7329. const itemName = itemLib[type][itemId].label;
  7330. textResult += ' <br>\n' + I18N('SECRET_WEALTH_PURCHASED', { count, name: itemName });
  7331. }
  7332.  
  7333. console.log(textResult, boughts);
  7334. setProgress(textResult, true);
  7335. }
  7336.  
  7337. async function getDailyBonus() {
  7338. const dailyBonusInfo = await Send(JSON.stringify({
  7339. calls: [{
  7340. name: "dailyBonusGetInfo",
  7341. args: {},
  7342. ident: "body"
  7343. }]
  7344. })).then(e => e.results[0].result.response);
  7345. const { availableToday, availableVip, currentDay } = dailyBonusInfo;
  7346.  
  7347. if (!availableToday) {
  7348. console.log('Уже собрано');
  7349. return;
  7350. }
  7351.  
  7352. const currentVipPoints = +userInfo.vipPoints;
  7353. const dailyBonusStat = lib.getData('dailyBonusStatic');
  7354. const vipInfo = lib.getData('level').vip;
  7355. let currentVipLevel = 0;
  7356. for (let i in vipInfo) {
  7357. vipLvl = vipInfo[i];
  7358. if (currentVipPoints >= vipLvl.vipPoints) {
  7359. currentVipLevel = vipLvl.level;
  7360. }
  7361. }
  7362. const vipLevelDouble = dailyBonusStat[`${currentDay}_0_0`].vipLevelDouble;
  7363.  
  7364. const calls = [{
  7365. name: "dailyBonusFarm",
  7366. args: {
  7367. vip: availableVip && currentVipLevel >= vipLevelDouble ? 1 : 0
  7368. },
  7369. ident: "body"
  7370. }];
  7371.  
  7372. const result = await Send(JSON.stringify({ calls }));
  7373. if (result.error) {
  7374. console.error(result.error);
  7375. return;
  7376. }
  7377.  
  7378. const reward = result.results[0].result.response;
  7379. const type = Object.keys(reward).pop();
  7380. const itemId = Object.keys(reward[type]).pop();
  7381. const count = reward[type][itemId];
  7382. const itemName = cheats.translate(`LIB_${type.toUpperCase()}_NAME_${itemId}`);
  7383.  
  7384. console.log(`Ежедневная награда: Получено ${count} ${itemName}`, reward);
  7385. }
  7386.  
  7387. async function farmStamina(lootBoxId = 148) {
  7388. const lootBox = await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"}]}')
  7389. .then(e => e.results[0].result.response.consumable[148]);
  7390.  
  7391. /** Добавить другие ящики */
  7392. /**
  7393. * 144 - медная шкатулка
  7394. * 145 - бронзовая шкатулка
  7395. * 148 - платиновая шкатулка
  7396. */
  7397. if (!lootBox) {
  7398. setProgress(I18N('NO_BOXES'), true);
  7399. return;
  7400. }
  7401.  
  7402. let maxFarmEnergy = getSaveVal('maxFarmEnergy', 100);
  7403. const result = await popup.confirm(I18N('OPEN_LOOTBOX', { lootBox }), [
  7404. { result: false, isClose: true },
  7405. { msg: I18N('BTN_YES'), result: true },
  7406. { msg: I18N('STAMINA'), isInput: true, default: maxFarmEnergy },
  7407. ]);
  7408. if (!+result) {
  7409. return;
  7410. }
  7411.  
  7412. if ((typeof result) !== 'boolean' && Number.parseInt(result)) {
  7413. maxFarmEnergy = +result;
  7414. setSaveVal('maxFarmEnergy', maxFarmEnergy);
  7415. } else {
  7416. maxFarmEnergy = 0;
  7417. }
  7418.  
  7419. let collectEnergy = 0;
  7420. for (let count = lootBox; count > 0; count--) {
  7421. const result = await Send('{"calls":[{"name":"consumableUseLootBox","args":{"libId":148,"amount":1},"ident":"body"}]}')
  7422. .then(e => e.results[0].result.response[0]);
  7423. if ('stamina' in result) {
  7424. setProgress(`${I18N('OPEN')}: ${lootBox - count}/${lootBox} ${I18N('STAMINA')} +${result.stamina}<br>${I18N('STAMINA')}: ${collectEnergy}`, false);
  7425. console.log(`${ I18N('STAMINA') } + ${ result.stamina }`);
  7426. if (!maxFarmEnergy) {
  7427. return;
  7428. }
  7429. collectEnergy += +result.stamina;
  7430. if (collectEnergy >= maxFarmEnergy) {
  7431. console.log(`${I18N('STAMINA')} + ${ collectEnergy }`);
  7432. setProgress(`${I18N('STAMINA')} + ${ collectEnergy }`, false);
  7433. return;
  7434. }
  7435. } else {
  7436. setProgress(`${I18N('OPEN')}: ${lootBox - count}/${lootBox}<br>${I18N('STAMINA')}: ${collectEnergy}`, false);
  7437. console.log(result);
  7438. }
  7439. }
  7440.  
  7441. setProgress(I18N('BOXES_OVER'), true);
  7442. }
  7443.  
  7444. async function fillActive() {
  7445. const data = await Send(JSON.stringify({
  7446. calls: [{
  7447. name: "questGetAll",
  7448. args: {},
  7449. ident: "questGetAll"
  7450. }, {
  7451. name: "inventoryGet",
  7452. args: {},
  7453. ident: "inventoryGet"
  7454. }, {
  7455. name: "clanGetInfo",
  7456. args: {},
  7457. ident: "clanGetInfo"
  7458. }
  7459. ]
  7460. })).then(e => e.results.map(n => n.result.response));
  7461.  
  7462. const quests = data[0];
  7463. const inv = data[1];
  7464. const stat = data[2].stat;
  7465. const maxActive = 2000 - stat.todayItemsActivity;
  7466. if (maxActive <= 0) {
  7467. setProgress(I18N('NO_MORE_ACTIVITY'), true);
  7468. return;
  7469. }
  7470. let countGetActive = 0;
  7471. const quest = quests.find(e => e.id > 10046 && e.id < 10051);
  7472. if (quest) {
  7473. countGetActive = 1750 - quest.progress;
  7474. }
  7475. if (countGetActive <= 0) {
  7476. countGetActive = maxActive;
  7477. }
  7478. console.log(countGetActive);
  7479.  
  7480. countGetActive = +(await popup.confirm(I18N('EXCHANGE_ITEMS', { maxActive }), [
  7481. { result: false, isClose: true },
  7482. { msg: I18N('GET_ACTIVITY'), isInput: true, default: countGetActive.toString() },
  7483. ]));
  7484.  
  7485. if (!countGetActive) {
  7486. return;
  7487. }
  7488.  
  7489. if (countGetActive > maxActive) {
  7490. countGetActive = maxActive;
  7491. }
  7492.  
  7493. const items = lib.getData('inventoryItem');
  7494.  
  7495. let itemsInfo = [];
  7496. for (let type of ['gear', 'scroll']) {
  7497. for (let i in inv[type]) {
  7498. const v = items[type][i]?.enchantValue || 0;
  7499. itemsInfo.push({
  7500. id: i,
  7501. count: inv[type][i],
  7502. v,
  7503. type
  7504. })
  7505. }
  7506. const invType = 'fragment' + type.toLowerCase().charAt(0).toUpperCase() + type.slice(1);
  7507. for (let i in inv[invType]) {
  7508. const v = items[type][i]?.fragmentEnchantValue || 0;
  7509. itemsInfo.push({
  7510. id: i,
  7511. count: inv[invType][i],
  7512. v,
  7513. type: invType
  7514. })
  7515. }
  7516. }
  7517. itemsInfo = itemsInfo.filter(e => e.v < 4 && e.count > 200);
  7518. itemsInfo = itemsInfo.sort((a, b) => b.count - a.count);
  7519. console.log(itemsInfo);
  7520. const activeItem = itemsInfo.shift();
  7521. console.log(activeItem);
  7522. const countItem = Math.ceil(countGetActive / activeItem.v);
  7523. if (countItem > activeItem.count) {
  7524. setProgress(I18N('NOT_ENOUGH_ITEMS'), true);
  7525. console.log(activeItem);
  7526. return;
  7527. }
  7528.  
  7529. await Send(JSON.stringify({
  7530. calls: [{
  7531. name: "clanItemsForActivity",
  7532. args: {
  7533. items: {
  7534. [activeItem.type]: {
  7535. [activeItem.id]: countItem
  7536. }
  7537. }
  7538. },
  7539. ident: "body"
  7540. }]
  7541. })).then(e => {
  7542. /** TODO: Вывести потраченые предметы */
  7543. console.log(e);
  7544. setProgress(`${I18N('ACTIVITY_RECEIVED')}: ` + e.results[0].result.response, true);
  7545. });
  7546. }
  7547.  
  7548. async function buyHeroFragments() {
  7549. const result = await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"},{"name":"shopGetAll","args":{},"ident":"shopGetAll"}]}')
  7550. .then(e => e.results.map(n => n.result.response));
  7551. const inv = result[0];
  7552. const shops = Object.values(result[1]).filter(shop => [4, 5, 6, 8, 9, 10, 17].includes(shop.id));
  7553. const calls = [];
  7554.  
  7555. for (let shop of shops) {
  7556. const slots = Object.values(shop.slots);
  7557. for (const slot of slots) {
  7558. /* Уже куплено */
  7559. if (slot.bought) {
  7560. continue;
  7561. }
  7562. /* Не душа героя */
  7563. if (!('fragmentHero' in slot.reward)) {
  7564. continue;
  7565. }
  7566. const coin = Object.keys(slot.cost).pop();
  7567. const coinId = Object.keys(slot.cost[coin]).pop();
  7568. const stock = inv[coin][coinId] || 0;
  7569. /* Не хватает на покупку */
  7570. if (slot.cost[coin][coinId] > stock) {
  7571. continue;
  7572. }
  7573. inv[coin][coinId] -= slot.cost[coin][coinId];
  7574. calls.push({
  7575. name: "shopBuy",
  7576. args: {
  7577. shopId: shop.id,
  7578. slot: slot.id,
  7579. cost: slot.cost,
  7580. reward: slot.reward,
  7581. },
  7582. ident: `shopBuy_${shop.id}_${slot.id}`,
  7583. })
  7584. }
  7585. }
  7586.  
  7587. if (!calls.length) {
  7588. setProgress(I18N('NO_PURCHASABLE_HERO_SOULS'), true);
  7589. return;
  7590. }
  7591.  
  7592. const bought = await Send(JSON.stringify({ calls })).then(e => e.results.map(n => n.result.response));
  7593. if (!bought) {
  7594. console.log('что-то пошло не так')
  7595. return;
  7596. }
  7597.  
  7598. let countHeroSouls = 0;
  7599. for (const buy of bought) {
  7600. countHeroSouls += +Object.values(Object.values(buy).pop()).pop();
  7601. }
  7602. console.log(countHeroSouls, bought, calls);
  7603. setProgress(I18N('PURCHASED_HERO_SOULS', { countHeroSouls }), true);
  7604. }
  7605.  
  7606. /** Открыть платные сундуки в Запределье за 90 */
  7607. async function bossOpenChestPay() {
  7608. const info = await Send('{"calls":[{"name":"userGetInfo","args":{},"ident":"userGetInfo"},{"name":"bossGetAll","args":{},"ident":"bossGetAll"}]}')
  7609. .then(e => e.results.map(n => n.result.response));
  7610.  
  7611. const user = info[0];
  7612. const boses = info[1];
  7613.  
  7614. const currentStarMoney = user.starMoney;
  7615. if (currentStarMoney < 540) {
  7616. setProgress(I18N('NOT_ENOUGH_EMERALDS_540', { currentStarMoney }), true);
  7617. return;
  7618. }
  7619.  
  7620. const calls = [];
  7621.  
  7622. let n = 0;
  7623. const amount = 1;
  7624. for (let boss of boses) {
  7625. const bossId = boss.id;
  7626. if (boss.chestNum != 2) {
  7627. continue;
  7628. }
  7629. for (const starmoney of [90, 90, 0]) {
  7630. calls.push({
  7631. name: "bossOpenChest",
  7632. args: {
  7633. bossId,
  7634. amount,
  7635. starmoney
  7636. },
  7637. ident: "bossOpenChest_" + (++n)
  7638. });
  7639. }
  7640. }
  7641.  
  7642. if (!calls.length) {
  7643. setProgress(I18N('CHESTS_NOT_AVAILABLE'), true);
  7644. return;
  7645. }
  7646.  
  7647. const result = await Send(JSON.stringify({ calls }));
  7648. console.log(result);
  7649. if (result?.results) {
  7650. setProgress(`${I18N('OUTLAND_CHESTS_RECEIVED')}: ` + result.results.length, true);
  7651. } else {
  7652. setProgress(I18N('CHESTS_NOT_AVAILABLE'), true);
  7653. }
  7654. }
  7655.  
  7656. async function autoRaidAdventure() {
  7657. const calls = [
  7658. {
  7659. name: "userGetInfo",
  7660. args: {},
  7661. ident: "userGetInfo"
  7662. },
  7663. {
  7664. name: "adventure_raidGetInfo",
  7665. args: {},
  7666. ident: "adventure_raidGetInfo"
  7667. }
  7668. ];
  7669. const result = await Send(JSON.stringify({ calls }))
  7670. .then(e => e.results.map(n => n.result.response));
  7671.  
  7672. const portalSphere = result[0].refillable.find(n => n.id == 45);
  7673. const adventureRaid = Object.entries(result[1].raid).filter(e => e[1]).pop()
  7674. const adventureId = adventureRaid ? adventureRaid[0] : 0;
  7675.  
  7676. if (!portalSphere.amount || !adventureId) {
  7677. setProgress(I18N('RAID_NOT_AVAILABLE'), true);
  7678. return;
  7679. }
  7680.  
  7681. const countRaid = +(await popup.confirm(I18N('RAID_ADVENTURE', { adventureId }), [
  7682. { result: false, isClose: true },
  7683. { msg: 'Рейд', isInput: true, default: portalSphere.amount },
  7684. ]));
  7685.  
  7686. if (!countRaid) {
  7687. return;
  7688. }
  7689.  
  7690. if (countRaid > portalSphere.amount) {
  7691. countRaid = portalSphere.amount;
  7692. }
  7693.  
  7694. const resultRaid = await Send(JSON.stringify({
  7695. calls: [...Array(countRaid)].map((e, i) => ({
  7696. name: "adventure_raid",
  7697. args: {
  7698. adventureId
  7699. },
  7700. ident: `body_${i}`
  7701. }))
  7702. })).then(e => e.results.map(n => n.result.response));
  7703.  
  7704. if (!resultRaid.length) {
  7705. console.log(resultRaid);
  7706. setProgress(I18N('SOMETHING_WENT_WRONG'), true);
  7707. return;
  7708. }
  7709.  
  7710. console.log(resultRaid, adventureId, portalSphere.amount);
  7711. setProgress(I18N('ADVENTURE_COMPLETED', { adventureId, times: resultRaid.length }), true);
  7712. }
  7713.  
  7714. /** Вывести всю клановую статистику в консоль браузера */
  7715. async function clanStatistic() {
  7716. const copy = function (text) {
  7717. const copyTextarea = document.createElement("textarea");
  7718. copyTextarea.style.opacity = "0";
  7719. copyTextarea.textContent = text;
  7720. document.body.appendChild(copyTextarea);
  7721. copyTextarea.select();
  7722. document.execCommand("copy");
  7723. document.body.removeChild(copyTextarea);
  7724. delete copyTextarea;
  7725. }
  7726. const calls = [
  7727. { name: "clanGetInfo", args: {}, ident: "clanGetInfo" },
  7728. { name: "clanGetWeeklyStat", args: {}, ident: "clanGetWeeklyStat" },
  7729. { name: "clanGetLog", args: {}, ident: "clanGetLog" },
  7730. ];
  7731.  
  7732. const result = await Send(JSON.stringify({ calls }));
  7733.  
  7734. const dataClanInfo = result.results[0].result.response;
  7735. const dataClanStat = result.results[1].result.response;
  7736. const dataClanLog = result.results[2].result.response;
  7737.  
  7738. const membersStat = {};
  7739. for (let i = 0; i < dataClanStat.stat.length; i++) {
  7740. membersStat[dataClanStat.stat[i].id] = dataClanStat.stat[i];
  7741. }
  7742.  
  7743. const joinStat = {};
  7744. historyLog = dataClanLog.history;
  7745. for (let j in historyLog) {
  7746. his = historyLog[j];
  7747. if (his.event == 'join') {
  7748. joinStat[his.userId] = his.ctime;
  7749. }
  7750. }
  7751.  
  7752. const infoArr = [];
  7753. const members = dataClanInfo.clan.members;
  7754. for (let n in members) {
  7755. var member = [
  7756. n,
  7757. members[n].name,
  7758. members[n].level,
  7759. dataClanInfo.clan.warriors.includes(+n) ? 1 : 0,
  7760. (new Date(members[n].lastLoginTime * 1000)).toLocaleString().replace(',', ''),
  7761. joinStat[n] ? (new Date(joinStat[n] * 1000)).toLocaleString().replace(',', '') : '',
  7762. membersStat[n].activity.reverse().join('\t'),
  7763. membersStat[n].adventureStat.reverse().join('\t'),
  7764. membersStat[n].clanGifts.reverse().join('\t'),
  7765. membersStat[n].clanWarStat.reverse().join('\t'),
  7766. membersStat[n].dungeonActivity.reverse().join('\t'),
  7767. ];
  7768. infoArr.push(member);
  7769. }
  7770. const info = infoArr.sort((a, b) => (b[2] - a[2])).map((e) => e.join('\t')).join('\n');
  7771. console.log(info);
  7772. copy(info);
  7773. setProgress(I18N('CLAN_STAT_COPY'), true);
  7774. }
  7775.  
  7776. async function buyInStoreForGold() {
  7777. const result = await Send('{"calls":[{"name":"shopGetAll","args":{},"ident":"body"},{"name":"userGetInfo","args":{},"ident":"userGetInfo"}]}').then(e => e.results.map(n => n.result.response));
  7778. const shops = result[0];
  7779. const user = result[1];
  7780. let gold = user.gold;
  7781. const calls = [];
  7782. if (shops[17]) {
  7783. const slots = shops[17].slots;
  7784. for (let i = 1; i <= 2; i++) {
  7785. if (!slots[i].bought) {
  7786. const costGold = slots[i].cost.gold;
  7787. if ((gold - costGold) < 0) {
  7788. continue;
  7789. }
  7790. gold -= costGold;
  7791. calls.push({
  7792. name: "shopBuy",
  7793. args: {
  7794. shopId: 17,
  7795. slot: i,
  7796. cost: slots[i].cost,
  7797. reward: slots[i].reward,
  7798. },
  7799. ident: 'body_' + i,
  7800. })
  7801. }
  7802. }
  7803. }
  7804. const slots = shops[1].slots;
  7805. for (let i = 4; i <= 6; i++) {
  7806. if (!slots[i].bought && slots[i]?.cost?.gold) {
  7807. const costGold = slots[i].cost.gold;
  7808. if ((gold - costGold) < 0) {
  7809. continue;
  7810. }
  7811. gold -= costGold;
  7812. calls.push({
  7813. name: "shopBuy",
  7814. args: {
  7815. shopId: 1,
  7816. slot: i,
  7817. cost: slots[i].cost,
  7818. reward: slots[i].reward,
  7819. },
  7820. ident: 'body_' + i,
  7821. })
  7822. }
  7823. }
  7824.  
  7825. if (!calls.length) {
  7826. setProgress(I18N('NOTHING_BUY'), true);
  7827. return;
  7828. }
  7829.  
  7830. const resultBuy = await Send(JSON.stringify({ calls })).then(e => e.results.map(n => n.result.response));
  7831. console.log(resultBuy);
  7832. const countBuy = resultBuy.length;
  7833. setProgress(I18N('LOTS_BOUGHT', { countBuy }), true);
  7834. }
  7835.  
  7836. function rewardsAndMailFarm() {
  7837. return new Promise(function (resolve, reject) {
  7838. let questGetAllCall = {
  7839. calls: [{
  7840. name: "questGetAll",
  7841. args: {},
  7842. ident: "questGetAll"
  7843. }, {
  7844. name: "mailGetAll",
  7845. args: {},
  7846. ident: "mailGetAll"
  7847. }]
  7848. }
  7849. send(JSON.stringify(questGetAllCall), function (data) {
  7850. if (!data) return;
  7851. let questGetAll = data.results[0].result.response.filter(e => e.state == 2);
  7852. const questBattlePass = lib.getData('quest').battlePass;
  7853. const questChainBPass = lib.getData('battlePass').questChain;
  7854.  
  7855. const questAllFarmCall = {
  7856. calls: []
  7857. }
  7858. let number = 0;
  7859. for (let quest of questGetAll) {
  7860. if (quest.id > 1e6) {
  7861. const questInfo = questBattlePass[quest.id];
  7862. const chain = questChainBPass[questInfo.chain];
  7863. if (chain.requirement?.battlePassTicket) {
  7864. continue;
  7865. }
  7866. }
  7867. questAllFarmCall.calls.push({
  7868. name: "questFarm",
  7869. args: {
  7870. questId: quest.id
  7871. },
  7872. ident: `questFarm_${number}`
  7873. });
  7874. number++;
  7875. }
  7876.  
  7877. let letters = data?.results[1]?.result?.response?.letters;
  7878. letterIds = lettersFilter(letters);
  7879.  
  7880. if (letterIds.length) {
  7881. questAllFarmCall.calls.push({
  7882. name: "mailFarm",
  7883. args: { letterIds },
  7884. ident: "mailFarm"
  7885. })
  7886. }
  7887.  
  7888. if (!questAllFarmCall.calls.length) {
  7889. setProgress(I18N('NOTHING_TO_COLLECT'), true);
  7890. resolve();
  7891. return;
  7892. }
  7893.  
  7894. send(JSON.stringify(questAllFarmCall), function (res) {
  7895. let reSend = false;
  7896. let countQuests = 0;
  7897. let countMail = 0;
  7898. for (let call of res.results) {
  7899. if (call.ident.includes('questFarm')) {
  7900. countQuests++;
  7901. } else {
  7902. countMail = Object.keys(call.result.response).length;
  7903. }
  7904.  
  7905. /** TODO: Переписать чтоб не вызывать функцию дважды */
  7906. const newQuests = call.result.newQuests;
  7907. if (newQuests) {
  7908. for (let quest of newQuests) {
  7909. if (quest.id < 1e6 && quest.state == 2) {
  7910. reSend = true;
  7911. }
  7912. }
  7913. }
  7914. }
  7915. setProgress(I18N('COLLECT_REWARDS_AND_MAIL', { countQuests, countMail }), true);
  7916. if (reSend) {
  7917. rewardsAndMailFarm()
  7918. }
  7919. resolve();
  7920. });
  7921. });
  7922. })
  7923. }
  7924.  
  7925. class epicBrawl {
  7926. timeout = null;
  7927. time = null;
  7928.  
  7929. constructor() {
  7930. if (epicBrawl.inst) {
  7931. return epicBrawl.inst;
  7932. }
  7933. epicBrawl.inst = this;
  7934. return this;
  7935. }
  7936.  
  7937. check() {
  7938. console.log(new Date(this.time))
  7939. if (Date.now() > this.time) {
  7940. this.timeout = null;
  7941. this.start()
  7942. return;
  7943. }
  7944. this.timeout = setTimeout(this.check, 6e4);
  7945. }
  7946.  
  7947. async start() {
  7948. if (this.timeout) {
  7949. console.log(new Date(this.time))
  7950. setProgress(I18N('TIMER_ALREADY'), 3000);
  7951. return;
  7952. }
  7953. setProgress(I18N('EPIC_BRAWL'), true);
  7954. 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));
  7955. const refill = teamInfo[2].refillable.find(n => n.id == 52)
  7956. this.time = (refill.lastRefill + 3600) * 1000
  7957. const attempts = refill.amount;
  7958. if (!attempts) {
  7959. console.log(new Date(this.time));
  7960. this.check();
  7961. setProgress(I18N('NO_ATTEMPTS_TIMER_START'), 3000);
  7962. return;
  7963. }
  7964.  
  7965. const args = {
  7966. heroes: teamInfo[0].epic_brawl.filter(e => e < 1000),
  7967. pet: teamInfo[0].epic_brawl.filter(e => e > 6000).pop(),
  7968. favor: teamInfo[1].epic_brawl,
  7969. }
  7970.  
  7971. let wins = 0;
  7972. let coins = 0;
  7973. let streak = { progress: 0, nextStage: 0 };
  7974. for (let i = attempts; i > 0; i--) {
  7975. const info = await Send(JSON.stringify({
  7976. calls: [
  7977. { name: "epicBrawl_getEnemy", args: {}, ident: "epicBrawl_getEnemy" }, { name: "epicBrawl_startBattle", args, ident: "epicBrawl_startBattle" }
  7978. ]
  7979. })).then(e => e.results.map(n => n.result.response));
  7980.  
  7981. const { progress, result } = await Calc(info[1].battle);
  7982. 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));
  7983.  
  7984. const resultInfo = endResult[0].result;
  7985. streak = endResult[1];
  7986.  
  7987. wins += resultInfo.win;
  7988. coins += resultInfo.reward ? resultInfo.reward.coin[39] : 0;
  7989.  
  7990. console.log(endResult[0].result)
  7991. if (endResult[1].progress == endResult[1].nextStage) {
  7992. const farm = await Send('{"calls":[{"name":"epicBrawl_farmWinStreak","args":{},"ident":"body"}]}').then(e => e.results[0].result.response);
  7993. coins += farm.coin[39];
  7994. }
  7995.  
  7996. setProgress(I18N('EPIC_BRAWL_RESULT', {
  7997. i, wins, attempts, coins,
  7998. progress: streak.progress,
  7999. nextStage: streak.nextStage,
  8000. end: '',
  8001. }), false, hideProgress);
  8002. }
  8003.  
  8004. console.log(new Date(this.time));
  8005. this.check();
  8006. setProgress(I18N('EPIC_BRAWL_RESULT', {
  8007. wins, attempts, coins,
  8008. i: '',
  8009. progress: streak.progress,
  8010. nextStage: streak.nextStage,
  8011. end: I18N('ATTEMPT_ENDED'),
  8012. }), false, hideProgress);
  8013. }
  8014. }
  8015.  
  8016. function Sleep(ms) {
  8017. return new Promise(resolve => setTimeout(resolve, ms));
  8018. }
  8019. function countdownTimer(seconds, message) {
  8020. message = message || I18N('TIMER');
  8021. const stopTimer = Date.now() + seconds * 1e3
  8022. return new Promise(resolve => {
  8023. const interval = setInterval(async () => {
  8024. const now = Date.now();
  8025. setProgress(`${message} ${((stopTimer - now) / 1000).toFixed(2)}`, false);
  8026. if (now > stopTimer) {
  8027. clearInterval(interval);
  8028. setProgress('', 1);
  8029. resolve();
  8030. }
  8031. }, 100);
  8032. });
  8033. }
  8034.  
  8035. /** Набить килов в горниле душк */
  8036. async function bossRatingEventSouls() {
  8037. const data = await Send({
  8038. calls: [
  8039. { name: "heroGetAll", args: {}, ident: "teamGetAll" },
  8040. { name: "offerGetAll", args: {}, ident: "offerGetAll" },
  8041. { name: "pet_getAll", args: {}, ident: "pet_getAll" },
  8042. ]
  8043. });
  8044. const bossEventInfo = data.results[1].result.response.find(e => e.offerType == "bossEvent");
  8045. if (!bossEventInfo) {
  8046. setProgress('Эвент завершен', true);
  8047. return;
  8048. }
  8049.  
  8050. if (bossEventInfo.progress.score > 250) {
  8051. setProgress('Уже убито больше 250 врагов');
  8052. rewardBossRatingEventSouls();
  8053. return;
  8054. }
  8055. const availablePets = Object.values(data.results[2].result.response).map(e => e.id);
  8056. const heroGetAllList = data.results[0].result.response;
  8057. const usedHeroes = bossEventInfo.progress.usedHeroes;
  8058. const heroList = [];
  8059.  
  8060. for (let heroId in heroGetAllList) {
  8061. let hero = heroGetAllList[heroId];
  8062. if (usedHeroes.includes(hero.id)) {
  8063. continue;
  8064. }
  8065. heroList.push(hero.id);
  8066. }
  8067.  
  8068. if (!heroList.length) {
  8069. setProgress('Нет героев', true);
  8070. return;
  8071. }
  8072.  
  8073. const pet = availablePets.includes(6005) ? 6005 : availablePets[Math.floor(Math.random() * availablePets.length)];
  8074. const petLib = lib.getData('pet');
  8075. let count = 1;
  8076.  
  8077. for (const heroId of heroList) {
  8078. const args = {
  8079. heroes: [heroId],
  8080. pet
  8081. }
  8082. /** Поиск питомца для героя */
  8083. for (const petId of availablePets) {
  8084. if (petLib[petId].favorHeroes.includes(heroId)) {
  8085. args.favor = {
  8086. [heroId]: petId
  8087. }
  8088. break;
  8089. }
  8090. }
  8091.  
  8092. const calls = [{
  8093. name: "bossRatingEvent_startBattle",
  8094. args,
  8095. ident: "body"
  8096. }, {
  8097. name: "offerGetAll",
  8098. args: {},
  8099. ident: "offerGetAll"
  8100. }];
  8101.  
  8102. const res = await Send({ calls });
  8103. count++;
  8104.  
  8105. if ('error' in res) {
  8106. console.error(res.error);
  8107. setProgress('Перезагрузите игру и попробуйте позже', true);
  8108. return;
  8109. }
  8110.  
  8111. const eventInfo = res.results[1].result.response.find(e => e.offerType == "bossEvent");
  8112. if (eventInfo.progress.score > 250) {
  8113. break;
  8114. }
  8115. setProgress('Количество убитых врагов: ' + eventInfo.progress.score + '<br>Использовано ' + count + ' героев');
  8116. }
  8117.  
  8118. rewardBossRatingEventSouls();
  8119. }
  8120. /** Сбор награды из Горнила Душ */
  8121. async function rewardBossRatingEventSouls() {
  8122. const data = await Send({
  8123. calls: [
  8124. { name: "offerGetAll", args: {}, ident: "offerGetAll" }
  8125. ]
  8126. });
  8127.  
  8128. const bossEventInfo = data.results[0].result.response.find(e => e.offerType == "bossEvent");
  8129. if (!bossEventInfo) {
  8130. setProgress('Эвент завершен', true);
  8131. return;
  8132. }
  8133.  
  8134. const farmedChests = bossEventInfo.progress.farmedChests;
  8135. const score = bossEventInfo.progress.score;
  8136. // setProgress('Количество убитых врагов: ' + score);
  8137. const revard = bossEventInfo.reward;
  8138. const calls = [];
  8139.  
  8140. let count = 0;
  8141. for (let i = 1; i < 10; i++) {
  8142. if (farmedChests.includes(i)) {
  8143. continue;
  8144. }
  8145. if (score < revard[i].score) {
  8146. break;
  8147. }
  8148. calls.push({
  8149. name: "bossRatingEvent_getReward",
  8150. args: {
  8151. rewardId: i
  8152. },
  8153. ident: "body_" + i
  8154. });
  8155. count++;
  8156. }
  8157. if (!count) {
  8158. setProgress('Нечего собирать', true);
  8159. return;
  8160. }
  8161.  
  8162. Send({ calls }).then(e => {
  8163. console.log(e);
  8164. setProgress('Собрано ' + e?.results?.length + ' наград', true);
  8165. })
  8166. }
  8167. /**
  8168. * Spin the Seer
  8169. *
  8170. * Покрутить провидца
  8171. */
  8172. async function rollAscension() {
  8173. const refillable = await Send({calls:[
  8174. {
  8175. name:"userGetInfo",
  8176. args:{},
  8177. ident:"userGetInfo"
  8178. }
  8179. ]}).then(e => e.results[0].result.response.refillable);
  8180. const i47 = refillable.find(i => i.id == 47);
  8181. if (i47?.amount) {
  8182. await Send({ calls: [{ name: "ascensionChest_open", args: { paid: false, amount: 1 }, ident: "body" }] });
  8183. setProgress(I18N('DONE'), true);
  8184. } else {
  8185. setProgress(I18N('NOT_ENOUGH_AP'), true);
  8186. }
  8187. }
  8188.  
  8189. /**
  8190. * Collect gifts for the New Year
  8191. *
  8192. * Собрать подарки на новый год
  8193. */
  8194. function getGiftNewYear() {
  8195. Send({ calls: [{ name: "newYearGiftGet", args: { type: 0 }, ident: "body" }] }).then(e => {
  8196. const gifts = e.results[0].result.response.gifts;
  8197. const calls = gifts.filter(e => e.opened == 0).map(e => ({
  8198. name: "newYearGiftOpen",
  8199. args: {
  8200. giftId: e.id
  8201. },
  8202. ident: `body_${e.id}`
  8203. }));
  8204. if (!calls.length) {
  8205. setProgress(I18N('NY_NO_GIFTS'), 5000);
  8206. return;
  8207. }
  8208. Send({ calls }).then(e => {
  8209. console.log(e.results)
  8210. const msg = I18N('NY_GIFTS_COLLECTED', { count: e.results.length });
  8211. console.log(msg);
  8212. setProgress(msg, 5000);
  8213. });
  8214. })
  8215. }
  8216.  
  8217. async function getSomething(countSomething = 0) {
  8218. const argsForSomething = getSaveVal('argsDataForSomething', false);
  8219. if (!argsForSomething) {
  8220. console.log(I18N('NO_SOMETHING_DATA'));
  8221. setProgress(I18N('NO_SOMETHING_DATA'));
  8222. return;
  8223. }
  8224.  
  8225. const boxes = await Send({ calls: [{ name: "rewardedVideo_boxyGetInfo", args: {}, ident: "body" }] }).then(e => e.results[0].result.response.boxes);
  8226.  
  8227. const calls = [];
  8228. for (const boxId in boxes) {
  8229. if (!boxes[boxId].opened) {
  8230. const args = { ...argsForSomething };
  8231. args.boxId = boxId;
  8232. calls.push({
  8233. name: "rewardedVideo_boxyFarmReward",
  8234. args,
  8235. ident: `body_${boxId}`
  8236. })
  8237. }
  8238. }
  8239.  
  8240. if (!calls.length) {
  8241. console.log(I18N('COLLECTED_SOMETHING', { count: countSomething }))
  8242. setProgress(I18N('COLLECTED_SOMETHING', { count: countSomething }));
  8243. return;
  8244. }
  8245.  
  8246. const result = await Send({ calls }).then(e => e?.results || e);
  8247. if ('error' in result) {
  8248. await popup.confirm(I18N('ERROR_MSG', {
  8249. name: result.error.name,
  8250. description: result.error.description
  8251. }), [
  8252. { msg: 'Ok', result: false },
  8253. { result: false, isClose: true }
  8254. ])
  8255. return;
  8256. }
  8257.  
  8258. countSomething += result.length;
  8259. getSomething(countSomething);
  8260. }
  8261.  
  8262. async function updateArtifacts() {
  8263. const count = +await popup.confirm(I18N('SET_NUMBER_LEVELS'), [
  8264. { msg: I18N('BTN_GO'), isInput: true, default: 10 },
  8265. { result: false, isClose: true }
  8266. ]);
  8267. if (!count) {
  8268. return;
  8269. }
  8270. const quest = new questRun;
  8271. await quest.autoInit();
  8272. const heroes = Object.values(quest.questInfo['heroGetAll']);
  8273. const inventory = quest.questInfo['inventoryGet'];
  8274. const calls = [];
  8275. for (let i = count; i > 0; i--) {
  8276. const upArtifact = quest.getUpgradeArtifact();
  8277. const hero = heroes.find(e => e.id == upArtifact.heroId);
  8278. hero.artifacts[upArtifact.slotId].level++;
  8279. inventory[upArtifact.costСurrency][upArtifact.costId] -= upArtifact.costValue;
  8280. calls.push({
  8281. name: "heroArtifactLevelUp",
  8282. args: {
  8283. heroId: upArtifact.heroId,
  8284. slotId: upArtifact.slotId
  8285. },
  8286. ident: `heroArtifactLevelUp_${i}`
  8287. });
  8288. }
  8289.  
  8290. if (!calls.length) {
  8291. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  8292. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  8293. return;
  8294. }
  8295.  
  8296. await Send(JSON.stringify({ calls })).then(e => {
  8297. if ('error' in e) {
  8298. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  8299. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  8300. } else {
  8301. console.log(I18N('IMPROVED_LEVELS', { count: e.results.length }));
  8302. setProgress(I18N('IMPROVED_LEVELS', { count: e.results.length }), false);
  8303. }
  8304. });
  8305. }
  8306.  
  8307. async function updateSkins() {
  8308. const count = +await popup.confirm(I18N('SET_NUMBER_LEVELS'), [
  8309. { msg: I18N('BTN_GO'), isInput: true, default: 10 },
  8310. { result: false, isClose: true }
  8311. ]);
  8312. if (!count) {
  8313. return;
  8314. }
  8315.  
  8316. const quest = new questRun;
  8317. await quest.autoInit();
  8318. const heroes = Object.values(quest.questInfo['heroGetAll']);
  8319. const inventory = quest.questInfo['inventoryGet'];
  8320. const calls = [];
  8321. for (let i = count; i > 0; i--) {
  8322. const upSkin = quest.getUpgradeSkin();
  8323. const hero = heroes.find(e => e.id == upSkin.heroId);
  8324. hero.skins[upSkin.skinId]++;
  8325. inventory[upSkin.costСurrency][upSkin.costСurrencyId] -= upSkin.cost;
  8326. calls.push({
  8327. name: "heroSkinUpgrade",
  8328. args: {
  8329. heroId: upSkin.heroId,
  8330. skinId: upSkin.skinId
  8331. },
  8332. ident: `heroSkinUpgrade_${i}`
  8333. })
  8334. }
  8335.  
  8336. if (!calls.length) {
  8337. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  8338. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  8339. return;
  8340. }
  8341.  
  8342. await Send(JSON.stringify({ calls })).then(e => {
  8343. if ('error' in e) {
  8344. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  8345. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  8346. } else {
  8347. console.log(I18N('IMPROVED_LEVELS', { count: e.results.length }));
  8348. setProgress(I18N('IMPROVED_LEVELS', { count: e.results.length }), false);
  8349. }
  8350. });
  8351. }
  8352.  
  8353. /**
  8354. * Attack of the minions of Asgard
  8355. *
  8356. * Атака прислужников Асгарда
  8357. */
  8358. function testRaidNodes() {
  8359. return new Promise((resolve, reject) => {
  8360. const tower = new executeRaidNodes(resolve, reject);
  8361. tower.start();
  8362. });
  8363. }
  8364.  
  8365. /**
  8366. * Attack of the minions of Asgard
  8367. *
  8368. * Атака прислужников Асгарда
  8369. */
  8370. function executeRaidNodes(resolve, reject) {
  8371. let raidData = {
  8372. teams: [],
  8373. favor: {},
  8374. nodes: [],
  8375. attempts: 0,
  8376. countExecuteBattles: 0,
  8377. cancelBattle: 0,
  8378. }
  8379.  
  8380. callsExecuteRaidNodes = {
  8381. calls: [{
  8382. name: "clanRaid_getInfo",
  8383. args: {},
  8384. ident: "clanRaid_getInfo"
  8385. }, {
  8386. name: "teamGetAll",
  8387. args: {},
  8388. ident: "teamGetAll"
  8389. }, {
  8390. name: "teamGetFavor",
  8391. args: {},
  8392. ident: "teamGetFavor"
  8393. }]
  8394. }
  8395.  
  8396. this.start = function () {
  8397. send(JSON.stringify(callsExecuteRaidNodes), startRaidNodes);
  8398. }
  8399.  
  8400. async function startRaidNodes(data) {
  8401. res = data.results;
  8402. clanRaidInfo = res[0].result.response;
  8403. teamGetAll = res[1].result.response;
  8404. teamGetFavor = res[2].result.response;
  8405.  
  8406. let index = 0;
  8407. let isNotFullPack = false;
  8408. for (let team of teamGetAll.clanRaid_nodes) {
  8409. if (team.length < 6) {
  8410. isNotFullPack = true;
  8411. }
  8412. raidData.teams.push({
  8413. data: {},
  8414. heroes: team.filter(id => id < 6000),
  8415. pet: team.filter(id => id >= 6000).pop(),
  8416. battleIndex: index++
  8417. });
  8418. }
  8419. raidData.favor = teamGetFavor.clanRaid_nodes;
  8420.  
  8421. if (isNotFullPack) {
  8422. if (await popup.confirm(I18N('MINIONS_WARNING'), [
  8423. { msg: I18N('BTN_NO'), result: true },
  8424. { msg: I18N('BTN_YES'), result: false },
  8425. ])) {
  8426. endRaidNodes('isNotFullPack');
  8427. return;
  8428. }
  8429. }
  8430.  
  8431. raidData.nodes = clanRaidInfo.nodes;
  8432. raidData.attempts = clanRaidInfo.attempts;
  8433. isCancalBattle = false;
  8434.  
  8435. checkNodes();
  8436. }
  8437.  
  8438. function getAttackNode() {
  8439. for (let nodeId in raidData.nodes) {
  8440. let node = raidData.nodes[nodeId];
  8441. let points = 0
  8442. for (team of node.teams) {
  8443. points += team.points;
  8444. }
  8445. let now = Date.now() / 1000;
  8446. if (!points && now > node.timestamps.start && now < node.timestamps.end) {
  8447. let countTeam = node.teams.length;
  8448. delete raidData.nodes[nodeId];
  8449. return {
  8450. nodeId,
  8451. countTeam
  8452. };
  8453. }
  8454. }
  8455. return null;
  8456. }
  8457.  
  8458. function checkNodes() {
  8459. setProgress(`${I18N('REMAINING_ATTEMPTS')}: ${raidData.attempts}`);
  8460. let nodeInfo = getAttackNode();
  8461. if (nodeInfo && raidData.attempts) {
  8462. startNodeBattles(nodeInfo);
  8463. return;
  8464. }
  8465.  
  8466. endRaidNodes('EndRaidNodes');
  8467. }
  8468.  
  8469. function startNodeBattles(nodeInfo) {
  8470. let {nodeId, countTeam} = nodeInfo;
  8471. let teams = raidData.teams.slice(0, countTeam);
  8472. let heroes = raidData.teams.map(e => e.heroes).flat();
  8473. let favor = {...raidData.favor};
  8474. for (let heroId in favor) {
  8475. if (!heroes.includes(+heroId)) {
  8476. delete favor[heroId];
  8477. }
  8478. }
  8479.  
  8480. let calls = [{
  8481. name: "clanRaid_startNodeBattles",
  8482. args: {
  8483. nodeId,
  8484. teams,
  8485. favor
  8486. },
  8487. ident: "body"
  8488. }];
  8489.  
  8490. send(JSON.stringify({calls}), resultNodeBattles);
  8491. }
  8492.  
  8493. function resultNodeBattles(e) {
  8494. if (e['error']) {
  8495. endRaidNodes('nodeBattlesError', e['error']);
  8496. return;
  8497. }
  8498.  
  8499. console.log(e);
  8500. let battles = e.results[0].result.response.battles;
  8501. let promises = [];
  8502. let battleIndex = 0;
  8503. for (let battle of battles) {
  8504. battle.battleIndex = battleIndex++;
  8505. promises.push(calcBattleResult(battle));
  8506. }
  8507.  
  8508. Promise.all(promises)
  8509. .then(results => {
  8510. const endResults = {};
  8511. let isAllWin = true;
  8512. for (let r of results) {
  8513. isAllWin &&= r.result.win;
  8514. }
  8515. if (!isAllWin) {
  8516. cancelEndNodeBattle(results[0]);
  8517. return;
  8518. }
  8519. raidData.countExecuteBattles = results.length;
  8520. let timeout = 500;
  8521. for (let r of results) {
  8522. setTimeout(endNodeBattle, timeout, r);
  8523. timeout += 500;
  8524. }
  8525. });
  8526. }
  8527. /**
  8528. * Returns the battle calculation promise
  8529. *
  8530. * Возвращает промис расчета боя
  8531. */
  8532. function calcBattleResult(battleData) {
  8533. return new Promise(function (resolve, reject) {
  8534. BattleCalc(battleData, "get_clanPvp", resolve);
  8535. });
  8536. }
  8537. /**
  8538. * Cancels the fight
  8539. *
  8540. * Отменяет бой
  8541. */
  8542. function cancelEndNodeBattle(r) {
  8543. const fixBattle = function (heroes) {
  8544. for (const ids in heroes) {
  8545. hero = heroes[ids];
  8546. hero.energy = random(1, 999);
  8547. if (hero.hp > 0) {
  8548. hero.hp = random(1, hero.hp);
  8549. }
  8550. }
  8551. }
  8552. fixBattle(r.progress[0].attackers.heroes);
  8553. fixBattle(r.progress[0].defenders.heroes);
  8554. endNodeBattle(r);
  8555. }
  8556. /**
  8557. * Ends the fight
  8558. *
  8559. * Завершает бой
  8560. */
  8561. function endNodeBattle(r) {
  8562. let nodeId = r.battleData.result.nodeId;
  8563. let battleIndex = r.battleData.battleIndex;
  8564. let calls = [{
  8565. name: "clanRaid_endNodeBattle",
  8566. args: {
  8567. nodeId,
  8568. battleIndex,
  8569. result: r.result,
  8570. progress: r.progress
  8571. },
  8572. ident: "body"
  8573. }]
  8574.  
  8575. SendRequest(JSON.stringify({calls}), battleResult);
  8576. }
  8577. /**
  8578. * Processing the results of the battle
  8579. *
  8580. * Обработка результатов боя
  8581. */
  8582. function battleResult(e) {
  8583. if (e['error']) {
  8584. endRaidNodes('missionEndError', e['error']);
  8585. return;
  8586. }
  8587. r = e.results[0].result.response;
  8588. if (r['error']) {
  8589. if (r.reason == "invalidBattle") {
  8590. raidData.cancelBattle++;
  8591. checkNodes();
  8592. } else {
  8593. endRaidNodes('missionEndError', e['error']);
  8594. }
  8595. return;
  8596. }
  8597.  
  8598. if (!(--raidData.countExecuteBattles)) {
  8599. raidData.attempts--;
  8600. checkNodes();
  8601. }
  8602. }
  8603. /**
  8604. * Completing a task
  8605. *
  8606. * Завершение задачи
  8607. */
  8608. function endRaidNodes(reason, info) {
  8609. isCancalBattle = true;
  8610. let textCancel = raidData.cancelBattle ? ` ${I18N('BATTLES_CANCELED')}: ${raidData.cancelBattle}` : '';
  8611. setProgress(`${I18N('MINION_RAID')} ${I18N('COMPLETED')}! ${textCancel}`, true);
  8612. console.log(reason, info);
  8613. resolve();
  8614. }
  8615. }
  8616.  
  8617. /**
  8618. * Asgard Boss Attack Replay
  8619. *
  8620. * Повтор атаки босса Асгарда
  8621. */
  8622. function testBossBattle() {
  8623. return new Promise((resolve, reject) => {
  8624. const bossBattle = new executeBossBattle(resolve, reject);
  8625. bossBattle.start(lastBossBattle, lastBossBattleInfo);
  8626. });
  8627. }
  8628.  
  8629. /**
  8630. * Asgard Boss Attack Replay
  8631. *
  8632. * Повтор атаки босса Асгарда
  8633. */
  8634. function executeBossBattle(resolve, reject) {
  8635. let lastBossBattleArgs = {};
  8636. let reachDamage = 0;
  8637. let countBattle = 0;
  8638. let countMaxBattle = 10;
  8639. let lastDamage = 0;
  8640.  
  8641. this.start = function (battleArg, battleInfo) {
  8642. lastBossBattleArgs = battleArg;
  8643. preCalcBattle(battleInfo);
  8644. }
  8645.  
  8646. function getBattleInfo(battle) {
  8647. return new Promise(function (resolve) {
  8648. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  8649. BattleCalc(battle, getBattleType(battle.type), e => {
  8650. let extra = e.progress[0].defenders.heroes[1].extra;
  8651. resolve(extra.damageTaken + extra.damageTakenNextLevel);
  8652. });
  8653. });
  8654. }
  8655.  
  8656. function preCalcBattle(battle) {
  8657. let actions = [];
  8658. const countTestBattle = getInput('countTestBattle');
  8659. for (let i = 0; i < countTestBattle; i++) {
  8660. actions.push(getBattleInfo(battle, true));
  8661. }
  8662. Promise.all(actions)
  8663. .then(resultPreCalcBattle);
  8664. }
  8665.  
  8666. function fixDamage(damage) {
  8667. for (let i = 1e6; i > 1; i /= 10) {
  8668. if (damage > i) {
  8669. let n = i / 10;
  8670. damage = Math.ceil(damage / n) * n;
  8671. break;
  8672. }
  8673. }
  8674. return damage;
  8675. }
  8676.  
  8677. async function resultPreCalcBattle(damages) {
  8678. let maxDamage = 0;
  8679. let minDamage = 1e10;
  8680. let avgDamage = 0;
  8681. for (let damage of damages) {
  8682. avgDamage += damage
  8683. if (damage > maxDamage) {
  8684. maxDamage = damage;
  8685. }
  8686. if (damage < minDamage) {
  8687. minDamage = damage;
  8688. }
  8689. }
  8690. avgDamage /= damages.length;
  8691. console.log(damages.map(e => e.toLocaleString()).join('\n'), avgDamage, maxDamage);
  8692.  
  8693. reachDamage = fixDamage(avgDamage);
  8694. const result = await popup.confirm(
  8695. `${I18N('ROUND_STAT')} ${damages.length} ${I18N('BATTLE')}:` +
  8696. `<br>${I18N('MINIMUM')}: ` + minDamage.toLocaleString() +
  8697. `<br>${I18N('MAXIMUM')}: ` + maxDamage.toLocaleString() +
  8698. `<br>${I18N('AVERAGE')}: ` + avgDamage.toLocaleString()
  8699. /*+ '<br>Поиск урона больше чем ' + reachDamage.toLocaleString()*/
  8700. , [
  8701. { msg: I18N('BTN_OK'), result: 0},
  8702. /* {msg: 'Погнали', isInput: true, default: reachDamage}, */
  8703. ])
  8704. if (result) {
  8705. reachDamage = result;
  8706. isCancalBossBattle = false;
  8707. startBossBattle();
  8708. return;
  8709. }
  8710. endBossBattle(I18N('BTN_CANCEL'));
  8711. }
  8712.  
  8713. function startBossBattle() {
  8714. countBattle++;
  8715. countMaxBattle = getInput('countAutoBattle');
  8716. if (countBattle > countMaxBattle) {
  8717. setProgress('Превышен лимит попыток: ' + countMaxBattle, true);
  8718. endBossBattle('Превышен лимит попыток: ' + countMaxBattle);
  8719. return;
  8720. }
  8721. let calls = [{
  8722. name: "clanRaid_startBossBattle",
  8723. args: lastBossBattleArgs,
  8724. ident: "body"
  8725. }];
  8726. send(JSON.stringify({calls}), calcResultBattle);
  8727. }
  8728.  
  8729. function calcResultBattle(e) {
  8730. BattleCalc(e.results[0].result.response.battle, "get_clanPvp", resultBattle);
  8731. }
  8732.  
  8733. async function resultBattle(e) {
  8734. let extra = e.progress[0].defenders.heroes[1].extra
  8735. resultDamage = extra.damageTaken + extra.damageTakenNextLevel
  8736. console.log(resultDamage);
  8737. scriptMenu.setStatus(countBattle + ') ' + resultDamage.toLocaleString());
  8738. lastDamage = resultDamage;
  8739. if (resultDamage > reachDamage && await popup.confirm(countBattle + ') Урон ' + resultDamage.toLocaleString(), [
  8740. {msg: 'Ок', result: true},
  8741. {msg: 'Не пойдет', result: false},
  8742. ])) {
  8743. endBattle(e, false);
  8744. return;
  8745. }
  8746. cancelEndBattle(e);
  8747. }
  8748.  
  8749. function cancelEndBattle (r) {
  8750. const fixBattle = function (heroes) {
  8751. for (const ids in heroes) {
  8752. hero = heroes[ids];
  8753. hero.energy = random(1, 999);
  8754. if (hero.hp > 0) {
  8755. hero.hp = random(1, hero.hp);
  8756. }
  8757. }
  8758. }
  8759. fixBattle(r.progress[0].attackers.heroes);
  8760. fixBattle(r.progress[0].defenders.heroes);
  8761. endBattle(r, true);
  8762. }
  8763.  
  8764. function endBattle(battleResult, isCancal) {
  8765. let calls = [{
  8766. name: "clanRaid_endBossBattle",
  8767. args: {
  8768. result: battleResult.result,
  8769. progress: battleResult.progress
  8770. },
  8771. ident: "body"
  8772. }];
  8773.  
  8774. send(JSON.stringify({calls}), e => {
  8775. console.log(e);
  8776. if (isCancal) {
  8777. startBossBattle();
  8778. return;
  8779. }
  8780. scriptMenu.setStatus('Босс пробит нанесен урон: ' + lastDamage);
  8781. setTimeout(() => {
  8782. scriptMenu.setStatus('');
  8783. }, 5000);
  8784. endBossBattle('Узпех!');
  8785. });
  8786. }
  8787.  
  8788. /**
  8789. * Completing a task
  8790. *
  8791. * Завершение задачи
  8792. */
  8793. function endBossBattle(reason, info) {
  8794. isCancalBossBattle = true;
  8795. console.log(reason, info);
  8796. resolve();
  8797. }
  8798. }
  8799.  
  8800. /**
  8801. * Auto-repeat attack
  8802. *
  8803. * Автоповтор атаки
  8804. */
  8805. function testAutoBattle() {
  8806. return new Promise((resolve, reject) => {
  8807. const bossBattle = new executeAutoBattle(resolve, reject);
  8808. bossBattle.start(lastBattleArg, lastBattleInfo);
  8809. });
  8810. }
  8811.  
  8812. /**
  8813. * Auto-repeat attack
  8814. *
  8815. * Автоповтор атаки
  8816. */
  8817. function executeAutoBattle(resolve, reject) {
  8818. let battleArg = {};
  8819. let countBattle = 0;
  8820. let findCoeff = 0;
  8821. let lastCalcBattle = null;
  8822.  
  8823. this.start = function (battleArgs, battleInfo) {
  8824. battleArg = battleArgs;
  8825. preCalcBattle(battleInfo);
  8826. }
  8827. /**
  8828. * Returns a promise for combat recalculation
  8829. *
  8830. * Возвращает промис для прерасчета боя
  8831. */
  8832. function getBattleInfo(battle) {
  8833. return new Promise(function (resolve) {
  8834. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  8835. Calc(battle).then(e => {
  8836. e.coeff = calcCoeff(e, 'defenders');
  8837. resolve(e);
  8838. });
  8839. });
  8840. }
  8841. /**
  8842. * Battle recalculation
  8843. *
  8844. * Прерасчет боя
  8845. */
  8846. function preCalcBattle(battle) {
  8847. let actions = [];
  8848. const countTestBattle = getInput('countTestBattle');
  8849. for (let i = 0; i < countTestBattle; i++) {
  8850. actions.push(getBattleInfo(battle));
  8851. }
  8852. Promise.all(actions)
  8853. .then(resultPreCalcBattle);
  8854. }
  8855. /**
  8856. * Processing the results of the battle recalculation
  8857. *
  8858. * Обработка результатов прерасчета боя
  8859. */
  8860. async function resultPreCalcBattle(results) {
  8861. let countWin = results.reduce((s, w) => w.result.win + s, 0);
  8862. setProgress(`${I18N('CHANCE_TO_WIN')} ${Math.floor(countWin / results.length * 100)}% (${results.length})`, false, hideProgress);
  8863. if (countWin > 0) {
  8864. isCancalBattle = false;
  8865. startBattle();
  8866. return;
  8867. }
  8868.  
  8869. let minCoeff = 100;
  8870. let maxCoeff = -100;
  8871. let avgCoeff = 0;
  8872. results.forEach(e => {
  8873. if (e.coeff < minCoeff) minCoeff = e.coeff;
  8874. if (e.coeff > maxCoeff) maxCoeff = e.coeff;
  8875. avgCoeff += e.coeff;
  8876. });
  8877. avgCoeff /= results.length;
  8878.  
  8879. if (nameFuncStartBattle == 'invasion_bossStart' ||
  8880. nameFuncStartBattle == 'bossAttack') {
  8881. const result = await popup.confirm(
  8882. I18N('BOSS_VICTORY_IMPOSSIBLE', { battles: results.length }), [
  8883. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  8884. { msg: I18N('BTN_DO_IT'), result: true },
  8885. ])
  8886. if (result) {
  8887. isCancalBattle = false;
  8888. startBattle();
  8889. return;
  8890. }
  8891. setProgress(I18N('NOT_THIS_TIME'), true);
  8892. endAutoBattle('invasion_bossStart');
  8893. return;
  8894. }
  8895.  
  8896. const result = await popup.confirm(
  8897. I18N('VICTORY_IMPOSSIBLE') +
  8898. `<br>${I18N('ROUND_STAT')} ${results.length} ${I18N('BATTLE')}:` +
  8899. `<br>${I18N('MINIMUM')}: ` + minCoeff.toLocaleString() +
  8900. `<br>${I18N('MAXIMUM')}: ` + maxCoeff.toLocaleString() +
  8901. `<br>${I18N('AVERAGE')}: ` + avgCoeff.toLocaleString() +
  8902. `<br>${I18N('FIND_COEFF')} ` + avgCoeff.toLocaleString(), [
  8903. { msg: I18N('BTN_CANCEL'), result: 0, isCancel: true },
  8904. { msg: I18N('BTN_GO'), isInput: true, default: Math.round(avgCoeff * 1000) / 1000 },
  8905. ])
  8906. if (result) {
  8907. findCoeff = result;
  8908. isCancalBattle = false;
  8909. startBattle();
  8910. return;
  8911. }
  8912. setProgress(I18N('NOT_THIS_TIME'), true);
  8913. endAutoBattle(I18N('NOT_THIS_TIME'));
  8914. }
  8915.  
  8916. /**
  8917. * Calculation of the combat result coefficient
  8918. *
  8919. * Расчет коэфициента результата боя
  8920. */
  8921. function calcCoeff(result, packType) {
  8922. let beforeSumFactor = 0;
  8923. const beforePack = result.battleData[packType][0];
  8924. for (let heroId in beforePack) {
  8925. const hero = beforePack[heroId];
  8926. const state = hero.state;
  8927. let factor = 1;
  8928. if (state) {
  8929. const hp = state.hp / state.maxHp;
  8930. const energy = state.energy / 1e3;
  8931. factor = hp + energy / 20;
  8932. }
  8933. beforeSumFactor += factor;
  8934. }
  8935.  
  8936. let afterSumFactor = 0;
  8937. const afterPack = result.progress[0][packType].heroes;
  8938. for (let heroId in afterPack) {
  8939. const hero = afterPack[heroId];
  8940. const stateHp = beforePack[heroId]?.state?.hp || beforePack[heroId]?.stats?.hp;
  8941. const hp = hero.hp / stateHp;
  8942. const energy = hero.energy / 1e3;
  8943. const factor = hp + energy / 20;
  8944. afterSumFactor += factor;
  8945. }
  8946. const resultCoeff = -(afterSumFactor - beforeSumFactor);
  8947. return Math.round(resultCoeff * 1000) / 1000;
  8948. }
  8949. /**
  8950. * Start battle
  8951. *
  8952. * Начало боя
  8953. */
  8954. function startBattle() {
  8955. countBattle++;
  8956. const countMaxBattle = getInput('countAutoBattle');
  8957. // setProgress(countBattle + '/' + countMaxBattle);
  8958. if (countBattle > countMaxBattle) {
  8959. setProgress(`${I18N('RETRY_LIMIT_EXCEEDED')}: ${countMaxBattle}`, true);
  8960. endAutoBattle(`${I18N('RETRY_LIMIT_EXCEEDED')}: ${countMaxBattle}`)
  8961. return;
  8962. }
  8963. let calls = [{
  8964. name: nameFuncStartBattle,
  8965. args: battleArg,
  8966. ident: "body"
  8967. }];
  8968. send(JSON.stringify({
  8969. calls
  8970. }), calcResultBattle);
  8971. }
  8972. /**
  8973. * Battle calculation
  8974. *
  8975. * Расчет боя
  8976. */
  8977. async function calcResultBattle(e) {
  8978. if ('error' in e) {
  8979. const result = await popup.confirm(
  8980. I18N('ERROR_DURING_THE_BATTLE'), [
  8981. { msg: I18N('BTN_OK'), result: false },
  8982. { msg: I18N('RELOAD_GAME'), result: true },
  8983. ]);
  8984. endAutoBattle('Error', e.error);
  8985. if (result) {
  8986. location.reload();
  8987. }
  8988. return;
  8989. }
  8990. let battle = e.results[0].result.response.battle
  8991. if (nameFuncStartBattle == 'towerStartBattle' ||
  8992. nameFuncStartBattle == 'bossAttack' ||
  8993. nameFuncStartBattle == 'invasion_bossStart') {
  8994. battle = e.results[0].result.response;
  8995. }
  8996. lastCalcBattle = battle;
  8997. BattleCalc(battle, getBattleType(battle.type), resultBattle);
  8998. }
  8999. /**
  9000. * Processing the results of the battle
  9001. *
  9002. * Обработка результатов боя
  9003. */
  9004. function resultBattle(e) {
  9005. const isWin = e.result.win;
  9006. if (isWin) {
  9007. endBattle(e, false);
  9008. return;
  9009. }
  9010. const countMaxBattle = getInput('countAutoBattle');
  9011. if (findCoeff) {
  9012. const coeff = calcCoeff(e, 'defenders');
  9013. setProgress(`${countBattle}/${countMaxBattle}, ${coeff}`);
  9014. if (coeff > findCoeff) {
  9015. endBattle(e, false);
  9016. return;
  9017. }
  9018. } else {
  9019. setProgress(`${countBattle}/${countMaxBattle}`);
  9020. }
  9021. if (nameFuncStartBattle == 'towerStartBattle' ||
  9022. nameFuncStartBattle == 'bossAttack' ||
  9023. nameFuncStartBattle == 'invasion_bossStart') {
  9024. startBattle();
  9025. return;
  9026. }
  9027. cancelEndBattle(e);
  9028. }
  9029. /**
  9030. * Cancel fight
  9031. *
  9032. * Отмена боя
  9033. */
  9034. function cancelEndBattle(r) {
  9035. const fixBattle = function (heroes) {
  9036. for (const ids in heroes) {
  9037. hero = heroes[ids];
  9038. hero.energy = random(1, 999);
  9039. if (hero.hp > 0) {
  9040. hero.hp = random(1, hero.hp);
  9041. }
  9042. }
  9043. }
  9044. fixBattle(r.progress[0].attackers.heroes);
  9045. fixBattle(r.progress[0].defenders.heroes);
  9046. endBattle(r, true);
  9047. }
  9048. /**
  9049. * End of the fight
  9050. *
  9051. * Завершение боя */
  9052. function endBattle(battleResult, isCancal) {
  9053. let calls = [{
  9054. name: nameFuncEndBattle,
  9055. args: {
  9056. result: battleResult.result,
  9057. progress: battleResult.progress
  9058. },
  9059. ident: "body"
  9060. }];
  9061.  
  9062. if (nameFuncStartBattle == 'invasion_bossStart') {
  9063. calls[0].args.id = lastBattleArg.id;
  9064. }
  9065.  
  9066. send(JSON.stringify({
  9067. calls
  9068. }), async e => {
  9069. console.log(e);
  9070. if (isCancal) {
  9071. startBattle();
  9072. return;
  9073. }
  9074.  
  9075. setProgress(`${I18N('SUCCESS')}!`, 5000)
  9076. if (nameFuncStartBattle == 'invasion_bossStart' ||
  9077. nameFuncStartBattle == 'bossAttack') {
  9078. const countMaxBattle = getInput('countAutoBattle');
  9079. const bossLvl = lastCalcBattle.typeId >= 130 ? lastCalcBattle.typeId : '';
  9080. const result = await popup.confirm(
  9081. I18N('BOSS_HAS_BEEN_DEF_TEXT', { bossLvl, countBattle, countMaxBattle }), [
  9082. { msg: I18N('BTN_OK'), result: 0 },
  9083. { msg: I18N('MAKE_A_SYNC'), result: 1 },
  9084. { msg: I18N('RELOAD_GAME'), result: 2 },
  9085. ]);
  9086. if (result) {
  9087. if (result == 1) {
  9088. cheats.refreshGame();
  9089. }
  9090. if (result == 2) {
  9091. location.reload();
  9092. }
  9093. }
  9094.  
  9095. }
  9096. endAutoBattle(`${I18N('SUCCESS')}!`)
  9097. });
  9098. }
  9099. /**
  9100. * Completing a task
  9101. *
  9102. * Завершение задачи
  9103. */
  9104. function endAutoBattle(reason, info) {
  9105. isCancalBattle = true;
  9106. console.log(reason, info);
  9107. resolve();
  9108. }
  9109. }
  9110.  
  9111. function testDailyQuests() {
  9112. return new Promise((resolve, reject) => {
  9113. const quests = new dailyQuests(resolve, reject);
  9114. quests.init(questsInfo);
  9115. quests.start();
  9116. });
  9117. }
  9118.  
  9119. /**
  9120. * Automatic completion of daily quests
  9121. *
  9122. * Автоматическое выполнение ежедневных квестов
  9123. */
  9124. class dailyQuests {
  9125. /**
  9126. * Send(' {"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}').then(e => console.log(e))
  9127. * Send(' {"calls":[{"name":"heroGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  9128. * Send(' {"calls":[{"name":"titanGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  9129. * Send(' {"calls":[{"name":"inventoryGet","args":{},"ident":"body"}]}').then(e => console.log(e))
  9130. * Send(' {"calls":[{"name":"questGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  9131. * Send(' {"calls":[{"name":"bossGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  9132. */
  9133. callsList = [
  9134. "userGetInfo",
  9135. "heroGetAll",
  9136. "titanGetAll",
  9137. "inventoryGet",
  9138. "questGetAll",
  9139. "bossGetAll",
  9140. ]
  9141.  
  9142. dataQuests = {
  9143. 10001: {
  9144. description: 'Улучши умения героев 3 раза', // ++++++++++++++++
  9145. doItCall: () => {
  9146. const upgradeSkills = this.getUpgradeSkills();
  9147. return upgradeSkills.map(({ heroId, skill }, index) => ({ name: "heroUpgradeSkill", args: { heroId, skill }, "ident": `heroUpgradeSkill_${index}` }));
  9148. },
  9149. isWeCanDo: () => {
  9150. const upgradeSkills = this.getUpgradeSkills();
  9151. let sumGold = 0;
  9152. for (const skill of upgradeSkills) {
  9153. sumGold += this.skillCost(skill.value);
  9154. if (!skill.heroId) {
  9155. return false;
  9156. }
  9157. }
  9158. return this.questInfo['userGetInfo'].gold > sumGold;
  9159. },
  9160. },
  9161. 10002: {
  9162. description: 'Пройди 10 миссий', // --------------
  9163. isWeCanDo: () => false,
  9164. },
  9165. 10003: {
  9166. description: 'Пройди 3 героические миссии', // --------------
  9167. isWeCanDo: () => false,
  9168. },
  9169. 10004: {
  9170. description: 'Сразись 3 раза на Арене или Гранд Арене', // --------------
  9171. isWeCanDo: () => false,
  9172. },
  9173. 10006: {
  9174. description: 'Используй обмен изумрудов 1 раз', // ++++++++++++++++
  9175. doItCall: () => [{
  9176. name: "refillableAlchemyUse",
  9177. args: { multi: false },
  9178. ident: "refillableAlchemyUse"
  9179. }],
  9180. isWeCanDo: () => {
  9181. const starMoney = this.questInfo['userGetInfo'].starMoney;
  9182. return starMoney >= 20;
  9183. },
  9184. },
  9185. 10007: {
  9186. description: 'Соверши 1 призыв в Атриуме Душ', // ++++++++++++++++
  9187. doItCall: () => [{ name: "gacha_open", args: { ident: "heroGacha", free: true, pack: false }, ident: "gacha_open" }],
  9188. isWeCanDo: () => {
  9189. const soulCrystal = this.questInfo['inventoryGet'].coin[38];
  9190. return soulCrystal > 0;
  9191. },
  9192. },
  9193. 10016: {
  9194. description: 'Отправь подарки согильдийцам', // ++++++++++++++++
  9195. doItCall: () => [{ name: "clanSendDailyGifts", args: {}, ident: "clanSendDailyGifts" }],
  9196. isWeCanDo: () => true,
  9197. },
  9198. 10018: {
  9199. description: 'Используй зелье опыта', // ++++++++++++++++
  9200. doItCall: () => {
  9201. const expHero = this.getExpHero();
  9202. return [{
  9203. name: "consumableUseHeroXp",
  9204. args: {
  9205. heroId: expHero.heroId,
  9206. libId: expHero.libId,
  9207. amount: 1
  9208. },
  9209. ident: "consumableUseHeroXp"
  9210. }];
  9211. },
  9212. isWeCanDo: () => {
  9213. const expHero = this.getExpHero();
  9214. return expHero.heroId && expHero.libId;
  9215. },
  9216. },
  9217. 10019: {
  9218. description: 'Открой 1 сундук в Башне',
  9219. doItFunc: testTower,
  9220. isWeCanDo: () => false,
  9221. },
  9222. 10020: {
  9223. description: 'Открой 3 сундука в Запределье', // Готово
  9224. doItCall: () => {
  9225. return this.getOutlandChest();
  9226. },
  9227. isWeCanDo: () => {
  9228. const outlandChest = this.getOutlandChest();
  9229. return outlandChest.length > 0;
  9230. },
  9231. },
  9232. 10021: {
  9233. description: 'Собери 75 Титанита в Подземелье Гильдии',
  9234. isWeCanDo: () => false,
  9235. },
  9236. 10022: {
  9237. description: 'Собери 150 Титанита в Подземелье Гильдии',
  9238. doItFunc: testDungeon,
  9239. isWeCanDo: () => false,
  9240. },
  9241. 10023: {
  9242. description: 'Прокачай Дар Стихий на 1 уровень', // Готово
  9243. doItCall: () => {
  9244. const heroId = this.getHeroIdTitanGift();
  9245. return [
  9246. { name: "heroTitanGiftLevelUp", args: { heroId }, ident: "heroTitanGiftLevelUp" },
  9247. { name: "heroTitanGiftDrop", args: { heroId }, ident: "heroTitanGiftDrop" }
  9248. ]
  9249. },
  9250. isWeCanDo: () => {
  9251. const heroId = this.getHeroIdTitanGift();
  9252. return heroId;
  9253. },
  9254. },
  9255. 10024: {
  9256. description: 'Повысь уровень любого артефакта один раз', // Готово
  9257. doItCall: () => {
  9258. const upArtifact = this.getUpgradeArtifact();
  9259. return [
  9260. {
  9261. name: "heroArtifactLevelUp",
  9262. args: {
  9263. heroId: upArtifact.heroId,
  9264. slotId: upArtifact.slotId
  9265. },
  9266. ident: `heroArtifactLevelUp`
  9267. }
  9268. ];
  9269. },
  9270. isWeCanDo: () => {
  9271. const upgradeArtifact = this.getUpgradeArtifact();
  9272. return upgradeArtifact.heroId;
  9273. },
  9274. },
  9275. 10025: {
  9276. description: 'Начни 1 Экспедицию',
  9277. doItFunc: checkExpedition,
  9278. isWeCanDo: () => false,
  9279. },
  9280. 10026: {
  9281. description: 'Начни 4 Экспедиции', // --------------
  9282. doItFunc: checkExpedition,
  9283. isWeCanDo: () => false,
  9284. },
  9285. 10027: {
  9286. description: 'Победи в 1 бою Турнира Стихий',
  9287. doItFunc: testTitanArena,
  9288. isWeCanDo: () => false,
  9289. },
  9290. 10028: {
  9291. description: 'Повысь уровень любого артефакта титанов', // Готово
  9292. doItCall: () => {
  9293. const upTitanArtifact = this.getUpgradeTitanArtifact();
  9294. return [
  9295. {
  9296. name: "titanArtifactLevelUp",
  9297. args: {
  9298. titanId: upTitanArtifact.titanId,
  9299. slotId: upTitanArtifact.slotId
  9300. },
  9301. ident: `titanArtifactLevelUp`
  9302. }
  9303. ];
  9304. },
  9305. isWeCanDo: () => {
  9306. const upgradeTitanArtifact = this.getUpgradeTitanArtifact();
  9307. return upgradeTitanArtifact.titanId;
  9308. },
  9309. },
  9310. 10029: {
  9311. description: 'Открой сферу артефактов титанов', // ++++++++++++++++
  9312. doItCall: () => [{ name: "titanArtifactChestOpen", args: { amount: 1, free: true }, ident: "titanArtifactChestOpen" }],
  9313. isWeCanDo: () => {
  9314. return this.questInfo['inventoryGet']?.consumable[55] > 0
  9315. },
  9316. },
  9317. 10030: {
  9318. description: 'Улучши облик любого героя 1 раз', // Готово
  9319. doItCall: () => {
  9320. const upSkin = this.getUpgradeSkin();
  9321. return [
  9322. {
  9323. name: "heroSkinUpgrade",
  9324. args: {
  9325. heroId: upSkin.heroId,
  9326. skinId: upSkin.skinId
  9327. },
  9328. ident: `heroSkinUpgrade`
  9329. }
  9330. ];
  9331. },
  9332. isWeCanDo: () => {
  9333. const upgradeSkin = this.getUpgradeSkin();
  9334. return upgradeSkin.heroId;
  9335. },
  9336. },
  9337. 10031: {
  9338. description: 'Победи в 6 боях Турнира Стихий', // --------------
  9339. doItFunc: testTitanArena,
  9340. isWeCanDo: () => false,
  9341. },
  9342. 10043: {
  9343. description: 'Начни или присоеденись к Приключению', // --------------
  9344. isWeCanDo: () => false,
  9345. },
  9346. 10044: {
  9347. description: 'Воспользуйся призывом питомцев 1 раз', // ++++++++++++++++
  9348. doItCall: () => [{ name: "pet_chestOpen", args: { amount: 1, paid: false }, ident: "pet_chestOpen" }],
  9349. isWeCanDo: () => {
  9350. return this.questInfo['inventoryGet']?.consumable[90] > 0
  9351. },
  9352. },
  9353. 10046: {
  9354. /**
  9355. * TODO: Watch Adventure
  9356. * TODO: Смотреть приключение
  9357. */
  9358. description: 'Открой 3 сундука в Приключениях',
  9359. isWeCanDo: () => false,
  9360. },
  9361. 10047: {
  9362. description: 'Набери 150 очков активности в Гильдии', // Готово
  9363. doItCall: () => {
  9364. const enchantRune = this.getEnchantRune();
  9365. return [
  9366. {
  9367. name: "heroEnchantRune",
  9368. args: {
  9369. heroId: enchantRune.heroId,
  9370. tier: enchantRune.tier,
  9371. items: {
  9372. consumable: { [enchantRune.itemId]: 1 }
  9373. }
  9374. },
  9375. ident: `heroEnchantRune`
  9376. }
  9377. ];
  9378. },
  9379. isWeCanDo: () => {
  9380. const userInfo = this.questInfo['userGetInfo'];
  9381. const enchantRune = this.getEnchantRune();
  9382. return enchantRune.heroId && userInfo.gold > 1e3;
  9383. },
  9384. },
  9385. };
  9386.  
  9387. constructor(resolve, reject, questInfo) {
  9388. this.resolve = resolve;
  9389. this.reject = reject;
  9390. }
  9391.  
  9392. init(questInfo) {
  9393. this.questInfo = questInfo;
  9394. this.isAuto = false;
  9395. }
  9396.  
  9397. async autoInit(isAuto) {
  9398. this.isAuto = isAuto || false;
  9399. const quests = {};
  9400. const calls = this.callsList.map(name => ({
  9401. name, args: {}, ident: name
  9402. }))
  9403. const result = await Send(JSON.stringify({ calls })).then(e => e.results);
  9404. for (const call of result) {
  9405. quests[call.ident] = call.result.response;
  9406. }
  9407. this.questInfo = quests;
  9408. }
  9409.  
  9410. async start() {
  9411. /**
  9412. * TODO may not be needed
  9413. *
  9414. * TODO возожно не нужна
  9415. */
  9416. let countQuest = 0;
  9417. const weCanDo = [];
  9418. const selectedActions = getSaveVal('selectedActions', {});
  9419. for (let quest of this.questInfo['questGetAll']) {
  9420. if (quest.id in this.dataQuests && quest.state == 1) {
  9421. if (!selectedActions[quest.id]) {
  9422. selectedActions[quest.id] = {
  9423. checked: false
  9424. }
  9425. }
  9426.  
  9427. const isWeCanDo = this.dataQuests[quest.id].isWeCanDo;
  9428. if (!isWeCanDo.call(this)) {
  9429. continue;
  9430. }
  9431.  
  9432. weCanDo.push({
  9433. name: quest.id,
  9434. label: I18N(`QUEST_${quest.id}`),
  9435. checked: selectedActions[quest.id].checked
  9436. });
  9437. countQuest++;
  9438. }
  9439. }
  9440.  
  9441. if (!weCanDo.length) {
  9442. this.end(I18N('NOTHING_TO_DO'));
  9443. return;
  9444. }
  9445.  
  9446. console.log(weCanDo);
  9447. let taskList = [];
  9448. if (this.isAuto) {
  9449. taskList = weCanDo;
  9450. } else {
  9451. const answer = await popup.confirm(`${I18N('YOU_CAN_COMPLETE') }:`, [
  9452. { msg: I18N('BTN_DO_IT'), result: true },
  9453. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  9454. ], weCanDo);
  9455. if (!answer) {
  9456. this.end('');
  9457. return;
  9458. }
  9459. taskList = popup.getCheckBoxes();
  9460. taskList.forEach(e => {
  9461. selectedActions[e.name].checked = e.checked;
  9462. });
  9463. setSaveVal('selectedActions', selectedActions);
  9464. }
  9465.  
  9466. const calls = [];
  9467. let countChecked = 0;
  9468. for (const task of taskList) {
  9469. if (task.checked) {
  9470. countChecked++;
  9471. const quest = this.dataQuests[task.name]
  9472. console.log(quest.description);
  9473.  
  9474. if (quest.doItCall) {
  9475. const doItCall = quest.doItCall.call(this);
  9476. calls.push(...doItCall);
  9477. }
  9478. }
  9479. }
  9480.  
  9481. if (!countChecked) {
  9482. this.end(I18N('NOT_QUEST_COMPLETED'));
  9483. return;
  9484. }
  9485.  
  9486. const result = await Send(JSON.stringify({ calls }));
  9487. if (result.error) {
  9488. console.error(result.error, result.error.call)
  9489. }
  9490. this.end(`${I18N('COMPLETED_QUESTS')}: ${countChecked}`);
  9491. }
  9492.  
  9493. errorHandling(error) {
  9494. //console.error(error);
  9495. let errorInfo = error.toString() + '\n';
  9496. try {
  9497. const errorStack = error.stack.split('\n');
  9498. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testDoYourBest");
  9499. errorInfo += errorStack.slice(0, endStack).join('\n');
  9500. } catch (e) {
  9501. errorInfo += error.stack;
  9502. }
  9503. copyText(errorInfo);
  9504. }
  9505.  
  9506. skillCost(lvl) {
  9507. return 573 * lvl ** 0.9 + lvl ** 2.379;
  9508. }
  9509.  
  9510. getUpgradeSkills() {
  9511. const heroes = Object.values(this.questInfo['heroGetAll']);
  9512. const upgradeSkills = [
  9513. { heroId: 0, slotId: 0, value: 130 },
  9514. { heroId: 0, slotId: 0, value: 130 },
  9515. { heroId: 0, slotId: 0, value: 130 },
  9516. ];
  9517. const skillLib = lib.getData('skill');
  9518. /**
  9519. * color - 1 (белый) открывает 1 навык
  9520. * color - 2 (зеленый) открывает 2 навык
  9521. * color - 4 (синий) открывает 3 навык
  9522. * color - 7 (фиолетовый) открывает 4 навык
  9523. */
  9524. const colors = [1, 2, 4, 7];
  9525. for (const hero of heroes) {
  9526. const level = hero.level;
  9527. const color = hero.color;
  9528. for (let skillId in hero.skills) {
  9529. const tier = skillLib[skillId].tier;
  9530. const sVal = hero.skills[skillId];
  9531. if (color < colors[tier] || tier < 1 || tier > 4) {
  9532. continue;
  9533. }
  9534. for (let upSkill of upgradeSkills) {
  9535. if (sVal < upSkill.value && sVal < level) {
  9536. upSkill.value = sVal;
  9537. upSkill.heroId = hero.id;
  9538. upSkill.skill = tier;
  9539. break;
  9540. }
  9541. }
  9542. }
  9543. }
  9544. return upgradeSkills;
  9545. }
  9546.  
  9547. getUpgradeArtifact() {
  9548. const heroes = Object.values(this.questInfo['heroGetAll']);
  9549. const inventory = this.questInfo['inventoryGet'];
  9550. const upArt = { heroId: 0, slotId: 0, level: 100 };
  9551.  
  9552. const heroLib = lib.getData('hero');
  9553. const artifactLib = lib.getData('artifact');
  9554.  
  9555. for (const hero of heroes) {
  9556. const heroInfo = heroLib[hero.id];
  9557. const level = hero.level
  9558. if (level < 20) {
  9559. continue;
  9560. }
  9561.  
  9562. for (let slotId in hero.artifacts) {
  9563. const art = hero.artifacts[slotId];
  9564. /* Текущая звезданость арта */
  9565. const star = art.star;
  9566. if (!star) {
  9567. continue;
  9568. }
  9569. /* Текущий уровень арта */
  9570. const level = art.level;
  9571. if (level >= 100) {
  9572. continue;
  9573. }
  9574. /* Идентификатор арта в библиотеке */
  9575. const artifactId = heroInfo.artifacts[slotId];
  9576. const artInfo = artifactLib.id[artifactId];
  9577. const costNextLevel = artifactLib.type[artInfo.type].levels[level + 1].cost;
  9578.  
  9579. const costСurrency = Object.keys(costNextLevel).pop();
  9580. const costValues = Object.entries(costNextLevel[costСurrency]).pop();
  9581. const costId = costValues[0];
  9582. const costValue = +costValues[1];
  9583.  
  9584. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  9585. if (level < upArt.level && inventory[costСurrency][costId] >= costValue) {
  9586. upArt.level = level;
  9587. upArt.heroId = hero.id;
  9588. upArt.slotId = slotId;
  9589. upArt.costСurrency = costСurrency;
  9590. upArt.costId = costId;
  9591. upArt.costValue = costValue;
  9592. }
  9593. }
  9594. }
  9595. return upArt;
  9596. }
  9597.  
  9598. getUpgradeSkin() {
  9599. const heroes = Object.values(this.questInfo['heroGetAll']);
  9600. const inventory = this.questInfo['inventoryGet'];
  9601. const upSkin = { heroId: 0, skinId: 0, level: 60, cost: 1500 };
  9602.  
  9603. const skinLib = lib.getData('skin');
  9604.  
  9605. for (const hero of heroes) {
  9606. const level = hero.level
  9607. if (level < 20) {
  9608. continue;
  9609. }
  9610.  
  9611. for (let skinId in hero.skins) {
  9612. /* Текущий уровень скина */
  9613. const level = hero.skins[skinId];
  9614. if (level >= 60) {
  9615. continue;
  9616. }
  9617. /* Идентификатор скина в библиотеке */
  9618. const skinInfo = skinLib[skinId];
  9619. const costNextLevel = skinInfo.statData.levels[level + 1].cost;
  9620.  
  9621. const costСurrency = Object.keys(costNextLevel).pop();
  9622. const costСurrencyId = Object.keys(costNextLevel[costСurrency]).pop();
  9623. const costValue = +costNextLevel[costСurrency][costСurrencyId];
  9624.  
  9625. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  9626. if (level < upSkin.level &&
  9627. costValue < upSkin.cost &&
  9628. inventory[costСurrency][costСurrencyId] >= costValue) {
  9629. upSkin.cost = costValue;
  9630. upSkin.level = level;
  9631. upSkin.heroId = hero.id;
  9632. upSkin.skinId = skinId;
  9633. upSkin.costСurrency = costСurrency;
  9634. upSkin.costСurrencyId = costСurrencyId;
  9635. }
  9636. }
  9637. }
  9638. return upSkin;
  9639. }
  9640.  
  9641. getUpgradeTitanArtifact() {
  9642. const titans = Object.values(this.questInfo['titanGetAll']);
  9643. const inventory = this.questInfo['inventoryGet'];
  9644. const userInfo = this.questInfo['userGetInfo'];
  9645. const upArt = { titanId: 0, slotId: 0, level: 120 };
  9646.  
  9647. const titanLib = lib.getData('titan');
  9648. const artTitanLib = lib.getData('titanArtifact');
  9649.  
  9650. for (const titan of titans) {
  9651. const titanInfo = titanLib[titan.id];
  9652. // const level = titan.level
  9653. // if (level < 20) {
  9654. // continue;
  9655. // }
  9656.  
  9657. for (let slotId in titan.artifacts) {
  9658. const art = titan.artifacts[slotId];
  9659. /* Текущая звезданость арта */
  9660. const star = art.star;
  9661. if (!star) {
  9662. continue;
  9663. }
  9664. /* Текущий уровень арта */
  9665. const level = art.level;
  9666. if (level >= 120) {
  9667. continue;
  9668. }
  9669. /* Идентификатор арта в библиотеке */
  9670. const artifactId = titanInfo.artifacts[slotId];
  9671. const artInfo = artTitanLib.id[artifactId];
  9672. const costNextLevel = artTitanLib.type[artInfo.type].levels[level + 1].cost;
  9673.  
  9674. const costСurrency = Object.keys(costNextLevel).pop();
  9675. let costValue = 0;
  9676. let currentValue = 0;
  9677. if (costСurrency == 'gold') {
  9678. costValue = costNextLevel[costСurrency];
  9679. currentValue = userInfo.gold;
  9680. } else {
  9681. const costValues = Object.entries(costNextLevel[costСurrency]).pop();
  9682. const costId = costValues[0];
  9683. costValue = +costValues[1];
  9684. currentValue = inventory[costСurrency][costId];
  9685. }
  9686.  
  9687. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  9688. if (level < upArt.level && currentValue >= costValue) {
  9689. upArt.level = level;
  9690. upArt.titanId = titan.id;
  9691. upArt.slotId = slotId;
  9692. break;
  9693. }
  9694. }
  9695. }
  9696. return upArt;
  9697. }
  9698.  
  9699. getEnchantRune() {
  9700. const heroes = Object.values(this.questInfo['heroGetAll']);
  9701. const inventory = this.questInfo['inventoryGet'];
  9702. const enchRune = { heroId: 0, tier: 0, exp: 43750, itemId: 0 };
  9703. for (let i = 1; i <= 4; i++) {
  9704. if (inventory.consumable[i] > 0) {
  9705. enchRune.itemId = i;
  9706. break;
  9707. }
  9708. return enchRune;
  9709. }
  9710.  
  9711. const runeLib = lib.getData('rune');
  9712. const runeLvls = Object.values(runeLib.level);
  9713. /**
  9714. * color - 4 (синий) открывает 1 и 2 символ
  9715. * color - 7 (фиолетовый) открывает 3 символ
  9716. * color - 8 (фиолетовый +1) открывает 4 символ
  9717. * color - 9 (фиолетовый +2) открывает 5 символ
  9718. */
  9719. // TODO: кажется надо учесть уровень команды
  9720. const colors = [4, 4, 7, 8, 9];
  9721. for (const hero of heroes) {
  9722. const color = hero.color;
  9723.  
  9724.  
  9725. for (let runeTier in hero.runes) {
  9726. /* Проверка на доступность руны */
  9727. if (color < colors[runeTier]) {
  9728. continue;
  9729. }
  9730. /* Текущий опыт руны */
  9731. const exp = hero.runes[runeTier];
  9732. if (exp >= 43750) {
  9733. continue;
  9734. }
  9735.  
  9736. let level = 0;
  9737. if (exp) {
  9738. for (let lvl of runeLvls) {
  9739. if (exp >= lvl.enchantValue) {
  9740. level = lvl.level;
  9741. } else {
  9742. break;
  9743. }
  9744. }
  9745. }
  9746. /** Уровень героя необходимый для уровня руны */
  9747. const heroLevel = runeLib.level[level].heroLevel;
  9748. if (hero.level < heroLevel) {
  9749. continue;
  9750. }
  9751.  
  9752. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  9753. if (exp < enchRune.exp) {
  9754. enchRune.exp = exp;
  9755. enchRune.heroId = hero.id;
  9756. enchRune.tier = runeTier;
  9757. break;
  9758. }
  9759. }
  9760. }
  9761. return enchRune;
  9762. }
  9763.  
  9764. getOutlandChest() {
  9765. const bosses = this.questInfo['bossGetAll'];
  9766.  
  9767. const calls = [];
  9768.  
  9769. for (let boss of bosses) {
  9770. if (boss.mayRaid) {
  9771. calls.push({
  9772. name: "bossRaid",
  9773. args: {
  9774. bossId: boss.id
  9775. },
  9776. ident: "bossRaid_" + boss.id
  9777. });
  9778. calls.push({
  9779. name: "bossOpenChest",
  9780. args: {
  9781. bossId: boss.id,
  9782. amount: 1,
  9783. starmoney: 0
  9784. },
  9785. ident: "bossOpenChest_" + boss.id
  9786. });
  9787. } else if (boss.chestId == 1) {
  9788. calls.push({
  9789. name: "bossOpenChest",
  9790. args: {
  9791. bossId: boss.id,
  9792. amount: 1,
  9793. starmoney: 0
  9794. },
  9795. ident: "bossOpenChest_" + boss.id
  9796. });
  9797. }
  9798. }
  9799.  
  9800. return calls;
  9801. }
  9802.  
  9803. getExpHero() {
  9804. const heroes = Object.values(this.questInfo['heroGetAll']);
  9805. const inventory = this.questInfo['inventoryGet'];
  9806. const expHero = { heroId: 0, exp: 3625195, libId: 0 };
  9807. /** зелья опыта (consumable 9, 10, 11, 12) */
  9808. for (let i = 9; i <= 12; i++) {
  9809. if (inventory.consumable[i]) {
  9810. expHero.libId = i;
  9811. break;
  9812. }
  9813. }
  9814.  
  9815. for (const hero of heroes) {
  9816. const exp = hero.xp;
  9817. if (exp < expHero.exp) {
  9818. expHero.heroId = hero.id;
  9819. }
  9820. }
  9821. return expHero;
  9822. }
  9823.  
  9824. getHeroIdTitanGift() {
  9825. const heroes = Object.values(this.questInfo['heroGetAll']);
  9826. const inventory = this.questInfo['inventoryGet'];
  9827. const user = this.questInfo['userGetInfo'];
  9828. const titanGiftLib = lib.getData('titanGift');
  9829. /** Искры */
  9830. const titanGift = inventory.consumable[24];
  9831. let heroId = 0;
  9832. let minLevel = 30;
  9833.  
  9834. if (titanGift < 250 || user.gold < 7000) {
  9835. return 0;
  9836. }
  9837.  
  9838. for (const hero of heroes) {
  9839. if (hero.titanGiftLevel >= 30) {
  9840. continue;
  9841. }
  9842.  
  9843. if (!hero.titanGiftLevel) {
  9844. return hero.id;
  9845. }
  9846.  
  9847. const cost = titanGiftLib[hero.titanGiftLevel].cost;
  9848. if (minLevel > hero.titanGiftLevel &&
  9849. titanGift >= cost.consumable[24] &&
  9850. user.gold >= cost.gold
  9851. ) {
  9852. minLevel = hero.titanGiftLevel;
  9853. heroId = hero.id;
  9854. }
  9855. }
  9856.  
  9857. return heroId;
  9858. }
  9859.  
  9860. end(status) {
  9861. setProgress(status, true);
  9862. this.resolve();
  9863. }
  9864. }
  9865.  
  9866. this.questRun = dailyQuests;
  9867.  
  9868. function testDoYourBest() {
  9869. return new Promise((resolve, reject) => {
  9870. const doIt = new doYourBest(resolve, reject);
  9871. doIt.start();
  9872. });
  9873. }
  9874.  
  9875. /**
  9876. * Do everything button
  9877. *
  9878. * Кнопка сделать все
  9879. */
  9880. class doYourBest {
  9881.  
  9882. funcList = [
  9883. {
  9884. name: 'getOutland',
  9885. label: I18N('ASSEMBLE_OUTLAND'),
  9886. checked: false
  9887. },
  9888. {
  9889. name: 'testTower',
  9890. label: I18N('PASS_THE_TOWER'),
  9891. checked: false
  9892. },
  9893. {
  9894. name: 'checkExpedition',
  9895. label: I18N('CHECK_EXPEDITIONS'),
  9896. checked: false
  9897. },
  9898. {
  9899. name: 'testTitanArena',
  9900. label: I18N('COMPLETE_TOE'),
  9901. checked: false
  9902. },
  9903. {
  9904. name: 'mailGetAll',
  9905. label: I18N('COLLECT_MAIL'),
  9906. checked: false
  9907. },
  9908. {
  9909. name: 'collectAllStuff',
  9910. label: I18N('COLLECT_MISC'),
  9911. title: I18N('COLLECT_MISC_TITLE'),
  9912. checked: false
  9913. },
  9914. {
  9915. name: 'getDailyBonus',
  9916. label: I18N('DAILY_BONUS'),
  9917. checked: false
  9918. },
  9919. {
  9920. name: 'dailyQuests',
  9921. label: I18N('DO_DAILY_QUESTS'),
  9922. checked: false
  9923. },
  9924. {
  9925. name: 'rollAscension',
  9926. label: I18N('SEER_TITLE'),
  9927. checked: false
  9928. },
  9929. {
  9930. name: 'questAllFarm',
  9931. label: I18N('COLLECT_QUEST_REWARDS'),
  9932. checked: false
  9933. },
  9934. {
  9935. name: 'testDungeon',
  9936. label: I18N('COMPLETE_DUNGEON'),
  9937. checked: false
  9938. },
  9939. {
  9940. name: 'synchronization',
  9941. label: I18N('MAKE_A_SYNC'),
  9942. checked: false
  9943. },
  9944. {
  9945. name: 'reloadGame',
  9946. label: I18N('RELOAD_GAME'),
  9947. checked: false
  9948. },
  9949. ];
  9950.  
  9951. functions = {
  9952. getOutland,
  9953. testTower,
  9954. checkExpedition,
  9955. testTitanArena,
  9956. mailGetAll,
  9957. collectAllStuff: async () => {
  9958. await offerFarmAllReward();
  9959. 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"}]}');
  9960. },
  9961. dailyQuests: async function () {
  9962. const quests = new dailyQuests(() => { }, () => { });
  9963. await quests.autoInit(true);
  9964. await quests.start();
  9965. },
  9966. rollAscension,
  9967. getDailyBonus,
  9968. questAllFarm,
  9969. testDungeon,
  9970. synchronization: async () => {
  9971. cheats.refreshGame();
  9972. },
  9973. reloadGame: async () => {
  9974. location.reload();
  9975. },
  9976. getSomething,
  9977. }
  9978.  
  9979. constructor(resolve, reject, questInfo) {
  9980. this.resolve = resolve;
  9981. this.reject = reject;
  9982. this.questInfo = questInfo
  9983. }
  9984.  
  9985. async start() {
  9986. const selectedDoIt = getSaveVal('selectedDoIt', {});
  9987.  
  9988. if (getSaveVal('argsDataForSomething', false)) {
  9989. this.funcList.unshift({
  9990. name: 'getSomething',
  9991. label: I18N('GET_SOMETHING'),
  9992. title: I18N('GET_SOMETHING_TITLE'),
  9993. checked: false
  9994. })
  9995. }
  9996.  
  9997. this.funcList.forEach(task => {
  9998. if (!selectedDoIt[task.name]) {
  9999. selectedDoIt[task.name] = {
  10000. checked: task.checked
  10001. }
  10002. } else {
  10003. task.checked = selectedDoIt[task.name].checked
  10004. }
  10005. });
  10006.  
  10007. const answer = await popup.confirm(I18N('RUN_FUNCTION'), [
  10008. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  10009. { msg: I18N('BTN_GO'), result: true },
  10010. ], this.funcList);
  10011.  
  10012. if (!answer) {
  10013. this.end('');
  10014. return;
  10015. }
  10016.  
  10017. const taskList = popup.getCheckBoxes();
  10018. taskList.forEach(task => {
  10019. selectedDoIt[task.name].checked = task.checked;
  10020. });
  10021. setSaveVal('selectedDoIt', selectedDoIt);
  10022. for (const task of popup.getCheckBoxes()) {
  10023. if (task.checked) {
  10024. try {
  10025. setProgress(`${task.label} <br>${I18N('PERFORMED')}!`);
  10026. await this.functions[task.name]();
  10027. setProgress(`${task.label} <br>${I18N('DONE')}!`);
  10028. } catch (error) {
  10029. if (await popup.confirm(`${I18N('ERRORS_OCCURRES')}:<br> ${task.label} <br>${I18N('COPY_ERROR')}?`, [
  10030. { msg: I18N('BTN_NO'), result: false },
  10031. { msg: I18N('BTN_YES'), result: true },
  10032. ])) {
  10033. this.errorHandling(error);
  10034. }
  10035. }
  10036. }
  10037. }
  10038. setTimeout((msg) => {
  10039. this.end(msg);
  10040. }, 2000, I18N('ALL_TASK_COMPLETED'));
  10041. return;
  10042. }
  10043.  
  10044. errorHandling(error) {
  10045. //console.error(error);
  10046. let errorInfo = error.toString() + '\n';
  10047. try {
  10048. const errorStack = error.stack.split('\n');
  10049. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testDoYourBest");
  10050. errorInfo += errorStack.slice(0, endStack).join('\n');
  10051. } catch (e) {
  10052. errorInfo += error.stack;
  10053. }
  10054. copyText(errorInfo);
  10055. }
  10056.  
  10057. end(status) {
  10058. setProgress(status, true);
  10059. this.resolve();
  10060. }
  10061. }
  10062.  
  10063. /**
  10064. * Passing the adventure along the specified route
  10065. *
  10066. * Прохождение приключения по указанному маршруту
  10067. */
  10068. function testAdventure(type) {
  10069. return new Promise((resolve, reject) => {
  10070. const bossBattle = new executeAdventure(resolve, reject);
  10071. bossBattle.start(type);
  10072. });
  10073. }
  10074.  
  10075. /**
  10076. * Passing the adventure along the specified route
  10077. *
  10078. * Прохождение приключения по указанному маршруту
  10079. */
  10080. class executeAdventure {
  10081.  
  10082. type = 'default';
  10083.  
  10084. actions = {
  10085. default: {
  10086. getInfo: "adventure_getInfo",
  10087. startBattle: 'adventure_turnStartBattle',
  10088. endBattle: 'adventure_endBattle',
  10089. collectBuff: 'adventure_turnCollectBuff'
  10090. },
  10091. solo: {
  10092. getInfo: "adventureSolo_getInfo",
  10093. startBattle: 'adventureSolo_turnStartBattle',
  10094. endBattle: 'adventureSolo_endBattle',
  10095. collectBuff: 'adventureSolo_turnCollectBuff'
  10096. }
  10097. }
  10098.  
  10099. terminatеReason = I18N('UNKNOWN');
  10100. callAdventureInfo = {
  10101. name: "adventure_getInfo",
  10102. args: {},
  10103. ident: "adventure_getInfo"
  10104. }
  10105. callTeamGetAll = {
  10106. name: "teamGetAll",
  10107. args: {},
  10108. ident: "teamGetAll"
  10109. }
  10110. callTeamGetFavor = {
  10111. name: "teamGetFavor",
  10112. args: {},
  10113. ident: "teamGetFavor"
  10114. }
  10115. callStartBattle = {
  10116. name: "adventure_turnStartBattle",
  10117. args: {},
  10118. ident: "body"
  10119. }
  10120. callEndBattle = {
  10121. name: "adventure_endBattle",
  10122. args: {
  10123. result: {},
  10124. progress: {},
  10125. },
  10126. ident: "body"
  10127. }
  10128. callCollectBuff = {
  10129. name: "adventure_turnCollectBuff",
  10130. args: {},
  10131. ident: "body"
  10132. }
  10133.  
  10134. constructor(resolve, reject) {
  10135. this.resolve = resolve;
  10136. this.reject = reject;
  10137. }
  10138.  
  10139. async start(type) {
  10140. this.type = type || this.type;
  10141. this.callAdventureInfo.name = this.actions[this.type].getInfo;
  10142. const data = await Send(JSON.stringify({
  10143. calls: [
  10144. this.callAdventureInfo,
  10145. this.callTeamGetAll,
  10146. this.callTeamGetFavor
  10147. ]
  10148. }));
  10149. return this.checkAdventureInfo(data.results);
  10150. }
  10151.  
  10152. async getPath() {
  10153. const oldVal = getSaveVal('adventurePath', '');
  10154. const keyPath = `adventurePath:${this.mapIdent}`;
  10155. const answer = await popup.confirm(I18N('ENTER_THE_PATH'), [
  10156. {
  10157. msg: I18N('START_ADVENTURE'),
  10158. placeholder: '1,2,3,4,5,6',
  10159. isInput: true,
  10160. default: getSaveVal(keyPath, oldVal)
  10161. },
  10162. {
  10163. msg: I18N('BTN_CANCEL'),
  10164. result: false,
  10165. isCancel: true
  10166. },
  10167. ]);
  10168. if (!answer) {
  10169. this.terminatеReason = I18N('BTN_CANCELED');
  10170. return false;
  10171. }
  10172.  
  10173. let path = answer.split(',');
  10174. if (path.length < 2) {
  10175. path = answer.split('-');
  10176. }
  10177. if (path.length < 2) {
  10178. this.terminatеReason = I18N('MUST_TWO_POINTS');
  10179. return false;
  10180. }
  10181.  
  10182. for (let p in path) {
  10183. path[p] = +path[p].trim()
  10184. if (Number.isNaN(path[p])) {
  10185. this.terminatеReason = I18N('MUST_ONLY_NUMBERS');
  10186. return false;
  10187. }
  10188. }
  10189.  
  10190. if (!this.checkPath(path)) {
  10191. return false;
  10192. }
  10193. setSaveVal(keyPath, answer);
  10194. return path;
  10195. }
  10196.  
  10197. checkPath(path) {
  10198. for (let i = 0; i < path.length - 1; i++) {
  10199. const currentPoint = path[i];
  10200. const nextPoint = path[i + 1];
  10201.  
  10202. const isValidPath = this.paths.some(p =>
  10203. (p.from_id === currentPoint && p.to_id === nextPoint) ||
  10204. (p.from_id === nextPoint && p.to_id === currentPoint)
  10205. );
  10206.  
  10207. if (!isValidPath) {
  10208. this.terminatеReason = I18N('INCORRECT_WAY', {
  10209. from: currentPoint,
  10210. to: nextPoint,
  10211. });
  10212. return false;
  10213. }
  10214. }
  10215.  
  10216. return true;
  10217. }
  10218.  
  10219. async checkAdventureInfo(data) {
  10220. this.advInfo = data[0].result.response;
  10221. if (!this.advInfo) {
  10222. this.terminatеReason = I18N('NOT_ON_AN_ADVENTURE') ;
  10223. return this.end();
  10224. }
  10225. const heroesTeam = data[1].result.response.adventure_hero;
  10226. const favor = data[2]?.result.response.adventure_hero;
  10227. const heroes = heroesTeam.slice(0, 5);
  10228. const pet = heroesTeam[5];
  10229. this.args = {
  10230. pet,
  10231. heroes,
  10232. favor,
  10233. path: [],
  10234. broadcast: false
  10235. }
  10236. const advUserInfo = this.advInfo.users[userInfo.id];
  10237. this.turnsLeft = advUserInfo.turnsLeft;
  10238. this.currentNode = advUserInfo.currentNode;
  10239. this.nodes = this.advInfo.nodes;
  10240. this.paths = this.advInfo.paths;
  10241. this.mapIdent = this.advInfo.mapIdent;
  10242.  
  10243. this.path = await this.getPath();
  10244. if (!this.path) {
  10245. return this.end();
  10246. }
  10247.  
  10248. if (this.currentNode == 1 && this.path[0] != 1) {
  10249. this.path.unshift(1);
  10250. }
  10251.  
  10252. return this.loop();
  10253. }
  10254.  
  10255. async loop() {
  10256. const position = this.path.indexOf(+this.currentNode);
  10257. if (!(~position)) {
  10258. this.terminatеReason = I18N('YOU_IN_NOT_ON_THE_WAY');
  10259. return this.end();
  10260. }
  10261. this.path = this.path.slice(position);
  10262. if ((this.path.length - 1) > this.turnsLeft &&
  10263. await popup.confirm(I18N('ATTEMPTS_NOT_ENOUGH'), [
  10264. { msg: I18N('YES_CONTINUE'), result: false },
  10265. { msg: I18N('BTN_NO'), result: true },
  10266. ])) {
  10267. this.terminatеReason = I18N('NOT_ENOUGH_AP');
  10268. return this.end();
  10269. }
  10270. const toPath = [];
  10271. for (const nodeId of this.path) {
  10272. if (!this.turnsLeft) {
  10273. this.terminatеReason = I18N('ATTEMPTS_ARE_OVER');
  10274. return this.end();
  10275. }
  10276. toPath.push(nodeId);
  10277. console.log(toPath);
  10278. if (toPath.length > 1) {
  10279. setProgress(toPath.join(' > ') + ` ${I18N('MOVES')}: ` + this.turnsLeft);
  10280. }
  10281. if (nodeId == this.currentNode) {
  10282. continue;
  10283. }
  10284.  
  10285. const nodeInfo = this.getNodeInfo(nodeId);
  10286. if (nodeInfo.type == 'TYPE_COMBAT') {
  10287. if (nodeInfo.state == 'empty') {
  10288. this.turnsLeft--;
  10289. continue;
  10290. }
  10291.  
  10292. /**
  10293. * Disable regular battle cancellation
  10294. *
  10295. * Отключаем штатную отменую боя
  10296. */
  10297. isCancalBattle = false;
  10298. if (await this.battle(toPath)) {
  10299. this.turnsLeft--;
  10300. toPath.splice(0, toPath.indexOf(nodeId));
  10301. nodeInfo.state = 'empty';
  10302. isCancalBattle = true;
  10303. continue;
  10304. }
  10305. isCancalBattle = true;
  10306. return this.end()
  10307. }
  10308.  
  10309. if (nodeInfo.type == 'TYPE_PLAYERBUFF') {
  10310. const buff = this.checkBuff(nodeInfo);
  10311. if (buff == null) {
  10312. continue;
  10313. }
  10314.  
  10315. if (await this.collectBuff(buff, toPath)) {
  10316. this.turnsLeft--;
  10317. toPath.splice(0, toPath.indexOf(nodeId));
  10318. continue;
  10319. }
  10320. this.terminatеReason = I18N('BUFF_GET_ERROR');
  10321. return this.end();
  10322. }
  10323. }
  10324. this.terminatеReason = I18N('SUCCESS');
  10325. return this.end();
  10326. }
  10327.  
  10328. /**
  10329. * Carrying out a fight
  10330. *
  10331. * Проведение боя
  10332. */
  10333. async battle(path, preCalc = true) {
  10334. const data = await this.startBattle(path);
  10335. try {
  10336. const battle = data.results[0].result.response.battle;
  10337. const result = await Calc(battle);
  10338. if (result.result.win) {
  10339. const info = await this.endBattle(result);
  10340. if (info.results[0].result.response?.error) {
  10341. this.terminatеReason = I18N('BATTLE_END_ERROR');
  10342. return false;
  10343. }
  10344. } else {
  10345. await this.cancelBattle(result);
  10346.  
  10347. if (preCalc && await this.preCalcBattle(battle)) {
  10348. path = path.slice(-2);
  10349. for (let i = 1; i <= getInput('countAutoBattle'); i++) {
  10350. setProgress(`${I18N('AUTOBOT')}: ${i}/${getInput('countAutoBattle')}`);
  10351. const result = await this.battle(path, false);
  10352. if (result) {
  10353. setProgress(I18N('VICTORY'));
  10354. return true;
  10355. }
  10356. }
  10357. this.terminatеReason = I18N('FAILED_TO_WIN_AUTO');
  10358. return false;
  10359. }
  10360. return false;
  10361. }
  10362. } catch (error) {
  10363. console.error(error);
  10364. if (await popup.confirm(I18N('ERROR_OF_THE_BATTLE_COPY'), [
  10365. { msg: I18N('BTN_NO'), result: false },
  10366. { msg: I18N('BTN_YES'), result: true },
  10367. ])) {
  10368. this.errorHandling(error, data);
  10369. }
  10370. this.terminatеReason = I18N('ERROR_DURING_THE_BATTLE');
  10371. return false;
  10372. }
  10373. return true;
  10374. }
  10375.  
  10376. /**
  10377. * Recalculate battles
  10378. *
  10379. * Прерасчтет битвы
  10380. */
  10381. async preCalcBattle(battle) {
  10382. const countTestBattle = getInput('countTestBattle');
  10383. for (let i = 0; i < countTestBattle; i++) {
  10384. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  10385. const result = await Calc(battle);
  10386. if (result.result.win) {
  10387. console.log(i, countTestBattle);
  10388. return true;
  10389. }
  10390. }
  10391. this.terminatеReason = I18N('NO_CHANCE_WIN') + countTestBattle;
  10392. return false;
  10393. }
  10394.  
  10395. /**
  10396. * Starts a fight
  10397. *
  10398. * Начинает бой
  10399. */
  10400. startBattle(path) {
  10401. this.args.path = path;
  10402. this.callStartBattle.name = this.actions[this.type].startBattle;
  10403. this.callStartBattle.args = this.args
  10404. const calls = [this.callStartBattle];
  10405. return Send(JSON.stringify({ calls }));
  10406. }
  10407.  
  10408. cancelBattle(battle) {
  10409. const fixBattle = function (heroes) {
  10410. for (const ids in heroes) {
  10411. const hero = heroes[ids];
  10412. hero.energy = random(1, 999);
  10413. if (hero.hp > 0) {
  10414. hero.hp = random(1, hero.hp);
  10415. }
  10416. }
  10417. }
  10418. fixBattle(battle.progress[0].attackers.heroes);
  10419. fixBattle(battle.progress[0].defenders.heroes);
  10420. return this.endBattle(battle);
  10421. }
  10422.  
  10423. /**
  10424. * Ends the fight
  10425. *
  10426. * Заканчивает бой
  10427. */
  10428. endBattle(battle) {
  10429. this.callEndBattle.name = this.actions[this.type].endBattle;
  10430. this.callEndBattle.args.result = battle.result
  10431. this.callEndBattle.args.progress = battle.progress
  10432. const calls = [this.callEndBattle];
  10433. return Send(JSON.stringify({ calls }));
  10434. }
  10435.  
  10436. /**
  10437. * Checks if you can get a buff
  10438. *
  10439. * Проверяет можно ли получить баф
  10440. */
  10441. checkBuff(nodeInfo) {
  10442. let id = null;
  10443. let value = 0;
  10444. for (const buffId in nodeInfo.buffs) {
  10445. const buff = nodeInfo.buffs[buffId];
  10446. if (buff.owner == null && buff.value > value) {
  10447. id = buffId;
  10448. value = buff.value;
  10449. }
  10450. }
  10451. nodeInfo.buffs[id].owner = 'Я';
  10452. return id;
  10453. }
  10454.  
  10455. /**
  10456. * Collects a buff
  10457. *
  10458. * Собирает баф
  10459. */
  10460. async collectBuff(buff, path) {
  10461. this.callCollectBuff.name = this.actions[this.type].collectBuff;
  10462. this.callCollectBuff.args = { buff, path };
  10463. const calls = [this.callCollectBuff];
  10464. return Send(JSON.stringify({ calls }));
  10465. }
  10466.  
  10467. getNodeInfo(nodeId) {
  10468. return this.nodes.find(node => node.id == nodeId);
  10469. }
  10470.  
  10471. errorHandling(error, data) {
  10472. //console.error(error);
  10473. let errorInfo = error.toString() + '\n';
  10474. try {
  10475. const errorStack = error.stack.split('\n');
  10476. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testAdventure");
  10477. errorInfo += errorStack.slice(0, endStack).join('\n');
  10478. } catch (e) {
  10479. errorInfo += error.stack;
  10480. }
  10481. if (data) {
  10482. errorInfo += '\nData: ' + JSON.stringify(data);
  10483. }
  10484. copyText(errorInfo);
  10485. }
  10486.  
  10487. end() {
  10488. isCancalBattle = true;
  10489. setProgress(this.terminatеReason, true);
  10490. console.log(this.terminatеReason);
  10491. this.resolve();
  10492. }
  10493. }
  10494.  
  10495. /**
  10496. * Passage of brawls
  10497. *
  10498. * Прохождение потасовок
  10499. */
  10500. function testBrawls() {
  10501. return new Promise((resolve, reject) => {
  10502. const brawls = new executeBrawls(resolve, reject);
  10503. brawls.start(brawlsPack);
  10504. });
  10505. }
  10506. /**
  10507. * Passage of brawls
  10508. *
  10509. * Прохождение потасовок
  10510. */
  10511. class executeBrawls {
  10512. callBrawlQuestGetInfo = {
  10513. name: "brawl_questGetInfo",
  10514. args: {},
  10515. ident: "brawl_questGetInfo"
  10516. }
  10517. callBrawlFindEnemies = {
  10518. name: "brawl_findEnemies",
  10519. args: {},
  10520. ident: "brawl_findEnemies"
  10521. }
  10522. callBrawlQuestFarm = {
  10523. name: "brawl_questFarm",
  10524. args: {},
  10525. ident: "brawl_questFarm"
  10526. }
  10527. callUserGetInfo = {
  10528. name: "userGetInfo",
  10529. args: {},
  10530. ident: "userGetInfo"
  10531. }
  10532. callTeamGetMaxUpgrade = {
  10533. name: "teamGetMaxUpgrade",
  10534. args: {},
  10535. ident: "teamGetMaxUpgrade"
  10536. }
  10537.  
  10538. stats = {
  10539. win: 0,
  10540. loss: 0,
  10541. count: 0,
  10542. }
  10543.  
  10544. stage = {
  10545. '3': 1,
  10546. '7': 2,
  10547. '12': 3,
  10548. }
  10549.  
  10550. attempts = 0;
  10551.  
  10552. constructor(resolve, reject) {
  10553. this.resolve = resolve;
  10554. this.reject = reject;
  10555. }
  10556.  
  10557. async start(args) {
  10558. this.args = args;
  10559. isCancalBattle = false;
  10560. this.brawlInfo = await this.getBrawlInfo();
  10561. this.attempts = this.brawlInfo.attempts;
  10562.  
  10563. if (!this.attempts) {
  10564. this.end(I18N('DONT_HAVE_LIVES'))
  10565. return;
  10566. }
  10567.  
  10568. while (1) {
  10569. if (!isBrawlsAutoStart) {
  10570. this.end(I18N('BTN_CANCELED'))
  10571. return;
  10572. }
  10573.  
  10574. const maxStage = this.brawlInfo.questInfo.stage;
  10575. const stage = this.stage[maxStage];
  10576. const progress = this.brawlInfo.questInfo.progress;
  10577.  
  10578. 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('LIVES')}: ${this.attempts}<br>${I18N('STOP')}`, false, function () {
  10579. isBrawlsAutoStart = false;
  10580. });
  10581.  
  10582. if (this.brawlInfo.questInfo.canFarm) {
  10583. const result = await this.questFarm();
  10584. console.log(result);
  10585. }
  10586.  
  10587. if (this.brawlInfo.questInfo.stage == 12 && this.brawlInfo.questInfo.progress == 12) {
  10588. this.end(I18N('SUCCESS'))
  10589. return;
  10590. }
  10591.  
  10592. if (!this.attempts) {
  10593. this.end(I18N('DONT_HAVE_LIVES'))
  10594. return;
  10595. }
  10596.  
  10597. const enemie = Object.values(this.brawlInfo.findEnemies).shift();
  10598.  
  10599. // Для потасовок брустара
  10600. this.args.heroes = await this.updatePack(enemie.heroes);
  10601.  
  10602. const result = await this.battle(enemie.userId);
  10603. this.brawlInfo = {
  10604. questInfo: result[1].result.response,
  10605. findEnemies: result[2].result.response,
  10606. }
  10607. }
  10608. }
  10609.  
  10610. async updatePack(enemieHeroes) {
  10611. const packs = [
  10612. [4030, 4032, 4031, 4043, 4033],
  10613. [4030, 4040, 4032, 4043, 4033],
  10614. [4030, 4032, 4043, 4042, 4033],
  10615. [4000, 4030, 4043, 4042, 4033],
  10616. [4030, 4040, 4043, 4042, 4033],
  10617. [4030, 4032, 4041, 4043, 4033],
  10618. [4030, 4040, 4031, 4043, 4033],
  10619. ];
  10620.  
  10621. for (const pack of packs) {
  10622. const attackers = this.maxUpgrade
  10623. .filter(e => pack.includes(e.id))
  10624. .reduce((obj, e) => ({ ...obj, [e.id]: e }), {});
  10625. const battle = {
  10626. attackers,
  10627. defenders: [enemieHeroes],
  10628. type: "brawl_titan",
  10629. }
  10630.  
  10631. let countWinBattles = 0;
  10632. let countTestBattle = 10;
  10633. for (let i = 0; i < countTestBattle; i++) {
  10634. battle.seed = Math.floor(Date.now() / 1000) + Math.random() * 1000;
  10635. const result = await Calc(battle);
  10636. if (result.result.win) {
  10637. countWinBattles++;
  10638. }
  10639. if (countWinBattles > 6) {
  10640. console.log(pack)
  10641. return pack;
  10642. }
  10643. }
  10644. }
  10645.  
  10646. return packs[1];
  10647. }
  10648.  
  10649. async questFarm() {
  10650. const calls = [this.callBrawlQuestFarm];
  10651. const result = await Send(JSON.stringify({ calls }));
  10652. return result.results[0].result.response;
  10653. }
  10654.  
  10655. async getBrawlInfo() {
  10656. const data = await Send(JSON.stringify({
  10657. calls: [
  10658. this.callUserGetInfo,
  10659. this.callBrawlQuestGetInfo,
  10660. this.callBrawlFindEnemies,
  10661. this.callTeamGetMaxUpgrade,
  10662. ]
  10663. }));
  10664.  
  10665. let attempts = data.results[0].result.response.refillable.find(n => n.id == 48);
  10666. this.maxUpgrade = Object.values(data.results[3].result.response.titan);
  10667. return {
  10668. attempts: attempts.amount,
  10669. questInfo: data.results[1].result.response,
  10670. findEnemies: data.results[2].result.response,
  10671. }
  10672. }
  10673.  
  10674. /**
  10675. * Carrying out a fight
  10676. *
  10677. * Проведение боя
  10678. */
  10679. async battle(userId) {
  10680. this.stats.count++;
  10681. const battle = await this.startBattle(userId, this.args);
  10682. const result = await Calc(battle);
  10683. console.log(result.result);
  10684. if (result.result.win) {
  10685. this.stats.win++;
  10686. } else {
  10687. this.stats.loss++;
  10688. this.attempts--;
  10689. }
  10690. return await this.endBattle(result);
  10691. // return await this.cancelBattle(result);
  10692. }
  10693.  
  10694. /**
  10695. * Starts a fight
  10696. *
  10697. * Начинает бой
  10698. */
  10699. async startBattle(userId, args) {
  10700. const call = {
  10701. name: "brawl_startBattle",
  10702. args,
  10703. ident: "brawl_startBattle"
  10704. }
  10705. call.args.userId = userId;
  10706. const calls = [call];
  10707. const result = await Send(JSON.stringify({ calls }));
  10708. return result.results[0].result.response;
  10709. }
  10710.  
  10711. cancelBattle(battle) {
  10712. const fixBattle = function (heroes) {
  10713. for (const ids in heroes) {
  10714. const hero = heroes[ids];
  10715. hero.energy = random(1, 999);
  10716. if (hero.hp > 0) {
  10717. hero.hp = random(1, hero.hp);
  10718. }
  10719. }
  10720. }
  10721. fixBattle(battle.progress[0].attackers.heroes);
  10722. fixBattle(battle.progress[0].defenders.heroes);
  10723. return this.endBattle(battle);
  10724. }
  10725.  
  10726. /**
  10727. * Ends the fight
  10728. *
  10729. * Заканчивает бой
  10730. */
  10731. async endBattle(battle) {
  10732. battle.progress[0].attackers.input = ['auto', 0, 0, 'auto', 0, 0];
  10733. const calls = [{
  10734. name: "brawl_endBattle",
  10735. args: {
  10736. result: battle.result,
  10737. progress: battle.progress
  10738. },
  10739. ident: "brawl_endBattle"
  10740. },
  10741. this.callBrawlQuestGetInfo,
  10742. this.callBrawlFindEnemies,
  10743. ];
  10744. const result = await Send(JSON.stringify({ calls }));
  10745. return result.results;
  10746. }
  10747.  
  10748. end(endReason) {
  10749. isCancalBattle = true;
  10750. isBrawlsAutoStart = false;
  10751. setProgress(endReason, true);
  10752. console.log(endReason);
  10753. this.resolve();
  10754. }
  10755. }
  10756.  
  10757. class executeEventAutoBoss {
  10758.  
  10759. async start() {
  10760. await this.loadInfo();
  10761. this.generateCombo();
  10762.  
  10763. const countTestBattle = +getInput('countTestBattle');
  10764. const maxCalcBattle = this.combo.length * countTestBattle;
  10765.  
  10766. const resultDialog = await popup.confirm(I18N('EVENT_AUTO_BOSS', {
  10767. length: this.combo.length,
  10768. countTestBattle,
  10769. maxCalcBattle
  10770. }), [
  10771. { msg: I18N('BEST_SLOW'), result: true },
  10772. { msg: I18N('FIRST_FAST'), result: false },
  10773. { isClose: true, result: 'exit' },
  10774. ]);
  10775.  
  10776. if (resultDialog == 'exit') {
  10777. this.end('Отменено');
  10778. return;
  10779. }
  10780.  
  10781. popup.confirm(I18N('FREEZE_INTERFACE'));
  10782.  
  10783. setTimeout(() => {
  10784. this.startFindPack(resultDialog)
  10785. }, 1000)
  10786. }
  10787.  
  10788. async loadInfo() {
  10789. const resultReq = await Send({ calls: [{ name: "teamGetMaxUpgrade", args: {}, ident: "group_1_body" }, { name: "invasion_bossStart", args: { id: 119, heroes: [3, 61], favor: { "61": 6001 } }, ident: "body" }] }).then(e => e.results);
  10790. this.heroes = resultReq[0].result.response;
  10791. this.battle = resultReq[1].result.response;
  10792.  
  10793. this.heroes.hero[61] = this.battle.attackers[1];
  10794. this.battle.attackers = [];
  10795. }
  10796.  
  10797. combinations(arr, n) {
  10798. if (n == 1) {
  10799. return arr.map(function (x) { return [x]; });
  10800. }
  10801. else if (n <= 0) {
  10802. return [];
  10803. }
  10804. var result = [];
  10805. for (var i = 0; i < arr.length; i++) {
  10806. var rest = arr.slice(i + 1);
  10807. var c = this.combinations(rest, n - 1);
  10808. for (var j = 0; j < c.length; j++) {
  10809. c[j].unshift(arr[i]);
  10810. result.push(c[j]);
  10811. }
  10812. }
  10813. return result;
  10814. }
  10815.  
  10816. generateCombo() {
  10817. // const heroesIds = [3, 7, 8, 9, 12, 16, 18, 22, 35, 40, 48, 57, 58, 59];
  10818. const heroesIds = [3, 7, 9, 12, 18, 22, 35, 40, 48, 57, 58, 59];
  10819. this.combo = this.combinations(heroesIds, 4);
  10820. }
  10821.  
  10822. async startFindPack(findBestOfAll) {
  10823. const promises = [];
  10824. let bestBattle = null;
  10825. for (const comb of this.combo) {
  10826. const copyBattle = structuredClone(this.battle);
  10827. const attackers = [];
  10828. for (const id of comb) {
  10829. if (this.heroes.hero[id]) {
  10830. attackers.push(this.heroes.hero[id]);
  10831. }
  10832. }
  10833. attackers.push(this.heroes.hero[61]);
  10834. attackers.push(this.heroes.pet[6001]);
  10835. copyBattle.attackers = attackers;
  10836. const countTestBattle = +getInput('countTestBattle');
  10837. if (findBestOfAll) {
  10838. promises.push(this.CalcBattle(copyBattle, countTestBattle));
  10839. } else {
  10840. try {
  10841. const checkBattle = await this.CalcBattle(copyBattle, countTestBattle);
  10842. if (checkBattle.result.win) {
  10843. bestBattle = checkBattle;
  10844. break;
  10845. }
  10846. } catch(e) {
  10847. console.log(e, copyBattle)
  10848. popup.confirm(I18N('ERROR_F12'));
  10849. this.end(I18N('ERROR_F12'), e, copyBattle)
  10850. return;
  10851. }
  10852. }
  10853. }
  10854.  
  10855. if (findBestOfAll) {
  10856. bestBattle = await Promise.all(promises)
  10857. .then(results => {
  10858. results = results.sort((a, b) => b.coeff - a.coeff).slice(0, 10);
  10859. let maxStars = 0;
  10860. let maxCoeff = -100;
  10861. let maxBattle = null;
  10862. results.forEach(e => {
  10863. if (e.stars > maxStars || e.coeff > maxCoeff) {
  10864. maxCoeff = e.coeff;
  10865. maxStars = e.stars;
  10866. maxBattle = e;
  10867. }
  10868. });
  10869. console.log(results);
  10870. console.log('better', maxCoeff, maxStars, maxBattle, maxBattle.battleData.attackers.map(e => e.id));
  10871. return maxBattle;
  10872. });
  10873. }
  10874.  
  10875. if (!bestBattle || !bestBattle.result.win) {
  10876. let msg = I18N('FAILED_FIND_WIN_PACK');
  10877. let msgc = msg;
  10878. if (bestBattle?.battleData) {
  10879. const heroes = bestBattle.battleData.attackers.map(e => e.id).filter(e => e < 61);
  10880. msg += `</br>${I18N('BEST_PACK')}</br>` + heroes.map(
  10881. id => `<img src="https://heroesweb-a.akamaihd.net/vk/v0952/assets/hero_icons/${('000' + id).slice(-4)}.png"/>`
  10882. ).join('');
  10883. msgc += I18N('BEST_PACK') + heroes.join(',')
  10884. }
  10885.  
  10886. await popup.confirm(msg);
  10887. this.end(msgc);
  10888. return;
  10889. }
  10890.  
  10891. this.heroesPack = bestBattle.battleData.attackers.map(e => e.id).filter(e => e < 6000);
  10892. this.battleLoop();
  10893. }
  10894.  
  10895. async battleLoop() {
  10896. let repeat = false;
  10897. do {
  10898. repeat = false;
  10899. const countAutoBattle = +getInput('countAutoBattle');
  10900. for (let i = 1; i <= countAutoBattle; i++) {
  10901. const startBattle = await Send({
  10902. calls: [{
  10903. name: "invasion_bossStart",
  10904. args: {
  10905. id: 119,
  10906. heroes: this.heroesPack,
  10907. favor: { "61": 6001 },
  10908. pet: 6001
  10909. }, ident: "body"
  10910. }]
  10911. }).then(e => e.results[0].result.response);
  10912. const calcBattle = await Calc(startBattle);
  10913.  
  10914. setProgress(`${i}) ${calcBattle.result.win ? I18N('VICTORY') : I18N('DEFEAT') } `)
  10915. console.log(i, calcBattle.result.win)
  10916. if (!calcBattle.result.win) {
  10917. continue;
  10918. }
  10919.  
  10920. const endBattle = await Send({
  10921. calls: [{
  10922. name: "invasion_bossEnd",
  10923. args: {
  10924. id: 119,
  10925. result: calcBattle.result,
  10926. progress: calcBattle.progress
  10927. }, ident: "body"
  10928. }]
  10929. }).then(e => e.results[0].result.response);
  10930. console.log(endBattle);
  10931. const msg = I18N('BOSS_HAS_BEEN_DEF', { bossLvl: this.battle.typeId });
  10932. await popup.confirm(msg);
  10933. this.end(msg);
  10934. return;
  10935. }
  10936.  
  10937. const msg = I18N('NOT_ENOUGH_ATTEMPTS_BOSS', { bossLvl: this.battle.typeId });
  10938. repeat = await popup.confirm(msg, [
  10939. { msg: 'Да', result: true },
  10940. { msg: 'Нет', result: false },
  10941. ]);
  10942. this.end(I18N('NOT_ENOUGH_ATTEMPTS_BOSS', { bossLvl: this.battle.typeId }));
  10943.  
  10944. } while (repeat)
  10945. }
  10946.  
  10947. calcCoeff(result, packType) {
  10948. let beforeSumFactor = 0;
  10949. const beforePack = result.battleData[packType][0];
  10950. for (let heroId in beforePack) {
  10951. const hero = beforePack[heroId];
  10952. const state = hero.state;
  10953. let factor = 1;
  10954. if (state) {
  10955. const hp = state.hp / state.maxHp;
  10956. factor = hp;
  10957. }
  10958. beforeSumFactor += factor;
  10959. }
  10960.  
  10961. let afterSumFactor = 0;
  10962. const afterPack = result.progress[0][packType].heroes;
  10963. for (let heroId in afterPack) {
  10964. const hero = afterPack[heroId];
  10965. const stateHp = beforePack[heroId]?.state?.hp || beforePack[heroId]?.stats?.hp;
  10966. const hp = hero.hp / stateHp;
  10967. afterSumFactor += hp;
  10968. }
  10969. const resultCoeff = beforeSumFactor / afterSumFactor;
  10970. return resultCoeff;
  10971. }
  10972.  
  10973. async CalcBattle(battle, count) {
  10974. const actions = [];
  10975. for (let i = 0; i < count; i++) {
  10976. battle.seed = Math.floor(Date.now() / 1000) + this.random(0, 1e3);
  10977. actions.push(Calc(battle).then(e => {
  10978. e.coeff = this.calcCoeff(e, 'defenders');
  10979. return e;
  10980. }));
  10981. }
  10982.  
  10983. return Promise.all(actions).then(results => {
  10984. let maxCoeff = -100;
  10985. let maxBattle = null;
  10986. results.forEach(e => {
  10987. if (e.coeff > maxCoeff) {
  10988. maxCoeff = e.coeff;
  10989. maxBattle = e;
  10990. }
  10991. });
  10992. maxBattle.stars = results.reduce((w, s) => w + s.result.stars, 0);
  10993. maxBattle.attempts = results;
  10994. return maxBattle;
  10995. });
  10996. }
  10997.  
  10998. random(min, max) {
  10999. return Math.floor(Math.random() * (max - min + 1) + min);
  11000. }
  11001.  
  11002. end(reason) {
  11003. setProgress('');
  11004. console.log('endEventAutoBoss', reason)
  11005. }
  11006. }
  11007.  
  11008. })();
  11009.  
  11010. /**
  11011. * TODO:
  11012. * Получение всех уровней при сборе всех наград (квест на титанит и на энку) +-
  11013. * Добивание на арене титанов
  11014. * Закрытие окошек по Esc +-
  11015. * Починить работу скрипта на уровне команды ниже 10 +-
  11016. * Написать номальную синхронизацию
  11017. * Добавить дополнительные настройки автопокупки в "Тайном богатстве"
  11018. */