HeroWarsHelper

Automation of actions for the game Hero Wars

目前为 2024-05-29 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name HeroWarsHelper
  3. // @name:en HeroWarsHelper
  4. // @name:ru HeroWarsHelper
  5. // @namespace HeroWarsHelper
  6. // @version 2.249
  7. // @description Automation of actions for the game Hero Wars
  8. // @description:en Automation of actions for the game Hero Wars
  9. // @description:ru Автоматизация действий для игры Хроники Хаоса
  10. // @author ZingerY
  11. // @license Copyright ZingerY
  12. // @homepage https://zingery.ru/scripts/HeroWarsHelper.user.js
  13. // @icon http://ilovemycomp.narod.ru/VaultBoyIco16.ico
  14. // @icon64 http://ilovemycomp.narod.ru/VaultBoyIco64.png
  15. // @match https://www.hero-wars.com/*
  16. // @match https://apps-1701433570146040.apps.fbsbx.com/*
  17. // @run-at document-start
  18. // ==/UserScript==
  19.  
  20. (function() {
  21. /**
  22. * Start script
  23. *
  24. * Стартуем скрипт
  25. */
  26. console.log('%cStart ' + GM_info.script.name + ', v' + GM_info.script.version, 'color: red');
  27. /**
  28. * Script info
  29. *
  30. * Информация о скрипте
  31. */
  32. const scriptInfo = (({name, version, author, homepage, lastModified}, updateUrl, source) =>
  33. ({name, version, author, homepage, lastModified, updateUrl, source}))
  34. (GM_info.script, GM_info.scriptUpdateURL, arguments.callee.toString());
  35. /**
  36. * Information for completing daily quests
  37. *
  38. * Информация для выполнения ежендевных квестов
  39. */
  40. const questsInfo = {};
  41. /**
  42. * Is the game data loaded
  43. *
  44. * Загружены ли данные игры
  45. */
  46. let isLoadGame = false;
  47. /**
  48. * Headers of the last request
  49. *
  50. * Заголовки последнего запроса
  51. */
  52. let lastHeaders = {};
  53. /**
  54. * Information about sent gifts
  55. *
  56. * Информация об отправленных подарках
  57. */
  58. let freebieCheckInfo = null;
  59. /**
  60. * missionTimer
  61. *
  62. * missionTimer
  63. */
  64. let missionBattle = null;
  65. /**
  66. * User data
  67. *
  68. * Данные пользователя
  69. */
  70. let userInfo;
  71. /**
  72. * Original methods for working with AJAX
  73. *
  74. * Оригинальные методы для работы с AJAX
  75. */
  76. const original = {
  77. open: XMLHttpRequest.prototype.open,
  78. send: XMLHttpRequest.prototype.send,
  79. setRequestHeader: XMLHttpRequest.prototype.setRequestHeader,
  80. SendWebSocket: WebSocket.prototype.send,
  81. };
  82. /**
  83. * Decoder for converting byte data to JSON string
  84. *
  85. * Декодер для перобразования байтовых данных в JSON строку
  86. */
  87. const decoder = new TextDecoder("utf-8");
  88. /**
  89. * Stores a history of requests
  90. *
  91. * Хранит историю запросов
  92. */
  93. let requestHistory = {};
  94. /**
  95. * URL for API requests
  96. *
  97. * URL для запросов к API
  98. */
  99. let apiUrl = '';
  100.  
  101. /**
  102. * Connecting to the game code
  103. *
  104. * Подключение к коду игры
  105. */
  106. this.cheats = new hackGame();
  107. /**
  108. * The function of calculating the results of the battle
  109. *
  110. * Функция расчета результатов боя
  111. */
  112. this.BattleCalc = cheats.BattleCalc;
  113. /**
  114. * Sending a request available through the console
  115. *
  116. * Отправка запроса доступная через консоль
  117. */
  118. this.SendRequest = send;
  119. /**
  120. * Simple combat calculation available through the console
  121. *
  122. * Простой расчет боя доступный через консоль
  123. */
  124. this.Calc = function (data) {
  125. const type = getBattleType(data?.type);
  126. return new Promise((resolve, reject) => {
  127. try {
  128. BattleCalc(data, type, resolve);
  129. } catch (e) {
  130. reject(e);
  131. }
  132. })
  133. }
  134. /**
  135. * Short asynchronous request
  136. * Usage example (returns information about a character):
  137. * const userInfo = await Send('{"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}')
  138. *
  139. * Короткий асинхронный запрос
  140. * Пример использования (возвращает информацию о персонаже):
  141. * const userInfo = await Send('{"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}')
  142. */
  143. this.Send = function (json, pr) {
  144. return new Promise((resolve, reject) => {
  145. try {
  146. send(json, resolve, pr);
  147. } catch (e) {
  148. reject(e);
  149. }
  150. })
  151. }
  152.  
  153. this.xyz = (({ name, version, author }) => ({ name, version, author }))(GM_info.script);
  154. const i18nLangData = {
  155. /* English translation by BaBa */
  156. en: {
  157. /* Checkboxes */
  158. SKIP_FIGHTS: 'Skip battle',
  159. SKIP_FIGHTS_TITLE: 'Skip battle in Outland and the arena of the titans, auto-pass in the tower and campaign',
  160. ENDLESS_CARDS: 'Infinite cards',
  161. ENDLESS_CARDS_TITLE: 'Disable Divination Cards wasting',
  162. AUTO_EXPEDITION: 'Auto Expedition',
  163. AUTO_EXPEDITION_TITLE: 'Auto-sending expeditions',
  164. CANCEL_FIGHT: 'Cancel battle',
  165. CANCEL_FIGHT_TITLE: 'Ability to cancel manual combat on GW, CoW and Asgard',
  166. GIFTS: 'Gifts',
  167. GIFTS_TITLE: 'Collect gifts automatically',
  168. BATTLE_RECALCULATION: 'Battle recalculation',
  169. BATTLE_RECALCULATION_TITLE: 'Preliminary calculation of the battle',
  170. QUANTITY_CONTROL: 'Quantity control',
  171. QUANTITY_CONTROL_TITLE: 'Ability to specify the number of opened "lootboxes"',
  172. REPEAT_CAMPAIGN: 'Repeat missions',
  173. REPEAT_CAMPAIGN_TITLE: 'Auto-repeat battles in the campaign',
  174. DISABLE_DONAT: 'Disable donation',
  175. DISABLE_DONAT_TITLE: 'Removes all donation offers',
  176. DAILY_QUESTS: 'Quests',
  177. DAILY_QUESTS_TITLE: 'Complete daily quests',
  178. AUTO_QUIZ: 'AutoQuiz',
  179. AUTO_QUIZ_TITLE: 'Automatically receive correct answers to quiz questions',
  180. SECRET_WEALTH_CHECKBOX: 'Automatic purchase in the store "Secret Wealth" when entering the game',
  181. HIDE_SERVERS: 'Collapse servers',
  182. HIDE_SERVERS_TITLE: 'Hide unused servers',
  183. /* Input fields */
  184. HOW_MUCH_TITANITE: 'How much titanite to farm',
  185. COMBAT_SPEED: 'Combat Speed Multiplier',
  186. NUMBER_OF_TEST: 'Number of test fights',
  187. NUMBER_OF_AUTO_BATTLE: 'Number of auto-battle attempts',
  188. /* Buttons */
  189. RUN_SCRIPT: 'Run the',
  190. TO_DO_EVERYTHING: 'Do All',
  191. TO_DO_EVERYTHING_TITLE: 'Perform multiple actions of your choice',
  192. OUTLAND: 'Outland',
  193. OUTLAND_TITLE: 'Collect Outland',
  194. TITAN_ARENA: 'ToE',
  195. TITAN_ARENA_TITLE: 'Complete the titan arena',
  196. DUNGEON: 'Dungeon',
  197. DUNGEON_TITLE: 'Go through the dungeon',
  198. SEER: 'Seer',
  199. SEER_TITLE: 'Roll the Seer',
  200. TOWER: 'Tower',
  201. TOWER_TITLE: 'Pass the tower',
  202. EXPEDITIONS: 'Expeditions',
  203. EXPEDITIONS_TITLE: 'Sending and collecting expeditions',
  204. SYNC: 'Sync',
  205. SYNC_TITLE: 'Partial synchronization of game data without reloading the page',
  206. ARCHDEMON: 'Archdemon',
  207. ARCHDEMON_TITLE: 'Hitting kills and collecting rewards',
  208. ESTER_EGGS: 'Easter eggs',
  209. ESTER_EGGS_TITLE: 'Collect all Easter eggs or rewards',
  210. REWARDS: 'Rewards',
  211. REWARDS_TITLE: 'Collect all quest rewards',
  212. MAIL: 'Mail',
  213. MAIL_TITLE: 'Collect all mail, except letters with energy and charges of the portal',
  214. MINIONS: 'Minions',
  215. MINIONS_TITLE: 'Attack minions with saved packs',
  216. ADVENTURE: 'Adventure',
  217. ADVENTURE_TITLE: 'Passes the adventure along the specified route',
  218. STORM: 'Storm',
  219. STORM_TITLE: 'Passes the Storm along the specified route',
  220. SANCTUARY: 'Sanctuary',
  221. SANCTUARY_TITLE: 'Fast travel to Sanctuary',
  222. GUILD_WAR: 'Guild War',
  223. GUILD_WAR_TITLE: 'Fast travel to Guild War',
  224. SECRET_WEALTH: 'Secret Wealth',
  225. SECRET_WEALTH_TITLE: 'Buy something in the store "Secret Wealth"',
  226. /* Misc */
  227. BOTTOM_URLS:
  228. '<a href="https://t.me/+0oMwICyV1aQ1MDAy" target="_blank" title="Telegram"><svg width="20" height="20" style="margin:2px" viewBox="0 0 1e3 1e3" xmlns="http://www.w3.org/2000/svg"><defs><linearGradient id="a" x1="50%" x2="50%" y2="99.258%"><stop stop-color="#2AABEE" offset="0"/><stop stop-color="#229ED9" offset="1"/></linearGradient></defs><g fill-rule="evenodd"><circle cx="500" cy="500" r="500" fill="url(#a)"/><path d="m226.33 494.72c145.76-63.505 242.96-105.37 291.59-125.6 138.86-57.755 167.71-67.787 186.51-68.119 4.1362-0.072862 13.384 0.95221 19.375 5.8132 5.0584 4.1045 6.4501 9.6491 7.1161 13.541 0.666 3.8915 1.4953 12.756 0.83608 19.683-7.5246 79.062-40.084 270.92-56.648 359.47-7.0089 37.469-20.81 50.032-34.17 51.262-29.036 2.6719-51.085-19.189-79.207-37.624-44.007-28.847-68.867-46.804-111.58-74.953-49.366-32.531-17.364-50.411 10.769-79.631 7.3626-7.6471 135.3-124.01 137.77-134.57 0.30968-1.3202 0.59708-6.2414-2.3265-8.8399s-7.2385-1.7099-10.352-1.0032c-4.4137 1.0017-74.715 47.468-210.9 139.4-19.955 13.702-38.029 20.379-54.223 20.029-17.853-0.3857-52.194-10.094-77.723-18.393-31.313-10.178-56.199-15.56-54.032-32.846 1.1287-9.0037 13.528-18.212 37.197-27.624z" fill="#fff"/></g></svg></a>',
  229. GIFTS_SENT: 'Gifts sent!',
  230. DO_YOU_WANT: 'Do you really want to do this?',
  231. BTN_RUN: 'Run',
  232. BTN_CANCEL: 'Cancel',
  233. BTN_OK: 'OK',
  234. MSG_HAVE_BEEN_DEFEATED: 'You have been defeated!',
  235. BTN_AUTO: 'Auto',
  236. MSG_YOU_APPLIED: 'You applied',
  237. MSG_DAMAGE: 'damage',
  238. MSG_CANCEL_AND_STAT: 'Auto (F5) and show statistic',
  239. MSG_REPEAT_MISSION: 'Repeat the mission?',
  240. BTN_REPEAT: 'Repeat',
  241. BTN_NO: 'No',
  242. MSG_SPECIFY_QUANT: 'Specify Quantity:',
  243. BTN_OPEN: 'Open',
  244. QUESTION_COPY: 'Question copied to clipboard',
  245. ANSWER_KNOWN: 'The answer is known',
  246. ANSWER_NOT_KNOWN: 'ATTENTION THE ANSWER IS NOT KNOWN',
  247. BEING_RECALC: 'The battle is being recalculated',
  248. THIS_TIME: 'This time',
  249. VICTORY: '<span style="color:green;">VICTORY</span>',
  250. DEFEAT: '<span style="color:red;">DEFEAT</span>',
  251. CHANCE_TO_WIN: 'Chance to win <span style="color: red;">based on pre-calculation</span>',
  252. OPEN_DOLLS: 'nesting dolls recursively',
  253. SENT_QUESTION: 'Question sent',
  254. SETTINGS: 'Settings',
  255. MSG_BAN_ATTENTION: '<p style="color:red;">Using this feature may result in a ban.</p> Continue?',
  256. BTN_YES_I_AGREE: 'Yes, I understand the risks!',
  257. BTN_NO_I_AM_AGAINST: 'No, I refuse it!',
  258. VALUES: 'Values',
  259. EXPEDITIONS_SENT: 'Expeditions:<br>Collected: {countGet}<br>Sent: {countSend}',
  260. EXPEDITIONS_NOTHING: 'Nothing to collect/send',
  261. TITANIT: 'Titanit',
  262. COMPLETED: 'completed',
  263. FLOOR: 'Floor',
  264. LEVEL: 'Level',
  265. BATTLES: 'battles',
  266. EVENT: 'Event',
  267. NOT_AVAILABLE: 'not available',
  268. NO_HEROES: 'No heroes',
  269. DAMAGE_AMOUNT: 'Damage amount',
  270. NOTHING_TO_COLLECT: 'Nothing to collect',
  271. COLLECTED: 'Collected',
  272. REWARD: 'rewards',
  273. REMAINING_ATTEMPTS: 'Remaining attempts',
  274. BATTLES_CANCELED: 'Battles canceled',
  275. MINION_RAID: 'Minion Raid',
  276. STOPPED: 'Stopped',
  277. REPETITIONS: 'Repetitions',
  278. MISSIONS_PASSED: 'Missions passed',
  279. STOP: 'stop',
  280. TOTAL_OPEN: 'Total open',
  281. OPEN: 'Open',
  282. ROUND_STAT: 'Damage statistics for ',
  283. BATTLE: 'battles',
  284. MINIMUM: 'Minimum',
  285. MAXIMUM: 'Maximum',
  286. AVERAGE: 'Average',
  287. NOT_THIS_TIME: 'Not this time',
  288. RETRY_LIMIT_EXCEEDED: 'Retry limit exceeded',
  289. SUCCESS: 'Success',
  290. RECEIVED: 'Received',
  291. LETTERS: 'letters',
  292. PORTALS: 'portals',
  293. ATTEMPTS: 'attempts',
  294. /* Quests */
  295. QUEST_10001: 'Upgrade the skills of heroes 3 times',
  296. QUEST_10002: 'Complete 10 missions',
  297. QUEST_10003: 'Complete 3 heroic missions',
  298. QUEST_10004: 'Fight 3 times in the Arena or Grand Arena',
  299. QUEST_10006: 'Use the exchange of emeralds 1 time',
  300. QUEST_10007: 'Perform 1 summon in the Solu Atrium',
  301. QUEST_10016: 'Send gifts to guildmates',
  302. QUEST_10018: 'Use an experience potion',
  303. QUEST_10019: 'Open 1 chest in the Tower',
  304. QUEST_10020: 'Open 3 chests in Outland',
  305. QUEST_10021: 'Collect 75 Titanite in the Guild Dungeon',
  306. QUEST_10021: 'Collect 150 Titanite in the Guild Dungeon',
  307. QUEST_10023: 'Upgrade Gift of the Elements by 1 level',
  308. QUEST_10024: 'Level up any artifact once',
  309. QUEST_10025: 'Start Expedition 1',
  310. QUEST_10026: 'Start 4 Expeditions',
  311. QUEST_10027: 'Win 1 battle of the Tournament of Elements',
  312. QUEST_10028: 'Level up any titan artifact',
  313. QUEST_10029: 'Unlock the Orb of Titan Artifacts',
  314. QUEST_10030: 'Upgrade any Skin of any hero 1 time',
  315. QUEST_10031: 'Win 6 battles of the Tournament of Elements',
  316. QUEST_10043: 'Start or Join an Adventure',
  317. QUEST_10044: 'Use Summon Pets 1 time',
  318. QUEST_10046: 'Open 3 chests in Adventure',
  319. QUEST_10047: 'Get 150 Guild Activity Points',
  320. NOTHING_TO_DO: 'Nothing to do',
  321. YOU_CAN_COMPLETE: 'You can complete quests',
  322. BTN_DO_IT: 'Do it',
  323. NOT_QUEST_COMPLETED: 'Not a single quest completed',
  324. COMPLETED_QUESTS: 'Completed quests',
  325. /* everything button */
  326. ASSEMBLE_OUTLAND: 'Assemble Outland',
  327. PASS_THE_TOWER: 'Pass the tower',
  328. CHECK_EXPEDITIONS: 'Check Expeditions',
  329. COMPLETE_TOE: 'Complete ToE',
  330. COMPLETE_DUNGEON: 'Complete the dungeon',
  331. COLLECT_MAIL: 'Collect mail',
  332. COLLECT_MISC: 'Collect some bullshit',
  333. COLLECT_MISC_TITLE: 'Collect Easter Eggs, Skin Gems, Keys, Arena Coins and Soul Crystal',
  334. COLLECT_QUEST_REWARDS: 'Collect quest rewards',
  335. MAKE_A_SYNC: 'Make a sync',
  336.  
  337. RUN_FUNCTION: 'Run the following functions?',
  338. BTN_GO: 'Go!',
  339. PERFORMED: 'Performed',
  340. DONE: 'Done',
  341. ERRORS_OCCURRES: 'Errors occurred while executing',
  342. COPY_ERROR: 'Copy error information to clipboard',
  343. BTN_YES: 'Yes',
  344. ALL_TASK_COMPLETED: 'All tasks completed',
  345.  
  346. UNKNOWN: 'unknown',
  347. ENTER_THE_PATH: 'Enter the path of adventure using commas or dashes',
  348. START_ADVENTURE: 'Start your adventure along this path!',
  349. INCORRECT_WAY: 'Incorrect path in adventure: {from} -> {to}',
  350. BTN_CANCELED: 'Canceled',
  351. MUST_TWO_POINTS: 'The path must contain at least 2 points.',
  352. MUST_ONLY_NUMBERS: 'The path must contain only numbers and commas',
  353. NOT_ON_AN_ADVENTURE: 'You are not on an adventure',
  354. YOU_IN_NOT_ON_THE_WAY: 'Your location is not on the way',
  355. ATTEMPTS_NOT_ENOUGH: 'Your attempts are not enough to complete the path, continue?',
  356. YES_CONTINUE: 'Yes, continue!',
  357. NOT_ENOUGH_AP: 'Not enough action points',
  358. ATTEMPTS_ARE_OVER: 'The attempts are over',
  359. MOVES: 'Moves',
  360. BUFF_GET_ERROR: 'Buff getting error',
  361. BATTLE_END_ERROR: 'Battle end error',
  362. AUTOBOT: 'Autobot',
  363. FAILED_TO_WIN_AUTO: 'Failed to win the auto battle',
  364. ERROR_OF_THE_BATTLE_COPY: 'An error occurred during the passage of the battle<br>Copy the error to the clipboard?',
  365. ERROR_DURING_THE_BATTLE: 'Error during the battle',
  366. NO_CHANCE_WIN: 'No chance of winning this fight: 0/',
  367. LOST_HEROES: 'You have won, but you have lost one or several heroes',
  368. VICTORY_IMPOSSIBLE: 'Is victory impossible, should we focus on the result?',
  369. FIND_COEFF: 'Find the coefficient greater than',
  370. BTN_PASS: 'PASS',
  371. BRAWLS: 'Brawls',
  372. BRAWLS_TITLE: 'Activates the ability to auto-brawl',
  373. START_AUTO_BRAWLS: 'Start Auto Brawls?',
  374. LOSSES: 'Losses',
  375. WINS: 'Wins',
  376. FIGHTS: 'Fights',
  377. STAGE: 'Stage',
  378. DONT_HAVE_LIVES: "You don't have lives",
  379. LIVES: 'Lives',
  380. SECRET_WEALTH_ALREADY: 'Item for Pet Potions already purchased',
  381. SECRET_WEALTH_NOT_ENOUGH: 'Not Enough Pet Potion, You Have {available}, Need {need}',
  382. SECRET_WEALTH_UPGRADE_NEW_PET: 'After purchasing the Pet Potion, it will not be enough to upgrade a new pet',
  383. SECRET_WEALTH_PURCHASED: 'Purchased {count} {name}',
  384. SECRET_WEALTH_CANCELED: 'Secret Wealth: Purchase Canceled',
  385. SECRET_WEALTH_BUY: 'You have {available} Pet Potion.<br>Do you want to buy {countBuy} {name} for {price} Pet Potion?',
  386. DAILY_BONUS: 'Daily bonus',
  387. DO_DAILY_QUESTS: 'Do daily quests',
  388. ACTIONS: 'Actions',
  389. ACTIONS_TITLE: 'Dialog box with various actions',
  390. OTHERS: 'Others',
  391. OTHERS_TITLE: 'Others',
  392. CHOOSE_ACTION: 'Choose an action',
  393. OPEN_LOOTBOX: 'You have {lootBox} boxes, should we open them?',
  394. STAMINA: 'Energy',
  395. BOXES_OVER: 'The boxes are over',
  396. NO_BOXES: 'No boxes',
  397. NO_MORE_ACTIVITY: 'No more activity for items today',
  398. EXCHANGE_ITEMS: 'Exchange items for activity points (max {maxActive})?',
  399. GET_ACTIVITY: 'Get Activity',
  400. NOT_ENOUGH_ITEMS: 'Not enough items',
  401. ACTIVITY_RECEIVED: 'Activity received',
  402. NO_PURCHASABLE_HERO_SOULS: 'No purchasable Hero Souls',
  403. PURCHASED_HERO_SOULS: 'Purchased {countHeroSouls} Hero Souls',
  404. NOT_ENOUGH_EMERALDS_540: 'Not enough emeralds, you need 540 you have {currentStarMoney}',
  405. CHESTS_NOT_AVAILABLE: 'Chests not available',
  406. OUTLAND_CHESTS_RECEIVED: 'Outland chests received',
  407. RAID_NOT_AVAILABLE: 'The raid is not available or there are no spheres',
  408. RAID_ADVENTURE: 'Raid {adventureId} adventure!',
  409. SOMETHING_WENT_WRONG: 'Something went wrong',
  410. ADVENTURE_COMPLETED: 'Adventure {adventureId} completed {times} times',
  411. CLAN_STAT_COPY: 'Clan statistics copied to clipboard',
  412. GET_ENERGY: 'Get Energy',
  413. GET_ENERGY_TITLE: 'Opens platinum boxes one at a time until you get 250 energy',
  414. ITEM_EXCHANGE: 'Item Exchange',
  415. ITEM_EXCHANGE_TITLE: 'Exchanges items for the specified amount of activity',
  416. BUY_SOULS: 'Buy souls',
  417. BUY_SOULS_TITLE: 'Buy hero souls from all available shops',
  418. BUY_OUTLAND: 'Buy Outland',
  419. BUY_OUTLAND_TITLE: 'Buy 9 chests in Outland for 540 emeralds',
  420. RAID: 'Raid',
  421. AUTO_RAID_ADVENTURE: 'Raid adventure',
  422. AUTO_RAID_ADVENTURE_TITLE: 'Raid adventure set number of times',
  423. CLAN_STAT: 'Clan statistics',
  424. CLAN_STAT_TITLE: 'Copies clan statistics to the clipboard',
  425. BTN_AUTO_F5: 'Auto (F5)',
  426. BOSS_DAMAGE: 'Boss Damage: ',
  427. NOTHING_BUY: 'Nothing to buy',
  428. LOTS_BOUGHT: '{countBuy} lots bought for gold',
  429. BUY_FOR_GOLD: 'Buy for gold',
  430. BUY_FOR_GOLD_TITLE: 'Buy items for gold in the Town Shop and in the Pet Soul Stone Shop',
  431. REWARDS_AND_MAIL: 'Rewars and Mail',
  432. REWARDS_AND_MAIL_TITLE: 'Collects rewards and mail',
  433. COLLECT_REWARDS_AND_MAIL: 'Collected {countQuests} rewards and {countMail} letters',
  434. TIMER_ALREADY: 'Timer already started {time}',
  435. NO_ATTEMPTS_TIMER_START: 'No attempts, timer started {time}',
  436. EPIC_BRAWL_RESULT: 'Wins: {wins}/{attempts}, Coins: {coins}, Streak: {progress}/{nextStage} [Close]{end}',
  437. ATTEMPT_ENDED: '<br>Attempts ended, timer started {time}',
  438. EPIC_BRAWL: 'Cosmic Battle',
  439. EPIC_BRAWL_TITLE: 'Spends attempts in the Cosmic Battle',
  440. RELOAD_GAME: 'Reload game',
  441. TIMER: 'Timer:',
  442. SHOW_ERRORS: 'Show errors',
  443. SHOW_ERRORS_TITLE: 'Show server request errors',
  444. ERROR_MSG: 'Error: {name}<br>{description}',
  445. EVENT_AUTO_BOSS:
  446. '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?',
  447. BEST_SLOW: 'Best (slower)',
  448. FIRST_FAST: 'First (faster)',
  449. FREEZE_INTERFACE: 'Calculating... <br>The interface may freeze.',
  450. ERROR_F12: 'Error, details in the console (F12)',
  451. FAILED_FIND_WIN_PACK: 'Failed to find a winning pack',
  452. BEST_PACK: 'Best pack:',
  453. BOSS_HAS_BEEN_DEF: 'Boss {bossLvl} has been defeated.',
  454. NOT_ENOUGH_ATTEMPTS_BOSS: 'Not enough attempts to defeat boss {bossLvl}, retry?',
  455. BOSS_VICTORY_IMPOSSIBLE:
  456. '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?',
  457. BOSS_HAS_BEEN_DEF_TEXT:
  458. 'Boss {bossLvl} defeated in<br>{countBattle}/{countMaxBattle} attempts<br>(Please synchronize or restart the game to update the data)',
  459. MAP: 'Map: ',
  460. PLAYER_POS: 'Player positions:',
  461. NY_GIFTS: 'Gifts',
  462. NY_GIFTS_TITLE: "Open all New Year's gifts",
  463. NY_NO_GIFTS: 'No gifts not received',
  464. NY_GIFTS_COLLECTED: '{count} gifts collected',
  465. CHANGE_MAP: 'Island map',
  466. CHANGE_MAP_TITLE: 'Change island map',
  467. SELECT_ISLAND_MAP: 'Select an island map:',
  468. FIRST_MAP: 'First map',
  469. SECOND_MAP: 'Second map',
  470. THIRD_MAP: 'Third card',
  471. SECRET_WEALTH_SHOP: 'Secret Wealth {name}: ',
  472. SHOPS: 'Shops',
  473. SHOPS_DEFAULT: 'Default',
  474. SHOPS_DEFAULT_TITLE: 'Default stores',
  475. SHOPS_LIST: 'Shops {number}',
  476. SHOPS_LIST_TITLE: 'List of shops {number}',
  477. SHOPS_WARNING:
  478. '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>',
  479. MINIONS_WARNING: 'The hero packs for attacking minions are incomplete, should I continue?',
  480. FAST_SEASON: 'Fast season',
  481. FAST_SEASON_TITLE: 'Skip the map selection screen in a season',
  482. SET_NUMBER_LEVELS: 'Specify the number of levels:',
  483. POSSIBLE_IMPROVE_LEVELS: 'It is possible to improve only {count} levels.<br>Improving?',
  484. NOT_ENOUGH_RESOURECES: 'Not enough resources',
  485. IMPROVED_LEVELS: 'Improved levels: {count}',
  486. ARTIFACTS_UPGRADE: 'Artifacts Upgrade',
  487. ARTIFACTS_UPGRADE_TITLE: 'Upgrades the specified amount of the cheapest hero artifacts',
  488. SKINS_UPGRADE: 'Skins Upgrade',
  489. SKINS_UPGRADE_TITLE: 'Upgrades the specified amount of the cheapest hero skins',
  490. HINT: '<br>Hint: ',
  491. PICTURE: '<br>Picture: ',
  492. ANSWER: '<br>Answer: ',
  493. NO_HEROES_PACK: 'Fight at least one battle to save the attacking team',
  494. },
  495. ru: {
  496. /* Чекбоксы */
  497. SKIP_FIGHTS: 'Пропуск боев',
  498. SKIP_FIGHTS_TITLE: 'Пропуск боев в запределье и арене титанов, автопропуск в башне и кампании',
  499. ENDLESS_CARDS: 'Бесконечные карты',
  500. ENDLESS_CARDS_TITLE: 'Отключить трату карт предсказаний',
  501. AUTO_EXPEDITION: 'АвтоЭкспедиции',
  502. AUTO_EXPEDITION_TITLE: 'Автоотправка экспедиций',
  503. CANCEL_FIGHT: 'Отмена боя',
  504. CANCEL_FIGHT_TITLE: 'Возможность отмены ручного боя на ВГ, СМ и в Асгарде',
  505. GIFTS: 'Подарки',
  506. GIFTS_TITLE: 'Собирать подарки автоматически',
  507. BATTLE_RECALCULATION: 'Прерасчет боя',
  508. BATTLE_RECALCULATION_TITLE: 'Предварительный расчет боя',
  509. QUANTITY_CONTROL: 'Контроль кол-ва',
  510. QUANTITY_CONTROL_TITLE: 'Возможность указывать количество открываемых "лутбоксов"',
  511. REPEAT_CAMPAIGN: 'Повтор в кампании',
  512. REPEAT_CAMPAIGN_TITLE: 'Автоповтор боев в кампании',
  513. DISABLE_DONAT: 'Отключить донат',
  514. DISABLE_DONAT_TITLE: 'Убирает все предложения доната',
  515. DAILY_QUESTS: 'Квесты',
  516. DAILY_QUESTS_TITLE: 'Выполнять ежедневные квесты',
  517. AUTO_QUIZ: 'АвтоВикторина',
  518. AUTO_QUIZ_TITLE: 'Автоматическое получение правильных ответов на вопросы викторины',
  519. SECRET_WEALTH_CHECKBOX: 'Автоматическая покупка в магазине "Тайное Богатство" при заходе в игру',
  520. HIDE_SERVERS: 'Свернуть сервера',
  521. HIDE_SERVERS_TITLE: 'Скрывать неиспользуемые сервера',
  522. /* Поля ввода */
  523. HOW_MUCH_TITANITE: 'Сколько фармим титанита',
  524. COMBAT_SPEED: 'Множитель ускорения боя',
  525. NUMBER_OF_TEST: 'Количество тестовых боев',
  526. NUMBER_OF_AUTO_BATTLE: 'Количество попыток автобоев',
  527. /* Кнопки */
  528. RUN_SCRIPT: 'Запустить скрипт',
  529. TO_DO_EVERYTHING: 'Сделать все',
  530. TO_DO_EVERYTHING_TITLE: 'Выполнить несколько действий',
  531. OUTLAND: 'Запределье',
  532. OUTLAND_TITLE: 'Собрать Запределье',
  533. TITAN_ARENA: 'Турнир Стихий',
  534. TITAN_ARENA_TITLE: 'Автопрохождение Турнира Стихий',
  535. DUNGEON: 'Подземелье',
  536. DUNGEON_TITLE: 'Автопрохождение подземелья',
  537. SEER: 'Провидец',
  538. SEER_TITLE: 'Покрутить Провидца',
  539. TOWER: 'Башня',
  540. TOWER_TITLE: 'Автопрохождение башни',
  541. EXPEDITIONS: 'Экспедиции',
  542. EXPEDITIONS_TITLE: 'Отправка и сбор экспедиций',
  543. SYNC: 'Синхронизация',
  544. SYNC_TITLE: 'Частичная синхронизация данных игры без перезагрузки сатраницы',
  545. ARCHDEMON: 'Архидемон',
  546. ARCHDEMON_TITLE: 'Набивает килы и собирает награду',
  547. ESTER_EGGS: 'Пасхалки',
  548. ESTER_EGGS_TITLE: 'Собрать все пасхалки или награды',
  549. REWARDS: 'Награды',
  550. REWARDS_TITLE: 'Собрать все награды за задания',
  551. MAIL: 'Почта',
  552. MAIL_TITLE: 'Собрать всю почту, кроме писем с энергией и зарядами портала',
  553. MINIONS: 'Прислужники',
  554. MINIONS_TITLE: 'Атакует прислужников сохраннеными пачками',
  555. ADVENTURE: 'Приключение',
  556. ADVENTURE_TITLE: 'Проходит приключение по указанному маршруту',
  557. STORM: 'Буря',
  558. STORM_TITLE: 'Проходит бурю по указанному маршруту',
  559. SANCTUARY: 'Святилище',
  560. SANCTUARY_TITLE: 'Быстрый переход к Святилищу',
  561. GUILD_WAR: 'Война гильдий',
  562. GUILD_WAR_TITLE: 'Быстрый переход к Войне гильдий',
  563. SECRET_WEALTH: 'Тайное богатство',
  564. SECRET_WEALTH_TITLE: 'Купить что-то в магазине "Тайное богатство"',
  565. /* Разное */
  566. BOTTOM_URLS:
  567. '<a href="https://t.me/+q6gAGCRpwyFkNTYy" target="_blank" title="Telegram"><svg width="20" height="20" style="margin:2px" viewBox="0 0 1e3 1e3" xmlns="http://www.w3.org/2000/svg"><defs><linearGradient id="a" x1="50%" x2="50%" y2="99.258%"><stop stop-color="#2AABEE" offset="0"/><stop stop-color="#229ED9" offset="1"/></linearGradient></defs><g fill-rule="evenodd"><circle cx="500" cy="500" r="500" fill="url(#a)"/><path d="m226.33 494.72c145.76-63.505 242.96-105.37 291.59-125.6 138.86-57.755 167.71-67.787 186.51-68.119 4.1362-0.072862 13.384 0.95221 19.375 5.8132 5.0584 4.1045 6.4501 9.6491 7.1161 13.541 0.666 3.8915 1.4953 12.756 0.83608 19.683-7.5246 79.062-40.084 270.92-56.648 359.47-7.0089 37.469-20.81 50.032-34.17 51.262-29.036 2.6719-51.085-19.189-79.207-37.624-44.007-28.847-68.867-46.804-111.58-74.953-49.366-32.531-17.364-50.411 10.769-79.631 7.3626-7.6471 135.3-124.01 137.77-134.57 0.30968-1.3202 0.59708-6.2414-2.3265-8.8399s-7.2385-1.7099-10.352-1.0032c-4.4137 1.0017-74.715 47.468-210.9 139.4-19.955 13.702-38.029 20.379-54.223 20.029-17.853-0.3857-52.194-10.094-77.723-18.393-31.313-10.178-56.199-15.56-54.032-32.846 1.1287-9.0037 13.528-18.212 37.197-27.624z" fill="#fff"/></g></svg></a><a href="https://vk.com/invite/YNPxKGX" target="_blank" title="Вконтакте"><svg width="20" height="20" style="margin:2px" viewBox="0 0 101 100" xmlns="http://www.w3.org/2000/svg"><g clip-path="url(#a)"><path d="M0.5 48C0.5 25.3726 0.5 14.0589 7.52944 7.02944C14.5589 0 25.8726 0 48.5 0H52.5C75.1274 0 86.4411 0 93.4706 7.02944C100.5 14.0589 100.5 25.3726 100.5 48V52C100.5 74.6274 100.5 85.9411 93.4706 92.9706C86.4411 100 75.1274 100 52.5 100H48.5C25.8726 100 14.5589 100 7.52944 92.9706C0.5 85.9411 0.5 74.6274 0.5 52V48Z" fill="#07f"/><path d="m53.708 72.042c-22.792 0-35.792-15.625-36.333-41.625h11.417c0.375 19.083 8.7915 27.167 15.458 28.833v-28.833h10.75v16.458c6.5833-0.7083 13.499-8.2082 15.832-16.458h10.75c-1.7917 10.167-9.2917 17.667-14.625 20.75 5.3333 2.5 13.875 9.0417 17.125 20.875h-11.834c-2.5417-7.9167-8.8745-14.042-17.25-14.875v14.875h-1.2919z" fill="#fff"/></g><defs><clipPath id="a"><rect transform="translate(.5)" width="100" height="100" fill="#fff"/></clipPath></defs></svg></a>',
  568. GIFTS_SENT: 'Подарки отправлены!',
  569. DO_YOU_WANT: 'Вы действительно хотите это сделать?',
  570. BTN_RUN: 'Запускай',
  571. BTN_CANCEL: 'Отмена',
  572. BTN_OK: 'Ок',
  573. MSG_HAVE_BEEN_DEFEATED: 'Вы потерпели поражение!',
  574. BTN_AUTO: 'Авто',
  575. MSG_YOU_APPLIED: 'Вы нанесли',
  576. MSG_DAMAGE: 'урона',
  577. MSG_CANCEL_AND_STAT: 'Авто (F5) и показать Статистику',
  578. MSG_REPEAT_MISSION: 'Повторить миссию?',
  579. BTN_REPEAT: 'Повторить',
  580. BTN_NO: 'Нет',
  581. MSG_SPECIFY_QUANT: 'Указать количество:',
  582. BTN_OPEN: 'Открыть',
  583. QUESTION_COPY: 'Вопрос скопирован в буфер обмена',
  584. ANSWER_KNOWN: 'Ответ известен',
  585. ANSWER_NOT_KNOWN: 'ВНИМАНИЕ ОТВЕТ НЕ ИЗВЕСТЕН',
  586. BEING_RECALC: 'Идет прерасчет боя',
  587. THIS_TIME: 'На этот раз',
  588. VICTORY: '<span style="color:green;">ПОБЕДА</span>',
  589. DEFEAT: '<span style="color:red;">ПОРАЖЕНИЕ</span>',
  590. CHANCE_TO_WIN: 'Шансы на победу <span style="color:red;">на основе прерасчета</span>',
  591. OPEN_DOLLS: 'матрешек рекурсивно',
  592. SENT_QUESTION: 'Вопрос отправлен',
  593. SETTINGS: 'Настройки',
  594. MSG_BAN_ATTENTION: '<p style="color:red;">Использование этой функции может привести к бану.</p> Продолжить?',
  595. BTN_YES_I_AGREE: 'Да, я беру на себя все риски!',
  596. BTN_NO_I_AM_AGAINST: 'Нет, я отказываюсь от этого!',
  597. VALUES: 'Значения',
  598. EXPEDITIONS_SENT: 'Экспедиции:<br>Собрано: {countGet}<br>Отправлено: {countSend}',
  599. EXPEDITIONS_NOTHING: 'Нечего собриать/отправлять',
  600. TITANIT: 'Титанит',
  601. COMPLETED: 'завершено',
  602. FLOOR: 'Этаж',
  603. LEVEL: 'Уровень',
  604. BATTLES: 'бои',
  605. EVENT: 'Эвент',
  606. NOT_AVAILABLE: 'недоступен',
  607. NO_HEROES: 'Нет героев',
  608. DAMAGE_AMOUNT: 'Количество урона',
  609. NOTHING_TO_COLLECT: 'Нечего собирать',
  610. COLLECTED: 'Собрано',
  611. REWARD: 'наград',
  612. REMAINING_ATTEMPTS: 'Осталось попыток',
  613. BATTLES_CANCELED: 'Битв отменено',
  614. MINION_RAID: 'Рейд прислужников',
  615. STOPPED: 'Остановлено',
  616. REPETITIONS: 'Повторений',
  617. MISSIONS_PASSED: 'Миссий пройдено',
  618. STOP: 'остановить',
  619. TOTAL_OPEN: 'Всего открыто',
  620. OPEN: 'Открыто',
  621. ROUND_STAT: 'Статистика урона за',
  622. BATTLE: 'боев',
  623. MINIMUM: 'Минимальный',
  624. MAXIMUM: 'Максимальный',
  625. AVERAGE: 'Средний',
  626. NOT_THIS_TIME: 'Не в этот раз',
  627. RETRY_LIMIT_EXCEEDED: 'Превышен лимит попыток',
  628. SUCCESS: 'Успех',
  629. RECEIVED: 'Получено',
  630. LETTERS: 'писем',
  631. PORTALS: 'порталов',
  632. ATTEMPTS: 'попыток',
  633. QUEST_10001: 'Улучши умения героев 3 раза',
  634. QUEST_10002: 'Пройди 10 миссий',
  635. QUEST_10003: 'Пройди 3 героические миссии',
  636. QUEST_10004: 'Сразись 3 раза на Арене или Гранд Арене',
  637. QUEST_10006: 'Используй обмен изумрудов 1 раз',
  638. QUEST_10007: 'Соверши 1 призыв в Атриуме Душ',
  639. QUEST_10016: 'Отправь подарки согильдийцам',
  640. QUEST_10018: 'Используй зелье опыта',
  641. QUEST_10019: 'Открой 1 сундук в Башне',
  642. QUEST_10020: 'Открой 3 сундука в Запределье',
  643. QUEST_10021: 'Собери 75 Титанита в Подземелье Гильдии',
  644. QUEST_10021: 'Собери 150 Титанита в Подземелье Гильдии',
  645. QUEST_10023: 'Прокачай Дар Стихий на 1 уровень',
  646. QUEST_10024: 'Повысь уровень любого артефакта один раз',
  647. QUEST_10025: 'Начни 1 Экспедицию',
  648. QUEST_10026: 'Начни 4 Экспедиции',
  649. QUEST_10027: 'Победи в 1 бою Турнира Стихий',
  650. QUEST_10028: 'Повысь уровень любого артефакта титанов',
  651. QUEST_10029: 'Открой сферу артефактов титанов',
  652. QUEST_10030: 'Улучши облик любого героя 1 раз',
  653. QUEST_10031: 'Победи в 6 боях Турнира Стихий',
  654. QUEST_10043: 'Начни или присоеденись к Приключению',
  655. QUEST_10044: 'Воспользуйся призывом питомцев 1 раз',
  656. QUEST_10046: 'Открой 3 сундука в Приключениях',
  657. QUEST_10047: 'Набери 150 очков активности в Гильдии',
  658. NOTHING_TO_DO: 'Нечего выполнять',
  659. YOU_CAN_COMPLETE: 'Можно выполнить квесты',
  660. BTN_DO_IT: 'Выполняй',
  661. NOT_QUEST_COMPLETED: 'Ни одного квеста не выполенно',
  662. COMPLETED_QUESTS: 'Выполнено квестов',
  663. /* everything button */
  664. ASSEMBLE_OUTLAND: 'Собрать Запределье',
  665. PASS_THE_TOWER: 'Пройти башню',
  666. CHECK_EXPEDITIONS: 'Проверить экспедиции',
  667. COMPLETE_TOE: 'Пройти Турнир Стихий',
  668. COMPLETE_DUNGEON: 'Пройти подземелье',
  669. COLLECT_MAIL: 'Собрать почту',
  670. COLLECT_MISC: 'Собрать всякую херню',
  671. COLLECT_MISC_TITLE: 'Собрать пасхалки, камни облика, ключи, монеты арены и Хрусталь души',
  672. COLLECT_QUEST_REWARDS: 'Собрать награды за квесты',
  673. MAKE_A_SYNC: 'Сделать синхронизацю',
  674.  
  675. RUN_FUNCTION: 'Выполнить следующие функции?',
  676. BTN_GO: 'Погнали!',
  677. PERFORMED: 'Выполняется',
  678. DONE: 'Выполнено',
  679. ERRORS_OCCURRES: 'Призошли ошибки при выполнении',
  680. COPY_ERROR: 'Скопировать в буфер информацию об ошибке',
  681. BTN_YES: 'Да',
  682. ALL_TASK_COMPLETED: 'Все задачи выполнены',
  683.  
  684. UNKNOWN: 'Неизвестно',
  685. ENTER_THE_PATH: 'Введите путь приключения через запятые или дефисы',
  686. START_ADVENTURE: 'Начать приключение по этому пути!',
  687. INCORRECT_WAY: 'Неверный путь в приключении: {from} -> {to}',
  688. BTN_CANCELED: 'Отменено',
  689. MUST_TWO_POINTS: 'Путь должен состоять минимум из 2х точек',
  690. MUST_ONLY_NUMBERS: 'Путь должен содержать только цифры и запятые',
  691. NOT_ON_AN_ADVENTURE: 'Вы не в приключении',
  692. YOU_IN_NOT_ON_THE_WAY: 'Указанный путь должен включать точку вашего положения',
  693. ATTEMPTS_NOT_ENOUGH: 'Ваших попыток не достаточно для завершения пути, продолжить?',
  694. YES_CONTINUE: 'Да, продолжай!',
  695. NOT_ENOUGH_AP: 'Попыток не достаточно',
  696. ATTEMPTS_ARE_OVER: 'Попытки закончились',
  697. MOVES: 'Ходы',
  698. BUFF_GET_ERROR: 'Ошибка при получении бафа',
  699. BATTLE_END_ERROR: 'Ошибка завершения боя',
  700. AUTOBOT: 'АвтоБой',
  701. FAILED_TO_WIN_AUTO: 'Не удалось победить в автобою',
  702. ERROR_OF_THE_BATTLE_COPY: 'Призошли ошибка в процессе прохождения боя<br>Скопировать ошибку в буфер обмена?',
  703. ERROR_DURING_THE_BATTLE: 'Ошибка в процессе прохождения боя',
  704. NO_CHANCE_WIN: 'Нет шансов победить в этом бою: 0/',
  705. LOST_HEROES: 'Вы победили, но потеряли одного или несколько героев!',
  706. VICTORY_IMPOSSIBLE: 'Победа не возможна, бъем на результат?',
  707. FIND_COEFF: 'Поиск коэффициента больше чем',
  708. BTN_PASS: 'ПРОПУСК',
  709. BRAWLS: 'Потасовки',
  710. BRAWLS_TITLE: 'Включает возможность автопотасовок',
  711. START_AUTO_BRAWLS: 'Запустить Автопотасовки?',
  712. LOSSES: 'Поражений',
  713. WINS: 'Побед',
  714. FIGHTS: 'Боев',
  715. STAGE: 'Стадия',
  716. DONT_HAVE_LIVES: 'У Вас нет жизней',
  717. LIVES: 'Жизни',
  718. SECRET_WEALTH_ALREADY: 'товар за Зелья питомцев уже куплен',
  719. SECRET_WEALTH_NOT_ENOUGH: 'Не достаточно Зелье Питомца, у Вас {available}, нужно {need}',
  720. SECRET_WEALTH_UPGRADE_NEW_PET: 'После покупки Зелье Питомца будет не достаточно для прокачки нового питомца',
  721. SECRET_WEALTH_PURCHASED: 'Куплено {count} {name}',
  722. SECRET_WEALTH_CANCELED: 'Тайное богатство: покупка отменена',
  723. SECRET_WEALTH_BUY: 'У вас {available} Зелье Питомца.<br>Вы хотите купить {countBuy} {name} за {price} Зелье Питомца?',
  724. DAILY_BONUS: 'Ежедневная награда',
  725. DO_DAILY_QUESTS: 'Сделать ежедневные квесты',
  726. ACTIONS: 'Действия',
  727. ACTIONS_TITLE: 'Диалоговое окно с различными действиями',
  728. OTHERS: 'Разное',
  729. OTHERS_TITLE: 'Диалоговое окно с дополнительными различными действиями',
  730. CHOOSE_ACTION: 'Выберите действие',
  731. OPEN_LOOTBOX: 'У Вас {lootBox} ящиков, откываем?',
  732. STAMINA: 'Энергия',
  733. BOXES_OVER: 'Ящики закончились',
  734. NO_BOXES: 'Нет ящиков',
  735. NO_MORE_ACTIVITY: 'Больше активности за предметы сегодня не получить',
  736. EXCHANGE_ITEMS: 'Обменять предметы на очки активности (не более {maxActive})?',
  737. GET_ACTIVITY: 'Получить активность',
  738. NOT_ENOUGH_ITEMS: 'Предметов недостаточно',
  739. ACTIVITY_RECEIVED: 'Получено активности',
  740. NO_PURCHASABLE_HERO_SOULS: 'Нет доступных для покупки душ героев',
  741. PURCHASED_HERO_SOULS: 'Куплено {countHeroSouls} душ героев',
  742. NOT_ENOUGH_EMERALDS_540: 'Недостаточно изюма, нужно 540 у Вас {currentStarMoney}',
  743. CHESTS_NOT_AVAILABLE: 'Сундуки не доступны',
  744. OUTLAND_CHESTS_RECEIVED: 'Получено сундуков Запределья',
  745. RAID_NOT_AVAILABLE: 'Рейд не доступен или сфер нет',
  746. RAID_ADVENTURE: 'Рейд {adventureId} приключения!',
  747. SOMETHING_WENT_WRONG: 'Что-то пошло не так',
  748. ADVENTURE_COMPLETED: 'Приключение {adventureId} пройдено {times} раз',
  749. CLAN_STAT_COPY: 'Клановая статистика скопирована в буфер обмена',
  750. GET_ENERGY: 'Получить энергию',
  751. GET_ENERGY_TITLE: 'Открывает платиновые шкатулки по одной до получения 250 энергии',
  752. ITEM_EXCHANGE: 'Обмен предметов',
  753. ITEM_EXCHANGE_TITLE: 'Обменивает предметы на указанное количество активности',
  754. BUY_SOULS: 'Купить души',
  755. BUY_SOULS_TITLE: 'Купить души героев из всех доступных магазинов',
  756. BUY_OUTLAND: 'Купить Запределье',
  757. BUY_OUTLAND_TITLE: 'Купить 9 сундуков в Запределье за 540 изумрудов',
  758. RAID: 'Рейд',
  759. AUTO_RAID_ADVENTURE: 'Рейд приключения',
  760. AUTO_RAID_ADVENTURE_TITLE: 'Рейд приключения заданное количество раз',
  761. CLAN_STAT: 'Клановая статистика',
  762. CLAN_STAT_TITLE: 'Копирует клановую статистику в буфер обмена',
  763. BTN_AUTO_F5: 'Авто (F5)',
  764. BOSS_DAMAGE: 'Урон по боссу: ',
  765. NOTHING_BUY: 'Нечего покупать',
  766. LOTS_BOUGHT: 'За золото куплено {countBuy} лотов',
  767. BUY_FOR_GOLD: 'Скупить за золото',
  768. BUY_FOR_GOLD_TITLE: 'Скупить предметы за золото в Городской лавке и в магазине Камней Душ Питомцев',
  769. REWARDS_AND_MAIL: 'Награды и почта',
  770. REWARDS_AND_MAIL_TITLE: 'Собирает награды и почту',
  771. COLLECT_REWARDS_AND_MAIL: 'Собрано {countQuests} наград и {countMail} писем',
  772. TIMER_ALREADY: 'Таймер уже запущен {time}',
  773. NO_ATTEMPTS_TIMER_START: 'Попыток нет, запущен таймер {time}',
  774. EPIC_BRAWL_RESULT: '{i} Победы: {wins}/{attempts}, Монеты: {coins}, Серия: {progress}/{nextStage} [Закрыть]{end}',
  775. ATTEMPT_ENDED: '<br>Попытки закончились, запущен таймер {time}',
  776. EPIC_BRAWL: 'Вселенская битва',
  777. EPIC_BRAWL_TITLE: 'Тратит попытки во Вселенской битве',
  778. RELOAD_GAME: 'Перезагрузить игру',
  779. TIMER: 'Таймер:',
  780. SHOW_ERRORS: 'Отображать ошибки',
  781. SHOW_ERRORS_TITLE: 'Отображать ошибки запросов к серверу',
  782. ERROR_MSG: 'Ошибка: {name}<br>{description}',
  783. EVENT_AUTO_BOSS:
  784. 'Максимальное количество боев для расчета:</br>{length} * {countTestBattle} = {maxCalcBattle}</br>Если у Вас слабый компьютер на это может потребоваться много времени, нажмите крестик для отмены.</br>Искать лучший пак из всех или первый подходящий?',
  785. BEST_SLOW: 'Лучший (медленее)',
  786. FIRST_FAST: 'Первый (быстрее)',
  787. FREEZE_INTERFACE: 'Идет расчет... <br> Интерфейс может зависнуть.',
  788. ERROR_F12: 'Ошибка, подробности в консоли (F12)',
  789. FAILED_FIND_WIN_PACK: 'Победный пак найти не удалось',
  790. BEST_PACK: 'Наилучший пак: ',
  791. BOSS_HAS_BEEN_DEF: 'Босс {bossLvl} побежден',
  792. NOT_ENOUGH_ATTEMPTS_BOSS: 'Для победы босса ${bossLvl} не хватило попыток, повторить?',
  793. BOSS_VICTORY_IMPOSSIBLE:
  794. 'По результатам прерасчета {battles} боев победу получить не удалось. Вы хотите продолжить поиск победного боя на реальных боях?',
  795. BOSS_HAS_BEEN_DEF_TEXT:
  796. 'Босс {bossLvl} побежден за<br>{countBattle}/{countMaxBattle} попыток<br>(Сделайте синхронизацию или перезагрузите игру для обновления данных)',
  797. MAP: 'Карта: ',
  798. PLAYER_POS: 'Позиции игроков:',
  799. NY_GIFTS: 'Подарки',
  800. NY_GIFTS_TITLE: 'Открыть все новогодние подарки',
  801. NY_NO_GIFTS: 'Нет не полученных подарков',
  802. NY_GIFTS_COLLECTED: 'Собрано {count} подарков',
  803. CHANGE_MAP: 'Карта острова',
  804. CHANGE_MAP_TITLE: 'Сменить карту острова',
  805. SELECT_ISLAND_MAP: 'Выберите карту острова:',
  806. FIRST_MAP: 'Первая карта',
  807. SECOND_MAP: 'Вторая карта',
  808. THIRD_MAP: 'Третья карта',
  809. SECRET_WEALTH_SHOP: 'Тайное богатство {name}: ',
  810. SHOPS: 'Магазины',
  811. SHOPS_DEFAULT: 'Стандартные',
  812. SHOPS_DEFAULT_TITLE: 'Стандартные магазины',
  813. SHOPS_LIST: 'Магазины {number}',
  814. SHOPS_LIST_TITLE: 'Список магазинов {number}',
  815. SHOPS_WARNING:
  816. 'Магазины<br><span style="color:red">Если Вы купите монеты магазинов потасовок за изумруды, то их надо использовать сразу, иначе после перезагрузки игры они пропадут!</span>',
  817. MINIONS_WARNING: 'Пачки героев для атаки приспешников неполные, продолжить?',
  818. FAST_SEASON: 'Быстрый сезон',
  819. FAST_SEASON_TITLE: 'Пропуск экрана с выбором карты в сезоне',
  820. SET_NUMBER_LEVELS: 'Указать колличество уровней:',
  821. POSSIBLE_IMPROVE_LEVELS: 'Возможно улучшить только {count} уровней.<br>Улучшаем?',
  822. NOT_ENOUGH_RESOURECES: 'Не хватает ресурсов',
  823. IMPROVED_LEVELS: 'Улучшено уровней: {count}',
  824. ARTIFACTS_UPGRADE: 'Улучшение артефактов',
  825. ARTIFACTS_UPGRADE_TITLE: 'Улучшает указанное количество самых дешевых артефактов героев',
  826. SKINS_UPGRADE: 'Улучшение обликов',
  827. SKINS_UPGRADE_TITLE: 'Улучшает указанное количество самых дешевых обликов героев',
  828. HINT: '<br>Подсказка: ',
  829. PICTURE: '<br>На картинке: ',
  830. ANSWER: '<br>Ответ: ',
  831. NO_HEROES_PACK: 'Проведите хотя бы один бой для сохранения атакующей команды',
  832. },
  833. };
  834.  
  835. function getLang() {
  836. let lang = '';
  837. if (typeof NXFlashVars !== 'undefined') {
  838. lang = NXFlashVars.interface_lang
  839. }
  840. if (!lang) {
  841. lang = (navigator.language || navigator.userLanguage).substr(0, 2);
  842. }
  843. if (lang == 'ru') {
  844. return lang;
  845. }
  846. return 'en';
  847. }
  848.  
  849. this.I18N = function (constant, replace) {
  850. const selectLang = getLang();
  851. if (constant && constant in i18nLangData[selectLang]) {
  852. const result = i18nLangData[selectLang][constant];
  853. if (replace) {
  854. return result.sprintf(replace);
  855. }
  856. return result;
  857. }
  858. return `% ${constant} %`;
  859. };
  860.  
  861. String.prototype.sprintf = String.prototype.sprintf ||
  862. function () {
  863. "use strict";
  864. var str = this.toString();
  865. if (arguments.length) {
  866. var t = typeof arguments[0];
  867. var key;
  868. var args = ("string" === t || "number" === t) ?
  869. Array.prototype.slice.call(arguments)
  870. : arguments[0];
  871.  
  872. for (key in args) {
  873. str = str.replace(new RegExp("\\{" + key + "\\}", "gi"), args[key]);
  874. }
  875. }
  876.  
  877. return str;
  878. };
  879.  
  880. /**
  881. * Checkboxes
  882. *
  883. * Чекбоксы
  884. */
  885. const checkboxes = {
  886. passBattle: {
  887. label: I18N('SKIP_FIGHTS'),
  888. cbox: null,
  889. title: I18N('SKIP_FIGHTS_TITLE'),
  890. default: false
  891. },
  892. sendExpedition: {
  893. label: I18N('AUTO_EXPEDITION'),
  894. cbox: null,
  895. title: I18N('AUTO_EXPEDITION_TITLE'),
  896. default: false
  897. },
  898. cancelBattle: {
  899. label: I18N('CANCEL_FIGHT'),
  900. cbox: null,
  901. title: I18N('CANCEL_FIGHT_TITLE'),
  902. default: false,
  903. },
  904. preCalcBattle: {
  905. label: I18N('BATTLE_RECALCULATION'),
  906. cbox: null,
  907. title: I18N('BATTLE_RECALCULATION_TITLE'),
  908. default: false
  909. },
  910. countControl: {
  911. label: I18N('QUANTITY_CONTROL'),
  912. cbox: null,
  913. title: I18N('QUANTITY_CONTROL_TITLE'),
  914. default: true
  915. },
  916. repeatMission: {
  917. label: I18N('REPEAT_CAMPAIGN'),
  918. cbox: null,
  919. title: I18N('REPEAT_CAMPAIGN_TITLE'),
  920. default: false
  921. },
  922. noOfferDonat: {
  923. label: I18N('DISABLE_DONAT'),
  924. cbox: null,
  925. title: I18N('DISABLE_DONAT_TITLE'),
  926. /**
  927. * A crutch to get the field before getting the character id
  928. *
  929. * Костыль чтоб получать поле до получения id персонажа
  930. */
  931. default: (() => {
  932. $result = false;
  933. try {
  934. $result = JSON.parse(localStorage[GM_info.script.name + ':noOfferDonat'])
  935. } catch(e) {
  936. $result = false;
  937. }
  938. return $result || false;
  939. })(),
  940. },
  941. dailyQuests: {
  942. label: I18N('DAILY_QUESTS'),
  943. cbox: null,
  944. title: I18N('DAILY_QUESTS_TITLE'),
  945. default: false
  946. },
  947. // Потасовки
  948. autoBrawls: {
  949. label: I18N('BRAWLS'),
  950. cbox: null,
  951. title: I18N('BRAWLS_TITLE'),
  952. default: (() => {
  953. $result = false;
  954. try {
  955. $result = JSON.parse(localStorage[GM_info.script.name + ':autoBrawls'])
  956. } catch (e) {
  957. $result = false;
  958. }
  959. return $result || false;
  960. })(),
  961. hide: false,
  962. },
  963. getAnswer: {
  964. label: I18N('AUTO_QUIZ'),
  965. cbox: null,
  966. title: I18N('AUTO_QUIZ_TITLE'),
  967. default: false,
  968. hide: true,
  969. },
  970. showErrors: {
  971. label: I18N('SHOW_ERRORS'),
  972. cbox: null,
  973. title: I18N('SHOW_ERRORS_TITLE'),
  974. default: true
  975. },
  976. buyForGold: {
  977. label: I18N('BUY_FOR_GOLD'),
  978. cbox: null,
  979. title: I18N('BUY_FOR_GOLD_TITLE'),
  980. default: false
  981. },
  982. hideServers: {
  983. label: I18N('HIDE_SERVERS'),
  984. cbox: null,
  985. title: I18N('HIDE_SERVERS_TITLE'),
  986. default: false
  987. },
  988. fastSeason: {
  989. label: I18N('FAST_SEASON'),
  990. cbox: null,
  991. title: I18N('FAST_SEASON_TITLE'),
  992. default: false
  993. },
  994. };
  995. /**
  996. * Get checkbox state
  997. *
  998. * Получить состояние чекбокса
  999. */
  1000. function isChecked(checkBox) {
  1001. if (!(checkBox in checkboxes)) {
  1002. return false;
  1003. }
  1004. return checkboxes[checkBox].cbox?.checked;
  1005. }
  1006. /**
  1007. * Input fields
  1008. *
  1009. * Поля ввода
  1010. */
  1011. const inputs = {
  1012. countTitanit: {
  1013. input: null,
  1014. title: I18N('HOW_MUCH_TITANITE'),
  1015. default: 150,
  1016. },
  1017. speedBattle: {
  1018. input: null,
  1019. title: I18N('COMBAT_SPEED'),
  1020. default: 5,
  1021. },
  1022. countTestBattle: {
  1023. input: null,
  1024. title: I18N('NUMBER_OF_TEST'),
  1025. default: 10,
  1026. },
  1027. countAutoBattle: {
  1028. input: null,
  1029. title: I18N('NUMBER_OF_AUTO_BATTLE'),
  1030. default: 10,
  1031. },
  1032. FPS: {
  1033. input: null,
  1034. title: 'FPS',
  1035. default: 60,
  1036. }
  1037. }
  1038. /**
  1039. * Checks the checkbox
  1040. *
  1041. * Поплучить данные поля ввода
  1042. */
  1043. function getInput(inputName) {
  1044. return inputs[inputName]?.input?.value;
  1045. }
  1046.  
  1047. /**
  1048. * Control FPS
  1049. *
  1050. * Контроль FPS
  1051. */
  1052. let nextAnimationFrame = Date.now();
  1053. const oldRequestAnimationFrame = this.requestAnimationFrame;
  1054. this.requestAnimationFrame = async function (e) {
  1055. const FPS = Number(getInput('FPS')) || -1;
  1056. const now = Date.now();
  1057. const delay = nextAnimationFrame - now;
  1058. nextAnimationFrame = Math.max(now, nextAnimationFrame) + Math.min(1e3 / FPS, 1e3);
  1059. if (delay > 0) {
  1060. await new Promise((e) => setTimeout(e, delay));
  1061. }
  1062. oldRequestAnimationFrame(e);
  1063. };
  1064. /**
  1065. * Button List
  1066. *
  1067. * Список кнопочек
  1068. */
  1069. const buttons = {
  1070. getOutland: {
  1071. name: I18N('TO_DO_EVERYTHING'),
  1072. title: I18N('TO_DO_EVERYTHING_TITLE'),
  1073. func: testDoYourBest,
  1074. },
  1075. doActions: {
  1076. name: I18N('ACTIONS'),
  1077. title: I18N('ACTIONS_TITLE'),
  1078. func: async function () {
  1079. const popupButtons = [
  1080. {
  1081. msg: I18N('OUTLAND'),
  1082. result: function () {
  1083. confShow(`${I18N('RUN_SCRIPT')} ${I18N('OUTLAND')}?`, getOutland);
  1084. },
  1085. title: I18N('OUTLAND_TITLE'),
  1086. },
  1087. {
  1088. msg: I18N('TOWER'),
  1089. result: function () {
  1090. confShow(`${I18N('RUN_SCRIPT')} ${I18N('TOWER')}?`, testTower);
  1091. },
  1092. title: I18N('TOWER_TITLE'),
  1093. },
  1094. {
  1095. msg: I18N('EXPEDITIONS'),
  1096. result: function () {
  1097. confShow(`${I18N('RUN_SCRIPT')} ${I18N('EXPEDITIONS')}?`, checkExpedition);
  1098. },
  1099. title: I18N('EXPEDITIONS_TITLE'),
  1100. },
  1101. {
  1102. msg: I18N('MINIONS'),
  1103. result: function () {
  1104. confShow(`${I18N('RUN_SCRIPT')} ${I18N('MINIONS')}?`, testRaidNodes);
  1105. },
  1106. title: I18N('MINIONS_TITLE'),
  1107. },
  1108. {
  1109. msg: I18N('ESTER_EGGS'),
  1110. result: function () {
  1111. confShow(`${I18N('RUN_SCRIPT')} ${I18N('ESTER_EGGS')}?`, offerFarmAllReward);
  1112. },
  1113. title: I18N('ESTER_EGGS_TITLE'),
  1114. },
  1115. {
  1116. msg: I18N('STORM'),
  1117. result: function () {
  1118. testAdventure('solo');
  1119. },
  1120. title: I18N('STORM_TITLE'),
  1121. },
  1122. {
  1123. msg: I18N('REWARDS'),
  1124. result: function () {
  1125. confShow(`${I18N('RUN_SCRIPT')} ${I18N('REWARDS')}?`, questAllFarm);
  1126. },
  1127. title: I18N('REWARDS_TITLE'),
  1128. },
  1129. {
  1130. msg: I18N('MAIL'),
  1131. result: function () {
  1132. confShow(`${I18N('RUN_SCRIPT')} ${I18N('MAIL')}?`, mailGetAll);
  1133. },
  1134. title: I18N('MAIL_TITLE'),
  1135. },
  1136. {
  1137. msg: I18N('SEER'),
  1138. result: function () {
  1139. confShow(`${I18N('RUN_SCRIPT')} ${I18N('SEER')}?`, rollAscension);
  1140. },
  1141. title: I18N('SEER_TITLE'),
  1142. },
  1143. /*
  1144. {
  1145. msg: I18N('NY_GIFTS'),
  1146. result: getGiftNewYear,
  1147. title: I18N('NY_GIFTS_TITLE'),
  1148. },
  1149. */
  1150. ];
  1151. popupButtons.push({ result: false, isClose: true })
  1152. const answer = await popup.confirm(`${I18N('CHOOSE_ACTION')}:`, popupButtons);
  1153. if (typeof answer === 'function') {
  1154. answer();
  1155. }
  1156. }
  1157. },
  1158. doOthers: {
  1159. name: I18N('OTHERS'),
  1160. title: I18N('OTHERS_TITLE'),
  1161. func: async function () {
  1162. const popupButtons = [
  1163. {
  1164. msg: I18N('GET_ENERGY'),
  1165. result: farmStamina,
  1166. title: I18N('GET_ENERGY_TITLE'),
  1167. },
  1168. {
  1169. msg: I18N('ITEM_EXCHANGE'),
  1170. result: fillActive,
  1171. title: I18N('ITEM_EXCHANGE_TITLE'),
  1172. },
  1173. {
  1174. msg: I18N('BUY_SOULS'),
  1175. result: function () {
  1176. confShow(`${I18N('RUN_SCRIPT')} ${I18N('BUY_SOULS')}?`, buyHeroFragments);
  1177. },
  1178. title: I18N('BUY_SOULS_TITLE'),
  1179. },
  1180. {
  1181. msg: I18N('BUY_FOR_GOLD'),
  1182. result: function () {
  1183. confShow(`${I18N('RUN_SCRIPT')} ${I18N('BUY_FOR_GOLD')}?`, buyInStoreForGold);
  1184. },
  1185. title: I18N('BUY_FOR_GOLD_TITLE'),
  1186. },
  1187. {
  1188. msg: I18N('BUY_OUTLAND'),
  1189. result: function () {
  1190. confShow(I18N('BUY_OUTLAND_TITLE') + '?', bossOpenChestPay);
  1191. },
  1192. title: I18N('BUY_OUTLAND_TITLE'),
  1193. },
  1194. {
  1195. msg: I18N('AUTO_RAID_ADVENTURE'),
  1196. result: autoRaidAdventure,
  1197. title: I18N('AUTO_RAID_ADVENTURE_TITLE'),
  1198. },
  1199. {
  1200. msg: I18N('CLAN_STAT'),
  1201. result: clanStatistic,
  1202. title: I18N('CLAN_STAT_TITLE'),
  1203. },
  1204. {
  1205. msg: I18N('EPIC_BRAWL'),
  1206. result: async function () {
  1207. confShow(`${I18N('RUN_SCRIPT')} ${I18N('EPIC_BRAWL')}?`, () => {
  1208. const brawl = new epicBrawl;
  1209. brawl.start();
  1210. });
  1211. },
  1212. title: I18N('EPIC_BRAWL_TITLE'),
  1213. },
  1214. {
  1215. msg: I18N('ARTIFACTS_UPGRADE'),
  1216. result: updateArtifacts,
  1217. title: I18N('ARTIFACTS_UPGRADE_TITLE'),
  1218. },
  1219. {
  1220. msg: I18N('SKINS_UPGRADE'),
  1221. result: updateSkins,
  1222. title: I18N('SKINS_UPGRADE_TITLE'),
  1223. },
  1224. {
  1225. msg: I18N('CHANGE_MAP'),
  1226. result: async function () {
  1227. const result = await popup.confirm(I18N('SELECT_ISLAND_MAP'), [
  1228. { msg: I18N('FIRST_MAP'), result: 1 },
  1229. { msg: I18N('SECOND_MAP'), result: 2 },
  1230. { msg: I18N('THIRD_MAP'), result: 3 },
  1231. { result: false, isClose: true },
  1232. ]);
  1233. if (result) {
  1234. cheats.changeIslandMap(result);
  1235. }
  1236. },
  1237. title: I18N('CHANGE_MAP_TITLE'),
  1238. },
  1239. ];
  1240. popupButtons.push({ result: false, isClose: true })
  1241. const answer = await popup.confirm(`${I18N('CHOOSE_ACTION')}:`, popupButtons);
  1242. if (typeof answer === 'function') {
  1243. answer();
  1244. }
  1245. }
  1246. },
  1247. testTitanArena: {
  1248. name: I18N('TITAN_ARENA'),
  1249. title: I18N('TITAN_ARENA_TITLE'),
  1250. func: function () {
  1251. confShow(`${I18N('RUN_SCRIPT')} ${I18N('TITAN_ARENA')}?`, testTitanArena);
  1252. },
  1253. },
  1254. testDungeon: {
  1255. name: I18N('DUNGEON'),
  1256. title: I18N('DUNGEON_TITLE'),
  1257. func: function () {
  1258. confShow(`${I18N('RUN_SCRIPT')} ${I18N('DUNGEON')}?`, testDungeon);
  1259. },
  1260. },
  1261. // Архидемон
  1262. bossRatingEvent: {
  1263. name: I18N('ARCHDEMON'),
  1264. title: I18N('ARCHDEMON_TITLE'),
  1265. func: function () {
  1266. confShow(`${I18N('RUN_SCRIPT')} ${I18N('ARCHDEMON')}?`, bossRatingEvent);
  1267. },
  1268. hide: true,
  1269. },
  1270. /*
  1271. // Горнило душ
  1272. bossRatingEvent: {
  1273. name: I18N('ARCHDEMON'),
  1274. title: I18N('ARCHDEMON_TITLE'),
  1275. func: function () {
  1276. confShow(`${I18N('RUN_SCRIPT')} ${I18N('ARCHDEMON')}?`, bossRatingEventSouls);
  1277. },
  1278. },
  1279. */
  1280. rewardsAndMailFarm: {
  1281. name: I18N('REWARDS_AND_MAIL'),
  1282. title: I18N('REWARDS_AND_MAIL_TITLE'),
  1283. func: function () {
  1284. confShow(`${I18N('RUN_SCRIPT')} ${I18N('REWARDS_AND_MAIL')}?`, rewardsAndMailFarm);
  1285. },
  1286. },
  1287. testAdventure: {
  1288. name: I18N('ADVENTURE'),
  1289. title: I18N('ADVENTURE_TITLE'),
  1290. func: () => {
  1291. testAdventure();
  1292. },
  1293. },
  1294. goToSanctuary: {
  1295. name: I18N('SANCTUARY'),
  1296. title: I18N('SANCTUARY_TITLE'),
  1297. func: cheats.goSanctuary,
  1298. },
  1299. goToClanWar: {
  1300. name: I18N('GUILD_WAR'),
  1301. title: I18N('GUILD_WAR_TITLE'),
  1302. func: cheats.goClanWar,
  1303. },
  1304. dailyQuests: {
  1305. name: I18N('DAILY_QUESTS'),
  1306. title: I18N('DAILY_QUESTS_TITLE'),
  1307. func: async function () {
  1308. const quests = new dailyQuests(() => { }, () => { });
  1309. await quests.autoInit();
  1310. quests.start();
  1311. },
  1312. },
  1313. newDay: {
  1314. name: I18N('SYNC'),
  1315. title: I18N('SYNC_TITLE'),
  1316. func: function () {
  1317. confShow(`${I18N('RUN_SCRIPT')} ${I18N('SYNC')}?`, cheats.refreshGame);
  1318. },
  1319. },
  1320. }
  1321. /**
  1322. * Display buttons
  1323. *
  1324. * Вывести кнопочки
  1325. */
  1326. function addControlButtons() {
  1327. for (let name in buttons) {
  1328. button = buttons[name];
  1329. if (button.hide) {
  1330. continue;
  1331. }
  1332. button['button'] = scriptMenu.addButton(button.name, button.func, button.title);
  1333. }
  1334. }
  1335. /**
  1336. * Adds links
  1337. *
  1338. * Добавляет ссылки
  1339. */
  1340. function addBottomUrls() {
  1341. scriptMenu.addHeader(I18N('BOTTOM_URLS'));
  1342. }
  1343. /**
  1344. * Stop repetition of the mission
  1345. *
  1346. * Остановить повтор миссии
  1347. */
  1348. let isStopSendMission = false;
  1349. /**
  1350. * There is a repetition of the mission
  1351. *
  1352. * Идет повтор миссии
  1353. */
  1354. let isSendsMission = false;
  1355. /**
  1356. * Data on the past mission
  1357. *
  1358. * Данные о прошедшей мисии
  1359. */
  1360. let lastMissionStart = {}
  1361. /**
  1362. * Start time of the last battle in the company
  1363. *
  1364. * Время начала последнего боя в кампании
  1365. */
  1366. let lastMissionBattleStart = 0;
  1367. /**
  1368. * Data on the past attack on the boss
  1369. *
  1370. * Данные о прошедшей атаке на босса
  1371. */
  1372. let lastBossBattle = {}
  1373. /**
  1374. * Data for calculating the last battle with the boss
  1375. *
  1376. * Данные для расчете последнего боя с боссом
  1377. */
  1378. let lastBossBattleInfo = null;
  1379. /**
  1380. * Ability to cancel the battle in Asgard
  1381. *
  1382. * Возможность отменить бой в Астгарде
  1383. */
  1384. let isCancalBossBattle = true;
  1385. /**
  1386. * Information about the last battle
  1387. *
  1388. * Данные о прошедшей битве
  1389. */
  1390. let lastBattleArg = {}
  1391. let lastBossBattleStart = null;
  1392. this.addBattleTimer = 4;
  1393. this.invasionTimer = 2500;
  1394. /**
  1395. * The name of the function of the beginning of the battle
  1396. *
  1397. * Имя функции начала боя
  1398. */
  1399. let nameFuncStartBattle = '';
  1400. /**
  1401. * The name of the function of the end of the battle
  1402. *
  1403. * Имя функции конца боя
  1404. */
  1405. let nameFuncEndBattle = '';
  1406. /**
  1407. * Data for calculating the last battle
  1408. *
  1409. * Данные для расчета последнего боя
  1410. */
  1411. let lastBattleInfo = null;
  1412. /**
  1413. * The ability to cancel the battle
  1414. *
  1415. * Возможность отменить бой
  1416. */
  1417. let isCancalBattle = true;
  1418.  
  1419. /**
  1420. * Certificator of the last open nesting doll
  1421. *
  1422. * Идетификатор последней открытой матрешки
  1423. */
  1424. let lastRussianDollId = null;
  1425. /**
  1426. * Cancel the training guide
  1427. *
  1428. * Отменить обучающее руководство
  1429. */
  1430. this.isCanceledTutorial = false;
  1431.  
  1432. /**
  1433. * Data from the last question of the quiz
  1434. *
  1435. * Данные последнего вопроса викторины
  1436. */
  1437. let lastQuestion = null;
  1438. /**
  1439. * Answer to the last question of the quiz
  1440. *
  1441. * Ответ на последний вопрос викторины
  1442. */
  1443. let lastAnswer = null;
  1444. /**
  1445. * Flag for opening keys or titan artifact spheres
  1446. *
  1447. * Флаг открытия ключей или сфер артефактов титанов
  1448. */
  1449. let artifactChestOpen = false;
  1450. /**
  1451. * The name of the function to open keys or orbs of titan artifacts
  1452. *
  1453. * Имя функции открытия ключей или сфер артефактов титанов
  1454. */
  1455. let artifactChestOpenCallName = '';
  1456. let correctShowOpenArtifact = 0;
  1457. /**
  1458. * Data for the last battle in the dungeon
  1459. * (Fix endless cards)
  1460. *
  1461. * Данные для последнего боя в подземке
  1462. * (Исправление бесконечных карт)
  1463. */
  1464. let lastDungeonBattleData = null;
  1465. /**
  1466. * Start time of the last battle in the dungeon
  1467. *
  1468. * Время начала последнего боя в подземелье
  1469. */
  1470. let lastDungeonBattleStart = 0;
  1471. /**
  1472. * Subscription end time
  1473. *
  1474. * Время окончания подписки
  1475. */
  1476. let subEndTime = 0;
  1477. /**
  1478. * Number of prediction cards
  1479. *
  1480. * Количество карт предсказаний
  1481. */
  1482. let countPredictionCard = 0;
  1483.  
  1484. /**
  1485. * Brawl pack
  1486. *
  1487. * Пачка для потасовок
  1488. */
  1489. let brawlsPack = null;
  1490. /**
  1491. * Autobrawl started
  1492. *
  1493. * Автопотасовка запущена
  1494. */
  1495. let isBrawlsAutoStart = false;
  1496. /**
  1497. * Copies the text to the clipboard
  1498. *
  1499. * Копирует тест в буфер обмена
  1500. * @param {*} text copied text // копируемый текст
  1501. */
  1502. function copyText(text) {
  1503. let copyTextarea = document.createElement("textarea");
  1504. copyTextarea.style.opacity = "0";
  1505. copyTextarea.textContent = text;
  1506. document.body.appendChild(copyTextarea);
  1507. copyTextarea.select();
  1508. document.execCommand("copy");
  1509. document.body.removeChild(copyTextarea);
  1510. delete copyTextarea;
  1511. }
  1512. /**
  1513. * Returns the history of requests
  1514. *
  1515. * Возвращает историю запросов
  1516. */
  1517. this.getRequestHistory = function() {
  1518. return requestHistory;
  1519. }
  1520. /**
  1521. * Generates a random integer from min to max
  1522. *
  1523. * Гененирует случайное целое число от min до max
  1524. */
  1525. const random = function (min, max) {
  1526. return Math.floor(Math.random() * (max - min + 1) + min);
  1527. }
  1528. /**
  1529. * Clearing the request history
  1530. *
  1531. * Очистка истоии запросов
  1532. */
  1533. setInterval(function () {
  1534. let now = Date.now();
  1535. for (let i in requestHistory) {
  1536. const time = +i.split('_')[0];
  1537. if (now - time > 300000) {
  1538. delete requestHistory[i];
  1539. }
  1540. }
  1541. }, 300000);
  1542. /**
  1543. * Displays the dialog box
  1544. *
  1545. * Отображает диалоговое окно
  1546. */
  1547. function confShow(message, yesCallback, noCallback) {
  1548. let buts = [];
  1549. message = message || I18N('DO_YOU_WANT');
  1550. noCallback = noCallback || (() => {});
  1551. if (yesCallback) {
  1552. buts = [
  1553. { msg: I18N('BTN_RUN'), result: true},
  1554. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true},
  1555. ]
  1556. } else {
  1557. yesCallback = () => {};
  1558. buts = [
  1559. { msg: I18N('BTN_OK'), result: true},
  1560. ];
  1561. }
  1562. popup.confirm(message, buts).then((e) => {
  1563. // dialogPromice = null;
  1564. if (e) {
  1565. yesCallback();
  1566. } else {
  1567. noCallback();
  1568. }
  1569. });
  1570. }
  1571. /**
  1572. * Override/proxy the method for creating a WS package send
  1573. *
  1574. * Переопределяем/проксируем метод создания отправки WS пакета
  1575. */
  1576. WebSocket.prototype.send = function (data) {
  1577. if (!this.isSetOnMessage) {
  1578. const oldOnmessage = this.onmessage;
  1579. this.onmessage = function (event) {
  1580. try {
  1581. const data = JSON.parse(event.data);
  1582. if (!this.isWebSocketLogin && data.result.type == "iframeEvent.login") {
  1583. this.isWebSocketLogin = true;
  1584. } else if (data.result.type == "iframeEvent.login") {
  1585. return;
  1586. }
  1587. } catch (e) { }
  1588. return oldOnmessage.apply(this, arguments);
  1589. }
  1590. this.isSetOnMessage = true;
  1591. }
  1592. original.SendWebSocket.call(this, data);
  1593. }
  1594. /**
  1595. * Overriding/Proxying the Ajax Request Creation Method
  1596. *
  1597. * Переопределяем/проксируем метод создания Ajax запроса
  1598. */
  1599. XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
  1600. this.uniqid = Date.now() + '_' + random(1000000, 10000000);
  1601. this.errorRequest = false;
  1602. if (method == 'POST' && url.includes('.nextersglobal.com/api/') && /api\/$/.test(url)) {
  1603. if (!apiUrl) {
  1604. apiUrl = url;
  1605. const socialInfo = /heroes-(.+?)\./.exec(apiUrl);
  1606. console.log(socialInfo);
  1607. }
  1608. requestHistory[this.uniqid] = {
  1609. method,
  1610. url,
  1611. error: [],
  1612. headers: {},
  1613. request: null,
  1614. response: null,
  1615. signature: [],
  1616. calls: {},
  1617. };
  1618. } else if (method == 'POST' && url.includes('error.nextersglobal.com/client/')) {
  1619. this.errorRequest = true;
  1620. }
  1621. return original.open.call(this, method, url, async, user, password);
  1622. };
  1623. /**
  1624. * Overriding/Proxying the header setting method for the AJAX request
  1625. *
  1626. * Переопределяем/проксируем метод установки заголовков для AJAX запроса
  1627. */
  1628. XMLHttpRequest.prototype.setRequestHeader = function (name, value, check) {
  1629. if (this.uniqid in requestHistory) {
  1630. requestHistory[this.uniqid].headers[name] = value;
  1631. } else {
  1632. check = true;
  1633. }
  1634.  
  1635. if (name == 'X-Auth-Signature') {
  1636. requestHistory[this.uniqid].signature.push(value);
  1637. if (!check) {
  1638. return;
  1639. }
  1640. }
  1641.  
  1642. return original.setRequestHeader.call(this, name, value);
  1643. };
  1644. /**
  1645. * Overriding/Proxying the AJAX Request Sending Method
  1646. *
  1647. * Переопределяем/проксируем метод отправки AJAX запроса
  1648. */
  1649. XMLHttpRequest.prototype.send = async function (sourceData) {
  1650. if (this.uniqid in requestHistory) {
  1651. let tempData = null;
  1652. if (getClass(sourceData) == "ArrayBuffer") {
  1653. tempData = decoder.decode(sourceData);
  1654. } else {
  1655. tempData = sourceData;
  1656. }
  1657. requestHistory[this.uniqid].request = tempData;
  1658. let headers = requestHistory[this.uniqid].headers;
  1659. lastHeaders = Object.assign({}, headers);
  1660. /**
  1661. * Game loading event
  1662. *
  1663. * Событие загрузки игры
  1664. */
  1665. if (headers["X-Request-Id"] > 2 && !isLoadGame) {
  1666. isLoadGame = true;
  1667. await lib.load();
  1668. addControls();
  1669. addControlButtons();
  1670. addBottomUrls();
  1671.  
  1672. if (isChecked('sendExpedition')) {
  1673. checkExpedition();
  1674. }
  1675.  
  1676. getAutoGifts();
  1677.  
  1678. cheats.activateHacks();
  1679. justInfo();
  1680. if (isChecked('dailyQuests')) {
  1681. testDailyQuests();
  1682. }
  1683.  
  1684. if (isChecked('buyForGold')) {
  1685. buyInStoreForGold();
  1686. }
  1687. }
  1688. /**
  1689. * Outgoing request data processing
  1690. *
  1691. * Обработка данных исходящего запроса
  1692. */
  1693. sourceData = await checkChangeSend.call(this, sourceData, tempData);
  1694. /**
  1695. * Handling incoming request data
  1696. *
  1697. * Обработка данных входящего запроса
  1698. */
  1699. const oldReady = this.onreadystatechange;
  1700. this.onreadystatechange = async function (e) {
  1701. if (this.errorRequest) {
  1702. return oldReady.apply(this, arguments);
  1703. }
  1704. if(this.readyState == 4 && this.status == 200) {
  1705. isTextResponse = this.responseType === "text" || this.responseType === "";
  1706. let response = isTextResponse ? this.responseText : this.response;
  1707. requestHistory[this.uniqid].response = response;
  1708. /**
  1709. * Replacing incoming request data
  1710. *
  1711. * Заменна данных входящего запроса
  1712. */
  1713. if (isTextResponse) {
  1714. await checkChangeResponse.call(this, response);
  1715. }
  1716. /**
  1717. * A function to run after the request is executed
  1718. *
  1719. * Функция запускаемая после выполения запроса
  1720. */
  1721. if (typeof this.onReadySuccess == 'function') {
  1722. setTimeout(this.onReadySuccess, 500);
  1723. }
  1724. /** Удаляем из истории запросов битвы с боссом */
  1725. if ('invasion_bossStart' in requestHistory[this.uniqid].calls) delete requestHistory[this.uniqid];
  1726. }
  1727. if (oldReady) {
  1728. return oldReady.apply(this, arguments);
  1729. }
  1730. }
  1731. }
  1732. if (this.errorRequest) {
  1733. const oldReady = this.onreadystatechange;
  1734. this.onreadystatechange = function () {
  1735. Object.defineProperty(this, 'status', {
  1736. writable: true
  1737. });
  1738. this.status = 200;
  1739. Object.defineProperty(this, 'readyState', {
  1740. writable: true
  1741. });
  1742. this.readyState = 4;
  1743. Object.defineProperty(this, 'responseText', {
  1744. writable: true
  1745. });
  1746. this.responseText = JSON.stringify({
  1747. "result": true
  1748. });
  1749. if (typeof this.onReadySuccess == 'function') {
  1750. setTimeout(this.onReadySuccess, 500);
  1751. }
  1752. return oldReady.apply(this, arguments);
  1753. }
  1754. this.onreadystatechange();
  1755. } else {
  1756. try {
  1757. return original.send.call(this, sourceData);
  1758. } catch(e) {
  1759. debugger;
  1760. }
  1761. }
  1762. };
  1763. /**
  1764. * Processing and substitution of outgoing data
  1765. *
  1766. * Обработка и подмена исходящих данных
  1767. */
  1768. async function checkChangeSend(sourceData, tempData) {
  1769. try {
  1770. /**
  1771. * A function that replaces battle data with incorrect ones to cancel combatя
  1772. *
  1773. * Функция заменяющая данные боя на неверные для отмены боя
  1774. */
  1775. const fixBattle = function (heroes) {
  1776. for (const ids in heroes) {
  1777. hero = heroes[ids];
  1778. hero.energy = random(1, 999);
  1779. if (hero.hp > 0) {
  1780. hero.hp = random(1, hero.hp);
  1781. }
  1782. }
  1783. }
  1784. /**
  1785. * Dialog window 2
  1786. *
  1787. * Диалоговое окно 2
  1788. */
  1789. const showMsg = async function (msg, ansF, ansS) {
  1790. if (typeof popup == 'object') {
  1791. return await popup.confirm(msg, [
  1792. {msg: ansF, result: false},
  1793. {msg: ansS, result: true},
  1794. ]);
  1795. } else {
  1796. return !confirm(`${msg}\n ${ansF} (${I18N('BTN_OK')})\n ${ansS} (${I18N('BTN_CANCEL')})`);
  1797. }
  1798. }
  1799. /**
  1800. * Dialog window 3
  1801. *
  1802. * Диалоговое окно 3
  1803. */
  1804. const showMsgs = async function (msg, ansF, ansS, ansT) {
  1805. return await popup.confirm(msg, [
  1806. {msg: ansF, result: 0},
  1807. {msg: ansS, result: 1},
  1808. {msg: ansT, result: 2},
  1809. ]);
  1810. }
  1811.  
  1812. let changeRequest = false;
  1813. testData = JSON.parse(tempData);
  1814. for (const call of testData.calls) {
  1815. if (!artifactChestOpen) {
  1816. requestHistory[this.uniqid].calls[call.name] = call.ident;
  1817. }
  1818. /**
  1819. * Cancellation of the battle in adventures, on VG and with minions of Asgard
  1820. * Отмена боя в приключениях, на ВГ и с прислужниками Асгарда
  1821. */
  1822. if ((call.name == 'adventure_endBattle' ||
  1823. call.name == 'adventureSolo_endBattle' ||
  1824. call.name == 'clanWarEndBattle' &&
  1825. isChecked('cancelBattle') ||
  1826. call.name == 'crossClanWar_endBattle' &&
  1827. isChecked('cancelBattle') ||
  1828. call.name == 'brawl_endBattle' ||
  1829. call.name == 'towerEndBattle' ||
  1830. call.name == 'invasion_bossEnd' ||
  1831. call.name == 'bossEndBattle' ||
  1832. call.name == 'clanRaid_endNodeBattle') &&
  1833. isCancalBattle) {
  1834. nameFuncEndBattle = call.name;
  1835. if (!call.args.result.win) {
  1836. let resultPopup = false;
  1837. if (call.name == 'adventure_endBattle' ||
  1838. call.name == 'invasion_bossEnd' ||
  1839. call.name == 'bossEndBattle' ||
  1840. call.name == 'adventureSolo_endBattle') {
  1841. resultPopup = await showMsgs(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_CANCEL'), I18N('BTN_AUTO'));
  1842. } else if (call.name == 'clanWarEndBattle' ||
  1843. call.name == 'crossClanWar_endBattle') {
  1844. resultPopup = await showMsg(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_AUTO_F5'));
  1845. } else {
  1846. resultPopup = await showMsg(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_CANCEL'));
  1847. }
  1848. if (resultPopup) {
  1849. if (call.name == 'invasion_bossEnd') {
  1850. this.errorRequest = true;
  1851. }
  1852. fixBattle(call.args.progress[0].attackers.heroes);
  1853. fixBattle(call.args.progress[0].defenders.heroes);
  1854. changeRequest = true;
  1855. if (resultPopup > 1) {
  1856. this.onReadySuccess = testAutoBattle;
  1857. // setTimeout(bossBattle, 1000);
  1858. }
  1859. }
  1860. } else if (call.args.result.stars < 3 && call.name == 'towerEndBattle') {
  1861. resultPopup = await showMsg(I18N('LOST_HEROES'), I18N('BTN_OK'), I18N('BTN_CANCEL'), I18N('BTN_AUTO'));
  1862. if (resultPopup) {
  1863. fixBattle(call.args.progress[0].attackers.heroes);
  1864. fixBattle(call.args.progress[0].defenders.heroes);
  1865. changeRequest = true;
  1866. if (resultPopup > 1) {
  1867. this.onReadySuccess = testAutoBattle;
  1868. }
  1869. }
  1870. }
  1871. // Потасовки
  1872. if (isChecked('autoBrawls') && !isBrawlsAutoStart && call.name == 'brawl_endBattle') {
  1873. if (await popup.confirm(I18N('START_AUTO_BRAWLS'), [
  1874. { msg: I18N('BTN_NO'), result: false },
  1875. { msg: I18N('BTN_YES'), result: true },
  1876. ])) {
  1877. this.onReadySuccess = testBrawls;
  1878. isBrawlsAutoStart = true;
  1879. }
  1880. }
  1881. }
  1882. /**
  1883. * Save pack for Brawls
  1884. *
  1885. * Сохраняем пачку для потасовок
  1886. */
  1887. if (call.name == 'brawl_startBattle') {
  1888. console.log(JSON.stringify(call.args));
  1889. brawlsPack = call.args;
  1890. }
  1891. /**
  1892. * Canceled fight in Asgard
  1893. * Отмена боя в Асгарде
  1894. */
  1895. if (call.name == 'clanRaid_endBossBattle' &&
  1896. isCancalBossBattle &&
  1897. isChecked('cancelBattle')) {
  1898. bossDamage = call.args.progress[0].defenders.heroes[1].extra;
  1899. sumDamage = bossDamage.damageTaken + bossDamage.damageTakenNextLevel;
  1900. let resultPopup = await showMsgs(
  1901. `${I18N('MSG_YOU_APPLIED')} ${sumDamage.toLocaleString()} ${I18N('MSG_DAMAGE')}.`,
  1902. I18N('BTN_OK'), I18N('BTN_AUTO_F5'), I18N('MSG_CANCEL_AND_STAT'))
  1903. if (resultPopup) {
  1904. fixBattle(call.args.progress[0].attackers.heroes);
  1905. fixBattle(call.args.progress[0].defenders.heroes);
  1906. changeRequest = true;
  1907. if (resultPopup > 1) {
  1908. this.onReadySuccess = testBossBattle;
  1909. // setTimeout(bossBattle, 1000);
  1910. }
  1911. }
  1912. }
  1913. /**
  1914. * Save the Asgard Boss Attack Pack
  1915. * Сохраняем пачку для атаки босса Асгарда
  1916. */
  1917. if (call.name == 'clanRaid_startBossBattle') {
  1918. lastBossBattle = call.args;
  1919. }
  1920. /**
  1921. * Saving the request to start the last battle
  1922. * Сохранение запроса начала последнего боя
  1923. */
  1924. if (call.name == 'clanWarAttack' ||
  1925. call.name == 'crossClanWar_startBattle' ||
  1926. call.name == 'adventure_turnStartBattle' ||
  1927. call.name == 'bossAttack' ||
  1928. call.name == 'invasion_bossStart' ||
  1929. call.name == 'towerStartBattle') {
  1930. nameFuncStartBattle = call.name;
  1931. lastBattleArg = call.args;
  1932.  
  1933. if (call.name == 'invasion_bossStart') {
  1934. const timePassed = Date.now() - lastBossBattleStart;
  1935. if (timePassed < invasionTimer) {
  1936. await new Promise((e) => setTimeout(e, invasionTimer - timePassed));
  1937. }
  1938. invasionTimer -= 1;
  1939. }
  1940. lastBossBattleStart = Date.now();
  1941. }
  1942. if (call.name == 'invasion_bossEnd') {
  1943. const lastBattle = lastBattleInfo;
  1944. if (lastBattle && call.args.result.win) {
  1945. lastBattle.progress = call.args.progress;
  1946. const result = await Calc(lastBattle);
  1947. let timer = getTimer(result.battleTime, 1) + addBattleTimer;
  1948. const period = Math.ceil((Date.now() - lastBossBattleStart) / 1000);
  1949. console.log(timer, period);
  1950. if (period < timer) {
  1951. timer = timer - period;
  1952. await countdownTimer(timer);
  1953. }
  1954. }
  1955. }
  1956. /**
  1957. * Disable spending divination cards
  1958. * Отключить трату карт предсказаний
  1959. */
  1960. if (call.name == 'dungeonEndBattle') {
  1961. if (call.args.isRaid) {
  1962. if (countPredictionCard <= 0) {
  1963. delete call.args.isRaid;
  1964. changeRequest = true;
  1965. } else if (countPredictionCard > 0) {
  1966. countPredictionCard--;
  1967. }
  1968. }
  1969. console.log(`Cards: ${countPredictionCard}`);
  1970. /**
  1971. * Fix endless cards
  1972. * Исправление бесконечных карт
  1973. */
  1974. const lastBattle = lastDungeonBattleData;
  1975. if (lastBattle && !call.args.isRaid) {
  1976. if (changeRequest) {
  1977. lastBattle.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  1978. } else {
  1979. lastBattle.progress = call.args.progress;
  1980. }
  1981. const result = await Calc(lastBattle);
  1982.  
  1983. if (changeRequest) {
  1984. call.args.progress = result.progress;
  1985. call.args.result = result.result;
  1986. }
  1987. let timer = getTimer(result.battleTime) + addBattleTimer;
  1988. const period = Math.ceil((Date.now() - lastDungeonBattleStart) / 1000);
  1989. console.log(timer, period);
  1990. if (period < timer) {
  1991. timer = timer - period;
  1992. await countdownTimer(timer);
  1993. }
  1994. }
  1995. }
  1996. /**
  1997. * Quiz Answer
  1998. * Ответ на викторину
  1999. */
  2000. if (call.name == 'quizAnswer') {
  2001. /**
  2002. * Automatically changes the answer to the correct one if there is one.
  2003. * Автоматически меняет ответ на правильный если он есть
  2004. */
  2005. if (lastAnswer && isChecked('getAnswer')) {
  2006. call.args.answerId = lastAnswer;
  2007. lastAnswer = null;
  2008. changeRequest = true;
  2009. }
  2010. }
  2011. /**
  2012. * Present
  2013. * Подарки
  2014. */
  2015. if (call.name == 'freebieCheck') {
  2016. freebieCheckInfo = call;
  2017. }
  2018. /** missionTimer */
  2019. if (call.name == 'missionEnd' && missionBattle) {
  2020. missionBattle.progress = call.args.progress;
  2021. missionBattle.result = call.args.result;
  2022. const result = await Calc(missionBattle);
  2023.  
  2024. let timer = getTimer(result.battleTime) + addBattleTimer;
  2025. const period = Math.ceil((Date.now() - lastMissionBattleStart) / 1000);
  2026. if (period < timer) {
  2027. timer = timer - period;
  2028. await countdownTimer(timer);
  2029. }
  2030. missionBattle = null;
  2031. }
  2032. /**
  2033. * Getting mission data for auto-repeat
  2034. * Получение данных миссии для автоповтора
  2035. */
  2036. if (isChecked('repeatMission') &&
  2037. call.name == 'missionEnd') {
  2038. let missionInfo = {
  2039. id: call.args.id,
  2040. result: call.args.result,
  2041. heroes: call.args.progress[0].attackers.heroes,
  2042. count: 0,
  2043. }
  2044. setTimeout(async () => {
  2045. if (!isSendsMission && await popup.confirm(I18N('MSG_REPEAT_MISSION'), [
  2046. { msg: I18N('BTN_REPEAT'), result: true},
  2047. { msg: I18N('BTN_NO'), result: false},
  2048. ])) {
  2049. isStopSendMission = false;
  2050. isSendsMission = true;
  2051. sendsMission(missionInfo);
  2052. }
  2053. }, 0);
  2054. }
  2055. /**
  2056. * Getting mission data
  2057. * Получение данных миссии
  2058. * missionTimer
  2059. */
  2060. if (call.name == 'missionStart') {
  2061. lastMissionStart = call.args;
  2062. lastMissionBattleStart = Date.now();
  2063. }
  2064. /**
  2065. * Specify the quantity for Titan Orbs and Pet Eggs
  2066. * Указать количество для сфер титанов и яиц петов
  2067. */
  2068. if (isChecked('countControl') &&
  2069. (call.name == 'pet_chestOpen' ||
  2070. call.name == 'titanUseSummonCircle') &&
  2071. call.args.amount > 1) {
  2072. call.args.amount = 1;
  2073. const result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2074. { msg: I18N('BTN_OPEN'), isInput: true, default: call.args.amount},
  2075. ]);
  2076. if (result) {
  2077. call.args.amount = result;
  2078. changeRequest = true;
  2079. }
  2080. }
  2081. /**
  2082. * Specify the amount for keys and spheres of titan artifacts
  2083. * Указать колличество для ключей и сфер артефактов титанов
  2084. */
  2085. if (isChecked('countControl') &&
  2086. (call.name == 'artifactChestOpen' ||
  2087. call.name == 'titanArtifactChestOpen') &&
  2088. call.args.amount > 1 &&
  2089. call.args.free &&
  2090. !changeRequest) {
  2091. artifactChestOpenCallName = call.name;
  2092. let result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2093. { msg: I18N('BTN_OPEN'), isInput: true, default: call.args.amount },
  2094. ]);
  2095. if (result) {
  2096. let sphere = result < 10 ? 1 : 10;
  2097.  
  2098. call.args.amount = sphere;
  2099. result -= sphere;
  2100.  
  2101. for (let count = result; count > 0; count -= sphere) {
  2102. if (count < 10) sphere = 1;
  2103. const ident = artifactChestOpenCallName + "_" + count;
  2104. testData.calls.push({
  2105. name: artifactChestOpenCallName,
  2106. args: {
  2107. amount: sphere,
  2108. free: true,
  2109. },
  2110. ident: ident
  2111. });
  2112. if (!Array.isArray(requestHistory[this.uniqid].calls[call.name])) {
  2113. requestHistory[this.uniqid].calls[call.name] = [requestHistory[this.uniqid].calls[call.name]];
  2114. }
  2115. requestHistory[this.uniqid].calls[call.name].push(ident);
  2116. }
  2117.  
  2118. artifactChestOpen = true;
  2119. changeRequest = true;
  2120. }
  2121. }
  2122. if (call.name == 'consumableUseLootBox') {
  2123. lastRussianDollId = call.args.libId;
  2124. /**
  2125. * Specify quantity for gold caskets
  2126. * Указать количество для золотых шкатулок
  2127. */
  2128. if (isChecked('countControl') &&
  2129. call.args.libId == 148 &&
  2130. call.args.amount > 1) {
  2131. const result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2132. { msg: I18N('BTN_OPEN'), isInput: true, default: call.args.amount},
  2133. ]);
  2134. call.args.amount = result;
  2135. changeRequest = true;
  2136. }
  2137. }
  2138. /**
  2139. * Changing the maximum number of raids in the campaign
  2140. * Изменение максимального количества рейдов в кампании
  2141. */
  2142. // if (call.name == 'missionRaid') {
  2143. // if (isChecked('countControl') && call.args.times > 1) {
  2144. // const result = +(await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2145. // { msg: I18N('BTN_RUN'), isInput: true, default: call.args.times },
  2146. // ]));
  2147. // call.args.times = result > call.args.times ? call.args.times : result;
  2148. // changeRequest = true;
  2149. // }
  2150. // }
  2151. }
  2152.  
  2153. let headers = requestHistory[this.uniqid].headers;
  2154. if (changeRequest) {
  2155. sourceData = JSON.stringify(testData);
  2156. headers['X-Auth-Signature'] = getSignature(headers, sourceData);
  2157. }
  2158.  
  2159. let signature = headers['X-Auth-Signature'];
  2160. if (signature) {
  2161. original.setRequestHeader.call(this, 'X-Auth-Signature', signature);
  2162. }
  2163. } catch (err) {
  2164. console.log("Request(send, " + this.uniqid + "):\n", sourceData, "Error:\n", err);
  2165. }
  2166. return sourceData;
  2167. }
  2168. /**
  2169. * Processing and substitution of incoming data
  2170. *
  2171. * Обработка и подмена входящих данных
  2172. */
  2173. async function checkChangeResponse(response) {
  2174. try {
  2175. isChange = false;
  2176. let nowTime = Math.round(Date.now() / 1000);
  2177. callsIdent = requestHistory[this.uniqid].calls;
  2178. respond = JSON.parse(response);
  2179. /**
  2180. * If the request returned an error removes the error (removes synchronization errors)
  2181. * Если запрос вернул ошибку удаляет ошибку (убирает ошибки синхронизации)
  2182. */
  2183. if (respond.error) {
  2184. isChange = true;
  2185. console.error(respond.error);
  2186. if (isChecked('showErrors')) {
  2187. popup.confirm(I18N('ERROR_MSG', {
  2188. name: respond.error.name,
  2189. description: respond.error.description,
  2190. }));
  2191. }
  2192. delete respond.error;
  2193. respond.results = [];
  2194. }
  2195. let mainReward = null;
  2196. const allReward = {};
  2197. let countTypeReward = 0;
  2198. let readQuestInfo = false;
  2199. for (const call of respond.results) {
  2200. /**
  2201. * Obtaining initial data for completing quests
  2202. * Получение исходных данных для выполнения квестов
  2203. */
  2204. if (readQuestInfo) {
  2205. questsInfo[call.ident] = call.result.response;
  2206. }
  2207. /**
  2208. * Getting a user ID
  2209. * Получение идетификатора пользователя
  2210. */
  2211. if (call.ident == callsIdent['registration']) {
  2212. userId = call.result.response.userId;
  2213. if (localStorage['userId'] != userId) {
  2214. localStorage['newGiftSendIds'] = '';
  2215. localStorage['userId'] = userId;
  2216. }
  2217. await openOrMigrateDatabase(userId);
  2218. readQuestInfo = true;
  2219. }
  2220. /**
  2221. * Hiding donation offers 1
  2222. * Скрываем предложения доната 1
  2223. */
  2224. if (call.ident == callsIdent['billingGetAll'] && getSaveVal('noOfferDonat')) {
  2225. const billings = call.result.response?.billings;
  2226. const bundle = call.result.response?.bundle;
  2227. if (billings && bundle) {
  2228. call.result.response.billings = [];
  2229. call.result.response.bundle = [];
  2230. isChange = true;
  2231. }
  2232. }
  2233. /**
  2234. * Hiding donation offers 2
  2235. * Скрываем предложения доната 2
  2236. */
  2237. if (getSaveVal('noOfferDonat') &&
  2238. (call.ident == callsIdent['offerGetAll'] ||
  2239. call.ident == callsIdent['specialOffer_getAll'])) {
  2240. let offers = call.result.response;
  2241. if (offers) {
  2242. call.result.response = offers.filter(e => !['addBilling', 'bundleCarousel'].includes(e.type) || ['idleResource'].includes(e.offerType));
  2243. isChange = true;
  2244. }
  2245. }
  2246. /**
  2247. * Hiding donation offers 3
  2248. * Скрываем предложения доната 3
  2249. */
  2250. if (getSaveVal('noOfferDonat') && call.result?.bundleUpdate) {
  2251. delete call.result.bundleUpdate;
  2252. isChange = true;
  2253. }
  2254. /**
  2255. * Copies a quiz question to the clipboard
  2256. * Копирует вопрос викторины в буфер обмена и получает на него ответ если есть
  2257. */
  2258. if (call.ident == callsIdent['quizGetNewQuestion']) {
  2259. let quest = call.result.response;
  2260. console.log(quest.question);
  2261. copyText(quest.question);
  2262. setProgress(I18N('QUESTION_COPY'), true);
  2263. quest.lang = null;
  2264. if (typeof NXFlashVars !== 'undefined') {
  2265. quest.lang = NXFlashVars.interface_lang;
  2266. }
  2267. lastQuestion = quest;
  2268. if (isChecked('getAnswer')) {
  2269. const answer = await getAnswer(lastQuestion);
  2270. let showText = '';
  2271. if (answer) {
  2272. lastAnswer = answer;
  2273. console.log(answer);
  2274. showText = `${I18N('ANSWER_KNOWN')}: ${answer}`;
  2275. } else {
  2276. showText = I18N('ANSWER_NOT_KNOWN');
  2277. }
  2278.  
  2279. try {
  2280. const hint = hintQuest(quest);
  2281. if (hint) {
  2282. showText += I18N('HINT') + hint;
  2283. }
  2284. } catch(e) {}
  2285.  
  2286. setProgress(showText, true);
  2287. }
  2288. }
  2289. /**
  2290. * Submits a question with an answer to the database
  2291. * Отправляет вопрос с ответом в базу данных
  2292. */
  2293. if (call.ident == callsIdent['quizAnswer']) {
  2294. const answer = call.result.response;
  2295. if (lastQuestion) {
  2296. const answerInfo = {
  2297. answer,
  2298. question: lastQuestion,
  2299. lang: null,
  2300. }
  2301. if (typeof NXFlashVars !== 'undefined') {
  2302. answerInfo.lang = NXFlashVars.interface_lang;
  2303. }
  2304. lastQuestion = null;
  2305. setTimeout(sendAnswerInfo, 0, answerInfo);
  2306. }
  2307. }
  2308. /**
  2309. * Get user data
  2310. * Получить даныне пользователя
  2311. */
  2312. if (call.ident == callsIdent['userGetInfo']) {
  2313. let user = call.result.response;
  2314. userInfo = Object.assign({}, user);
  2315. delete userInfo.refillable;
  2316. if (!questsInfo['userGetInfo']) {
  2317. questsInfo['userGetInfo'] = user;
  2318. }
  2319. }
  2320. /**
  2321. * Start of the battle for recalculation
  2322. * Начало боя для прерасчета
  2323. */
  2324. if (call.ident == callsIdent['clanWarAttack'] ||
  2325. call.ident == callsIdent['crossClanWar_startBattle'] ||
  2326. call.ident == callsIdent['bossAttack'] ||
  2327. call.ident == callsIdent['battleGetReplay'] ||
  2328. call.ident == callsIdent['brawl_startBattle'] ||
  2329. call.ident == callsIdent['adventureSolo_turnStartBattle'] ||
  2330. call.ident == callsIdent['invasion_bossStart'] ||
  2331. call.ident == callsIdent['towerStartBattle'] ||
  2332. call.ident == callsIdent['adventure_turnStartBattle']) {
  2333. let battle = call.result.response.battle || call.result.response.replay;
  2334. if (call.ident == callsIdent['brawl_startBattle'] ||
  2335. call.ident == callsIdent['bossAttack'] ||
  2336. call.ident == callsIdent['towerStartBattle'] ||
  2337. call.ident == callsIdent['invasion_bossStart']) {
  2338. battle = call.result.response;
  2339. }
  2340. lastBattleInfo = battle;
  2341. if (!isChecked('preCalcBattle')) {
  2342. continue;
  2343. }
  2344. setProgress(I18N('BEING_RECALC'));
  2345. let battleDuration = 120;
  2346. try {
  2347. const typeBattle = getBattleType(battle.type);
  2348. battleDuration = +lib.data.battleConfig[typeBattle.split('_')[1]].config.battleDuration;
  2349. } catch (e) { }
  2350. //console.log(battle.type);
  2351. function getBattleInfo(battle, isRandSeed) {
  2352. return new Promise(function (resolve) {
  2353. if (isRandSeed) {
  2354. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  2355. }
  2356. BattleCalc(battle, getBattleType(battle.type), e => resolve(e));
  2357. });
  2358. }
  2359. let actions = [getBattleInfo(battle, false)]
  2360. const countTestBattle = getInput('countTestBattle');
  2361. if (call.ident == callsIdent['battleGetReplay']) {
  2362. battle.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  2363. }
  2364. for (let i = 0; i < countTestBattle; i++) {
  2365. actions.push(getBattleInfo(battle, true));
  2366. }
  2367. Promise.all(actions)
  2368. .then(e => {
  2369. e = e.map(n => ({win: n.result.win, time: n.battleTime}));
  2370. let firstBattle = e.shift();
  2371. const timer = Math.floor(battleDuration - firstBattle.time);
  2372. const min = ('00' + Math.floor(timer / 60)).slice(-2);
  2373. const sec = ('00' + Math.floor(timer - min * 60)).slice(-2);
  2374. const countWin = e.reduce((w, s) => w + s.win, 0);
  2375. 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)
  2376. });
  2377. }
  2378. /**
  2379. * Start of the Asgard boss fight
  2380. * Начало боя с боссом Асгарда
  2381. */
  2382. if (call.ident == callsIdent['clanRaid_startBossBattle']) {
  2383. lastBossBattleInfo = call.result.response.battle;
  2384. if (isChecked('preCalcBattle')) {
  2385. const result = await Calc(lastBossBattleInfo).then(e => e.progress[0].defenders.heroes[1].extra);
  2386. const bossDamage = result.damageTaken + result.damageTakenNextLevel;
  2387. setProgress(I18N('BOSS_DAMAGE') + bossDamage.toLocaleString(), false, hideProgress);
  2388. }
  2389. }
  2390. /**
  2391. * Cancel tutorial
  2392. * Отмена туториала
  2393. */
  2394. if (isCanceledTutorial && call.ident == callsIdent['tutorialGetInfo']) {
  2395. let chains = call.result.response.chains;
  2396. for (let n in chains) {
  2397. chains[n] = 9999;
  2398. }
  2399. isChange = true;
  2400. }
  2401. /**
  2402. * Opening keys and spheres of titan artifacts
  2403. * Открытие ключей и сфер артефактов титанов
  2404. */
  2405. if (artifactChestOpen &&
  2406. (call.ident == callsIdent[artifactChestOpenCallName] ||
  2407. (callsIdent[artifactChestOpenCallName] && callsIdent[artifactChestOpenCallName].includes(call.ident)))) {
  2408. let reward = call.result.response[artifactChestOpenCallName == 'artifactChestOpen' ? 'chestReward' : 'reward'];
  2409.  
  2410. reward.forEach(e => {
  2411. for (let f in e) {
  2412. if (!allReward[f]) {
  2413. allReward[f] = {};
  2414. }
  2415. for (let o in e[f]) {
  2416. if (!allReward[f][o]) {
  2417. allReward[f][o] = e[f][o];
  2418. countTypeReward++;
  2419. } else {
  2420. allReward[f][o] += e[f][o];
  2421. }
  2422. }
  2423. }
  2424. });
  2425.  
  2426. if (!call.ident.includes(artifactChestOpenCallName)) {
  2427. mainReward = call.result.response;
  2428. }
  2429. }
  2430.  
  2431. if (countTypeReward > 20) {
  2432. correctShowOpenArtifact = 3;
  2433. } else {
  2434. correctShowOpenArtifact = 0;
  2435. }
  2436. /**
  2437. * Sum the result of opening Pet Eggs
  2438. * Суммирование результата открытия яиц питомцев
  2439. */
  2440. if (isChecked('countControl') && call.ident == callsIdent['pet_chestOpen']) {
  2441. const rewards = call.result.response.rewards;
  2442. if (rewards.length > 10) {
  2443. /**
  2444. * Removing pet cards
  2445. * Убираем карточки петов
  2446. */
  2447. for (const reward of rewards) {
  2448. if (reward.petCard) {
  2449. delete reward.petCard;
  2450. }
  2451. }
  2452. }
  2453. rewards.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. } else {
  2462. allReward[f][o] += e[f][o];
  2463. }
  2464. }
  2465. }
  2466. });
  2467. call.result.response.rewards = [allReward];
  2468. isChange = true;
  2469. }
  2470. /**
  2471. * Removing titan cards
  2472. * Убираем карточки титанов
  2473. */
  2474. if (call.ident == callsIdent['titanUseSummonCircle']) {
  2475. if (call.result.response.rewards.length > 10) {
  2476. for (const reward of call.result.response.rewards) {
  2477. if (reward.titanCard) {
  2478. delete reward.titanCard;
  2479. }
  2480. }
  2481. isChange = true;
  2482. }
  2483. }
  2484. /**
  2485. * Auto-repeat opening matryoshkas
  2486. * АвтоПовтор открытия матрешек
  2487. */
  2488. if (isChecked('countControl') && call.ident == callsIdent['consumableUseLootBox']) {
  2489. let lootBox = call.result.response;
  2490. let newCount = 0;
  2491. for (let n of lootBox) {
  2492. if (n?.consumable && n.consumable[lastRussianDollId]) {
  2493. newCount += n.consumable[lastRussianDollId]
  2494. }
  2495. }
  2496. if (newCount && await popup.confirm(`${I18N('BTN_OPEN')} ${newCount} ${I18N('OPEN_DOLLS')}?`, [
  2497. { msg: I18N('BTN_OPEN'), result: true},
  2498. { msg: I18N('BTN_NO'), result: false},
  2499. ])) {
  2500. const recursionResult = await openRussianDolls(lastRussianDollId, newCount);
  2501. lootBox = [...lootBox, ...recursionResult];
  2502. }
  2503.  
  2504. /** Объединение результата лутбоксов */
  2505. const allLootBox = {};
  2506. lootBox.forEach(e => {
  2507. for (let f in e) {
  2508. if (!allLootBox[f]) {
  2509. if (typeof e[f] == 'object') {
  2510. allLootBox[f] = {};
  2511. } else {
  2512. allLootBox[f] = 0;
  2513. }
  2514. }
  2515. if (typeof e[f] == 'object') {
  2516. for (let o in e[f]) {
  2517. if (newCount && o == lastRussianDollId) {
  2518. continue;
  2519. }
  2520. if (!allLootBox[f][o]) {
  2521. allLootBox[f][o] = e[f][o];
  2522. } else {
  2523. allLootBox[f][o] += e[f][o];
  2524. }
  2525. }
  2526. } else {
  2527. allLootBox[f] += e[f];
  2528. }
  2529. }
  2530. });
  2531. /** Разбитие результата */
  2532. const output = [];
  2533. const maxCount = 5;
  2534. let currentObj = {};
  2535. let count = 0;
  2536. for (let f in allLootBox) {
  2537. if (!currentObj[f]) {
  2538. if (typeof allLootBox[f] == 'object') {
  2539. for (let o in allLootBox[f]) {
  2540. currentObj[f] ||= {}
  2541. if (!currentObj[f][o]) {
  2542. currentObj[f][o] = allLootBox[f][o];
  2543. count++;
  2544. if (count === maxCount) {
  2545. output.push(currentObj);
  2546. currentObj = {};
  2547. count = 0;
  2548. }
  2549. }
  2550. }
  2551. } else {
  2552. currentObj[f] = allLootBox[f];
  2553. count++;
  2554. if (count === maxCount) {
  2555. output.push(currentObj);
  2556. currentObj = {};
  2557. count = 0;
  2558. }
  2559. }
  2560. }
  2561. }
  2562. if (count > 0) {
  2563. output.push(currentObj);
  2564. }
  2565.  
  2566. console.log(output);
  2567. call.result.response = output;
  2568. isChange = true;
  2569. }
  2570. /**
  2571. * Dungeon recalculation (fix endless cards)
  2572. * Прерасчет подземки (исправление бесконечных карт)
  2573. */
  2574. if (call.ident == callsIdent['dungeonStartBattle']) {
  2575. lastDungeonBattleData = call.result.response;
  2576. lastDungeonBattleStart = Date.now();
  2577. }
  2578. /**
  2579. * Getting the number of prediction cards
  2580. * Получение количества карт предсказаний
  2581. */
  2582. if (call.ident == callsIdent['inventoryGet']) {
  2583. countPredictionCard = call.result.response.consumable[81] || 0;
  2584. }
  2585. /**
  2586. * Getting subscription status
  2587. * Получение состояния подписки
  2588. */
  2589. if (call.ident == callsIdent['subscriptionGetInfo']) {
  2590. const subscription = call.result.response.subscription;
  2591. if (subscription) {
  2592. subEndTime = subscription.endTime * 1000;
  2593. }
  2594. }
  2595. /**
  2596. * Getting prediction cards
  2597. * Получение карт предсказаний
  2598. */
  2599. if (call.ident == callsIdent['questFarm']) {
  2600. const consumable = call.result.response?.consumable;
  2601. if (consumable && consumable[81]) {
  2602. countPredictionCard += consumable[81];
  2603. console.log(`Cards: ${countPredictionCard}`);
  2604. }
  2605. }
  2606. /**
  2607. * Hiding extra servers
  2608. * Скрытие лишних серверов
  2609. */
  2610. if (call.ident == callsIdent['serverGetAll'] && isChecked('hideServers')) {
  2611. let servers = call.result.response.users.map(s => s.serverId)
  2612. call.result.response.servers = call.result.response.servers.filter(s => servers.includes(s.id));
  2613. isChange = true;
  2614. }
  2615. /**
  2616. * Displays player positions in the adventure
  2617. * Отображает позиции игроков в приключении
  2618. */
  2619. if (call.ident == callsIdent['adventure_getLobbyInfo']) {
  2620. const users = Object.values(call.result.response.users);
  2621. const mapIdent = call.result.response.mapIdent;
  2622. const adventureId = call.result.response.adventureId;
  2623. const maps = {
  2624. adv_strongford_3pl_hell: 9,
  2625. adv_valley_3pl_hell: 10,
  2626. adv_ghirwil_3pl_hell: 11,
  2627. adv_angels_3pl_hell: 12,
  2628. }
  2629. let msg = I18N('MAP') + (mapIdent in maps ? maps[mapIdent] : adventureId);
  2630. msg += '<br>' + I18N('PLAYER_POS');
  2631. for (const user of users) {
  2632. msg += `<br>${user.user.name} - ${user.currentNode}`;
  2633. }
  2634. setProgress(msg, false, hideProgress);
  2635. }
  2636. /**
  2637. * Automatic launch of a raid at the end of the adventure
  2638. * Автоматический запуск рейда при окончании приключения
  2639. */
  2640. if (call.ident == callsIdent['adventure_end']) {
  2641. autoRaidAdventure()
  2642. }
  2643. /** Удаление лавки редкостей */
  2644. if (call.ident == callsIdent['missionRaid']) {
  2645. if (call.result?.heroesMerchant) {
  2646. delete call.result.heroesMerchant;
  2647. isChange = true;
  2648. }
  2649. }
  2650. /** missionTimer */
  2651. if (call.ident == callsIdent['missionStart']) {
  2652. missionBattle = call.result.response;
  2653. }
  2654. }
  2655.  
  2656. if (mainReward && artifactChestOpen) {
  2657. console.log(allReward);
  2658. mainReward[artifactChestOpenCallName == 'artifactChestOpen' ? 'chestReward' : 'reward'] = [allReward];
  2659. artifactChestOpen = false;
  2660. artifactChestOpenCallName = '';
  2661. isChange = true;
  2662. }
  2663. } catch(err) {
  2664. console.log("Request(response, " + this.uniqid + "):\n", "Error:\n", response, err);
  2665. }
  2666.  
  2667. if (isChange) {
  2668. Object.defineProperty(this, 'responseText', {
  2669. writable: true
  2670. });
  2671. this.responseText = JSON.stringify(respond);
  2672. }
  2673. }
  2674.  
  2675. /**
  2676. * Request an answer to a question
  2677. *
  2678. * Запрос ответа на вопрос
  2679. */
  2680. async function getAnswer(question) {
  2681. const now = Date.now();
  2682. const body = JSON.stringify({ ...question, now });
  2683. const signature = window['\x73\x69\x67\x6e'](now);
  2684. return new Promise(resolve => {
  2685. fetch('https://zingery.ru/heroes/getAnswer.php', {
  2686. method: 'POST',
  2687. headers: {
  2688. 'X-Request-Signature': signature,
  2689. 'X-Script-Name': GM_info.script.name,
  2690. 'X-Script-Version': GM_info.script.version,
  2691. 'X-Script-Author': GM_info.script.author,
  2692. },
  2693. body,
  2694. }).then(
  2695. response => response.json()
  2696. ).then(
  2697. data => {
  2698. if (data.result) {
  2699. resolve(data.result);
  2700. } else {
  2701. resolve(false);
  2702. }
  2703. }
  2704. ).catch((error) => {
  2705. console.error(error);
  2706. resolve(false);
  2707. });
  2708. })
  2709. }
  2710.  
  2711. /**
  2712. * Submitting a question and answer to a database
  2713. *
  2714. * Отправка вопроса и ответа в базу данных
  2715. */
  2716. function sendAnswerInfo(answerInfo) {
  2717. fetch('https://zingery.ru/heroes/setAnswer.php', {
  2718. method: 'POST',
  2719. body: JSON.stringify(answerInfo)
  2720. }).then(
  2721. response => response.json()
  2722. ).then(
  2723. data => {
  2724. if (data.result) {
  2725. console.log(I18N('SENT_QUESTION'));
  2726. }
  2727. }
  2728. )
  2729. }
  2730.  
  2731. /**
  2732. * Returns the battle type by preset type
  2733. *
  2734. * Возвращает тип боя по типу пресета
  2735. */
  2736. function getBattleType(strBattleType) {
  2737. if (strBattleType.includes("invasion")) {
  2738. return "get_invasion";
  2739. }
  2740. if (strBattleType.includes("boss")) {
  2741. return "get_boss";
  2742. }
  2743. switch (strBattleType) {
  2744. case "invasion":
  2745. return "get_invasion";
  2746. case "titan_pvp_manual":
  2747. return "get_titanPvpManual";
  2748. case "titan_pvp":
  2749. return "get_titanPvp";
  2750. case "titan_clan_pvp":
  2751. case "clan_pvp_titan":
  2752. case "clan_global_pvp_titan":
  2753. case "brawl_titan":
  2754. case "challenge_titan":
  2755. return "get_titanClanPvp";
  2756. case "clan_raid": // Asgard Boss // Босс асгарда
  2757. case "adventure": // Adventures // Приключения
  2758. case "clan_global_pvp":
  2759. case "clan_pvp":
  2760. return "get_clanPvp";
  2761. case "dungeon_titan":
  2762. case "titan_tower":
  2763. return "get_titan";
  2764. case "tower":
  2765. case "clan_dungeon":
  2766. return "get_tower";
  2767. case "pve":
  2768. return "get_pve";
  2769. case "pvp_manual":
  2770. return "get_pvpManual";
  2771. case "grand":
  2772. case "arena":
  2773. case "pvp":
  2774. case "challenge":
  2775. return "get_pvp";
  2776. case "core":
  2777. return "get_core";
  2778. case "boss_10":
  2779. case "boss_11":
  2780. case "boss_12":
  2781. return "get_boss";
  2782. default:
  2783. return "get_clanPvp";
  2784. }
  2785. }
  2786. /**
  2787. * Returns the class name of the passed object
  2788. *
  2789. * Возвращает название класса переданного объекта
  2790. */
  2791. function getClass(obj) {
  2792. return {}.toString.call(obj).slice(8, -1);
  2793. }
  2794. /**
  2795. * Calculates the request signature
  2796. *
  2797. * Расчитывает сигнатуру запроса
  2798. */
  2799. this.getSignature = function(headers, data) {
  2800. const sign = {
  2801. signature: '',
  2802. length: 0,
  2803. add: function (text) {
  2804. this.signature += text;
  2805. if (this.length < this.signature.length) {
  2806. this.length = 3 * (this.signature.length + 1) >> 1;
  2807. }
  2808. },
  2809. }
  2810. sign.add(headers["X-Request-Id"]);
  2811. sign.add(':');
  2812. sign.add(headers["X-Auth-Token"]);
  2813. sign.add(':');
  2814. sign.add(headers["X-Auth-Session-Id"]);
  2815. sign.add(':');
  2816. sign.add(data);
  2817. sign.add(':');
  2818. sign.add('LIBRARY-VERSION=1');
  2819. sign.add('UNIQUE-SESSION-ID=' + headers["X-Env-Unique-Session-Id"]);
  2820.  
  2821. return md5(sign.signature);
  2822. }
  2823. /**
  2824. * Creates an interface
  2825. *
  2826. * Создает интерфейс
  2827. */
  2828. function createInterface() {
  2829. scriptMenu.init({
  2830. showMenu: true
  2831. });
  2832. scriptMenu.addHeader(GM_info.script.name, justInfo);
  2833. scriptMenu.addHeader('v' + GM_info.script.version);
  2834. }
  2835.  
  2836. function addControls() {
  2837. createInterface();
  2838. const checkboxDetails = scriptMenu.addDetails(I18N('SETTINGS'));
  2839. for (let name in checkboxes) {
  2840. if (checkboxes[name].hide) {
  2841. continue;
  2842. }
  2843. checkboxes[name].cbox = scriptMenu.addCheckbox(checkboxes[name].label, checkboxes[name].title, checkboxDetails);
  2844. /**
  2845. * Getting the state of checkboxes from storage
  2846. * Получаем состояние чекбоксов из storage
  2847. */
  2848. let val = storage.get(name, null);
  2849. if (val != null) {
  2850. checkboxes[name].cbox.checked = val;
  2851. } else {
  2852. storage.set(name, checkboxes[name].default);
  2853. checkboxes[name].cbox.checked = checkboxes[name].default;
  2854. }
  2855. /**
  2856. * Tracing the change event of the checkbox for writing to storage
  2857. * Отсеживание события изменения чекбокса для записи в storage
  2858. */
  2859. checkboxes[name].cbox.dataset['name'] = name;
  2860. checkboxes[name].cbox.addEventListener('change', async function (event) {
  2861. const nameCheckbox = this.dataset['name'];
  2862. /*
  2863. if (this.checked && nameCheckbox == 'cancelBattle') {
  2864. this.checked = false;
  2865. if (await popup.confirm(I18N('MSG_BAN_ATTENTION'), [
  2866. { msg: I18N('BTN_NO_I_AM_AGAINST'), result: true },
  2867. { msg: I18N('BTN_YES_I_AGREE'), result: false },
  2868. ])) {
  2869. return;
  2870. }
  2871. this.checked = true;
  2872. }
  2873. */
  2874. storage.set(nameCheckbox, this.checked);
  2875. })
  2876. }
  2877.  
  2878. const inputDetails = scriptMenu.addDetails(I18N('VALUES'));
  2879. for (let name in inputs) {
  2880. inputs[name].input = scriptMenu.addInputText(inputs[name].title, false, inputDetails);
  2881. /**
  2882. * Get inputText state from storage
  2883. * Получаем состояние inputText из storage
  2884. */
  2885. let val = storage.get(name, null);
  2886. if (val != null) {
  2887. inputs[name].input.value = val;
  2888. } else {
  2889. storage.set(name, inputs[name].default);
  2890. inputs[name].input.value = inputs[name].default;
  2891. }
  2892. /**
  2893. * Tracing a field change event for a record in storage
  2894. * Отсеживание события изменения поля для записи в storage
  2895. */
  2896. inputs[name].input.dataset['name'] = name;
  2897. inputs[name].input.addEventListener('input', function () {
  2898. const inputName = this.dataset['name'];
  2899. let value = +this.value;
  2900. if (!value || Number.isNaN(value)) {
  2901. value = storage.get(inputName, inputs[inputName].default);
  2902. inputs[name].input.value = value;
  2903. }
  2904. storage.set(inputName, value);
  2905. })
  2906. }
  2907. }
  2908.  
  2909. /**
  2910. * Sending a request
  2911. *
  2912. * Отправка запроса
  2913. */
  2914. function send(json, callback, pr) {
  2915. if (typeof json == 'string') {
  2916. json = JSON.parse(json);
  2917. }
  2918. for (const call of json.calls) {
  2919. if (!call?.context?.actionTs) {
  2920. call.context = {
  2921. actionTs: Math.floor(performance.now())
  2922. }
  2923. }
  2924. }
  2925. json = JSON.stringify(json);
  2926. /**
  2927. * We get the headlines of the previous intercepted request
  2928. * Получаем заголовки предыдущего перехваченого запроса
  2929. */
  2930. let headers = lastHeaders;
  2931. /**
  2932. * We increase the header of the query Certifier by 1
  2933. * Увеличиваем заголовок идетификатора запроса на 1
  2934. */
  2935. headers["X-Request-Id"]++;
  2936. /**
  2937. * We calculate the title with the signature
  2938. * Расчитываем заголовок с сигнатурой
  2939. */
  2940. headers["X-Auth-Signature"] = getSignature(headers, json);
  2941. /**
  2942. * Create a new ajax request
  2943. * Создаем новый AJAX запрос
  2944. */
  2945. let xhr = new XMLHttpRequest;
  2946. /**
  2947. * Indicate the previously saved URL for API queries
  2948. * Указываем ранее сохраненный URL для API запросов
  2949. */
  2950. xhr.open('POST', apiUrl, true);
  2951. /**
  2952. * Add the function to the event change event
  2953. * Добавляем функцию к событию смены статуса запроса
  2954. */
  2955. xhr.onreadystatechange = function() {
  2956. /**
  2957. * If the result of the request is obtained, we call the flask function
  2958. * Если результат запроса получен вызываем колбек функцию
  2959. */
  2960. if(xhr.readyState == 4) {
  2961. callback(xhr.response, pr);
  2962. }
  2963. };
  2964. /**
  2965. * Indicate the type of request
  2966. * Указываем тип запроса
  2967. */
  2968. xhr.responseType = 'json';
  2969. /**
  2970. * We set the request headers
  2971. * Задаем заголовки запроса
  2972. */
  2973. for(let nameHeader in headers) {
  2974. let head = headers[nameHeader];
  2975. xhr.setRequestHeader(nameHeader, head);
  2976. }
  2977. /**
  2978. * Sending a request
  2979. * Отправляем запрос
  2980. */
  2981. xhr.send(json);
  2982. }
  2983.  
  2984. let hideTimeoutProgress = 0;
  2985. /**
  2986. * Hide progress
  2987. *
  2988. * Скрыть прогресс
  2989. */
  2990. function hideProgress(timeout) {
  2991. timeout = timeout || 0;
  2992. clearTimeout(hideTimeoutProgress);
  2993. hideTimeoutProgress = setTimeout(function () {
  2994. scriptMenu.setStatus('');
  2995. }, timeout);
  2996. }
  2997. /**
  2998. * Progress display
  2999. *
  3000. * Отображение прогресса
  3001. */
  3002. function setProgress(text, hide, onclick) {
  3003. scriptMenu.setStatus(text, onclick);
  3004. hide = hide || false;
  3005. if (hide) {
  3006. hideProgress(3000);
  3007. }
  3008. }
  3009.  
  3010. /**
  3011. * Returns the timer value depending on the subscription
  3012. *
  3013. * Возвращает значение таймера в зависимости от подписки
  3014. */
  3015. function getTimer(time, div) {
  3016. let speedDiv = 5;
  3017. if (subEndTime < Date.now()) {
  3018. speedDiv = div || 1.5;
  3019. }
  3020. return Math.max(Math.ceil(time / speedDiv + 1.5), 4);
  3021. }
  3022.  
  3023. /**
  3024. * Calculates HASH MD5 from string
  3025. *
  3026. * Расчитывает HASH MD5 из строки
  3027. *
  3028. * [js-md5]{@link https://github.com/emn178/js-md5}
  3029. *
  3030. * @namespace md5
  3031. * @version 0.7.3
  3032. * @author Chen, Yi-Cyuan [emn178@gmail.com]
  3033. * @copyright Chen, Yi-Cyuan 2014-2017
  3034. * @license MIT
  3035. */
  3036. !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 _}))}();
  3037.  
  3038. /**
  3039. * Script for beautiful dialog boxes
  3040. *
  3041. * Скрипт для красивых диалоговых окошек
  3042. */
  3043. const popup = new (function () {
  3044. this.popUp,
  3045. this.downer,
  3046. this.middle,
  3047. this.msgText,
  3048. this.buttons = [];
  3049. this.checkboxes = [];
  3050. this.dialogPromice = null;
  3051.  
  3052. function init() {
  3053. addStyle();
  3054. addBlocks();
  3055. addEventListeners();
  3056. }
  3057.  
  3058. const addEventListeners = () => {
  3059. document.addEventListener('keyup', (e) => {
  3060. if (e.key == 'Escape') {
  3061. if (this.dialogPromice) {
  3062. const { func, result } = this.dialogPromice;
  3063. this.dialogPromice = null;
  3064. popup.hide();
  3065. func(result);
  3066. }
  3067. }
  3068. });
  3069. }
  3070.  
  3071. const addStyle = () => {
  3072. let style = document.createElement('style');
  3073. style.innerText = `
  3074. .PopUp_ {
  3075. position: absolute;
  3076. min-width: 300px;
  3077. max-width: 500px;
  3078. max-height: 600px;
  3079. background-color: #190e08e6;
  3080. z-index: 10001;
  3081. top: 169px;
  3082. left: 345px;
  3083. border: 3px #ce9767 solid;
  3084. border-radius: 10px;
  3085. display: flex;
  3086. flex-direction: column;
  3087. justify-content: space-around;
  3088. padding: 15px 9px;
  3089. box-sizing: border-box;
  3090. }
  3091.  
  3092. .PopUp_back {
  3093. position: absolute;
  3094. background-color: #00000066;
  3095. width: 100%;
  3096. height: 100%;
  3097. z-index: 10000;
  3098. top: 0;
  3099. left: 0;
  3100. }
  3101.  
  3102. .PopUp_close {
  3103. width: 40px;
  3104. height: 40px;
  3105. position: absolute;
  3106. right: -18px;
  3107. top: -18px;
  3108. border: 3px solid #c18550;
  3109. border-radius: 20px;
  3110. background: radial-gradient(circle, rgba(190,30,35,1) 0%, rgba(0,0,0,1) 100%);
  3111. background-position-y: 3px;
  3112. box-shadow: -1px 1px 3px black;
  3113. cursor: pointer;
  3114. box-sizing: border-box;
  3115. }
  3116.  
  3117. .PopUp_close:hover {
  3118. filter: brightness(1.2);
  3119. }
  3120.  
  3121. .PopUp_crossClose {
  3122. width: 100%;
  3123. height: 100%;
  3124. background-size: 65%;
  3125. background-position: center;
  3126. background-repeat: no-repeat;
  3127. 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")
  3128. }
  3129.  
  3130. .PopUp_blocks {
  3131. width: 100%;
  3132. height: 50%;
  3133. display: flex;
  3134. justify-content: space-evenly;
  3135. align-items: center;
  3136. flex-wrap: wrap;
  3137. justify-content: center;
  3138. }
  3139.  
  3140. .PopUp_blocks:last-child {
  3141. margin-top: 25px;
  3142. }
  3143.  
  3144. .PopUp_buttons {
  3145. display: flex;
  3146. margin: 7px 10px;
  3147. flex-direction: column;
  3148. }
  3149.  
  3150. .PopUp_button {
  3151. background-color: #52A81C;
  3152. border-radius: 5px;
  3153. box-shadow: inset 0px -4px 10px, inset 0px 3px 2px #99fe20, 0px 0px 4px, 0px -3px 1px #d7b275, 0px 0px 0px 3px #ce9767;
  3154. cursor: pointer;
  3155. padding: 4px 12px 6px;
  3156. }
  3157.  
  3158. .PopUp_input {
  3159. text-align: center;
  3160. font-size: 16px;
  3161. height: 27px;
  3162. border: 1px solid #cf9250;
  3163. border-radius: 9px 9px 0px 0px;
  3164. background: transparent;
  3165. color: #fce1ac;
  3166. padding: 1px 10px;
  3167. box-sizing: border-box;
  3168. box-shadow: 0px 0px 4px, 0px 0px 0px 3px #ce9767;
  3169. }
  3170.  
  3171. .PopUp_checkboxes {
  3172. display: flex;
  3173. flex-direction: column;
  3174. margin: 15px 15px -5px 15px;
  3175. align-items: flex-start;
  3176. }
  3177.  
  3178. .PopUp_ContCheckbox {
  3179. margin: 2px 0px;
  3180. }
  3181.  
  3182. .PopUp_checkbox {
  3183. position: absolute;
  3184. z-index: -1;
  3185. opacity: 0;
  3186. }
  3187. .PopUp_checkbox+label {
  3188. display: inline-flex;
  3189. align-items: center;
  3190. user-select: none;
  3191.  
  3192. font-size: 15px;
  3193. font-family: sans-serif;
  3194. font-weight: 600;
  3195. font-stretch: condensed;
  3196. letter-spacing: 1px;
  3197. color: #fce1ac;
  3198. text-shadow: 0px 0px 1px;
  3199. }
  3200. .PopUp_checkbox+label::before {
  3201. content: '';
  3202. display: inline-block;
  3203. width: 20px;
  3204. height: 20px;
  3205. border: 1px solid #cf9250;
  3206. border-radius: 7px;
  3207. margin-right: 7px;
  3208. }
  3209. .PopUp_checkbox:checked+label::before {
  3210. 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");
  3211. }
  3212.  
  3213. .PopUp_input::placeholder {
  3214. color: #fce1ac75;
  3215. }
  3216.  
  3217. .PopUp_input:focus {
  3218. outline: 0;
  3219. }
  3220.  
  3221. .PopUp_input + .PopUp_button {
  3222. border-radius: 0px 0px 5px 5px;
  3223. padding: 2px 18px 5px;
  3224. }
  3225.  
  3226. .PopUp_button:hover {
  3227. filter: brightness(1.2);
  3228. }
  3229.  
  3230. .PopUp_button:active {
  3231. box-shadow: inset 0px 5px 10px, inset 0px 1px 2px #99fe20, 0px 0px 4px, 0px -3px 1px #d7b275, 0px 0px 0px 3px #ce9767;
  3232. }
  3233.  
  3234. .PopUp_text {
  3235. font-size: 22px;
  3236. font-family: sans-serif;
  3237. font-weight: 600;
  3238. font-stretch: condensed;
  3239. letter-spacing: 1px;
  3240. text-align: center;
  3241. }
  3242.  
  3243. .PopUp_buttonText {
  3244. color: #E4FF4C;
  3245. text-shadow: 0px 1px 2px black;
  3246. }
  3247.  
  3248. .PopUp_msgText {
  3249. color: #FDE5B6;
  3250. text-shadow: 0px 0px 2px;
  3251. }
  3252.  
  3253. .PopUp_hideBlock {
  3254. display: none;
  3255. }
  3256. `;
  3257. document.head.appendChild(style);
  3258. }
  3259.  
  3260. const addBlocks = () => {
  3261. this.back = document.createElement('div');
  3262. this.back.classList.add('PopUp_back');
  3263. this.back.classList.add('PopUp_hideBlock');
  3264. document.body.append(this.back);
  3265.  
  3266. this.popUp = document.createElement('div');
  3267. this.popUp.classList.add('PopUp_');
  3268. this.back.append(this.popUp);
  3269.  
  3270. let upper = document.createElement('div')
  3271. upper.classList.add('PopUp_blocks');
  3272. this.popUp.append(upper);
  3273.  
  3274. this.middle = document.createElement('div')
  3275. this.middle.classList.add('PopUp_blocks');
  3276. this.middle.classList.add('PopUp_checkboxes');
  3277. this.popUp.append(this.middle);
  3278.  
  3279. this.downer = document.createElement('div')
  3280. this.downer.classList.add('PopUp_blocks');
  3281. this.popUp.append(this.downer);
  3282.  
  3283. this.msgText = document.createElement('div');
  3284. this.msgText.classList.add('PopUp_text', 'PopUp_msgText');
  3285. upper.append(this.msgText);
  3286. }
  3287.  
  3288. this.showBack = function () {
  3289. this.back.classList.remove('PopUp_hideBlock');
  3290. }
  3291.  
  3292. this.hideBack = function () {
  3293. this.back.classList.add('PopUp_hideBlock');
  3294. }
  3295.  
  3296. this.show = function () {
  3297. if (this.checkboxes.length) {
  3298. this.middle.classList.remove('PopUp_hideBlock');
  3299. }
  3300. this.showBack();
  3301. this.popUp.classList.remove('PopUp_hideBlock');
  3302. this.popUp.style.left = (window.innerWidth - this.popUp.offsetWidth) / 2 + 'px';
  3303. this.popUp.style.top = (window.innerHeight - this.popUp.offsetHeight) / 3 + 'px';
  3304. }
  3305.  
  3306. this.hide = function () {
  3307. this.hideBack();
  3308. this.popUp.classList.add('PopUp_hideBlock');
  3309. }
  3310.  
  3311. this.addAnyButton = (option) => {
  3312. const contButton = document.createElement('div');
  3313. contButton.classList.add('PopUp_buttons');
  3314. this.downer.append(contButton);
  3315.  
  3316. let inputField = {
  3317. value: option.result || option.default
  3318. }
  3319. if (option.isInput) {
  3320. inputField = document.createElement('input');
  3321. inputField.type = 'text';
  3322. if (option.placeholder) {
  3323. inputField.placeholder = option.placeholder;
  3324. }
  3325. if (option.default) {
  3326. inputField.value = option.default;
  3327. }
  3328. inputField.classList.add('PopUp_input');
  3329. contButton.append(inputField);
  3330. }
  3331.  
  3332. const button = document.createElement('div');
  3333. button.classList.add('PopUp_button');
  3334. button.title = option.title || '';
  3335. contButton.append(button);
  3336.  
  3337. const buttonText = document.createElement('div');
  3338. buttonText.classList.add('PopUp_text', 'PopUp_buttonText');
  3339. buttonText.innerText = option.msg;
  3340. button.append(buttonText);
  3341.  
  3342. return { button, contButton, inputField };
  3343. }
  3344.  
  3345. this.addCloseButton = () => {
  3346. let button = document.createElement('div')
  3347. button.classList.add('PopUp_close');
  3348. this.popUp.append(button);
  3349.  
  3350. let crossClose = document.createElement('div')
  3351. crossClose.classList.add('PopUp_crossClose');
  3352. button.append(crossClose);
  3353.  
  3354. return { button, contButton: button };
  3355. }
  3356.  
  3357. this.addButton = (option, buttonClick) => {
  3358.  
  3359. const { button, contButton, inputField } = option.isClose ? this.addCloseButton() : this.addAnyButton(option);
  3360. if (option.isClose) {
  3361. this.dialogPromice = {func: buttonClick, result: option.result};
  3362. }
  3363. button.addEventListener('click', () => {
  3364. let result = '';
  3365. if (option.isInput) {
  3366. result = inputField.value;
  3367. }
  3368. if (option.isClose || option.isCancel) {
  3369. this.dialogPromice = null;
  3370. }
  3371. buttonClick(result);
  3372. });
  3373.  
  3374. this.buttons.push(contButton);
  3375. }
  3376.  
  3377. this.clearButtons = () => {
  3378. while (this.buttons.length) {
  3379. this.buttons.pop().remove();
  3380. }
  3381. }
  3382.  
  3383. this.addCheckBox = (checkBox) => {
  3384. const contCheckbox = document.createElement('div');
  3385. contCheckbox.classList.add('PopUp_ContCheckbox');
  3386. this.middle.append(contCheckbox);
  3387.  
  3388. const checkbox = document.createElement('input');
  3389. checkbox.type = 'checkbox';
  3390. checkbox.id = 'PopUpCheckbox' + this.checkboxes.length;
  3391. checkbox.dataset.name = checkBox.name;
  3392. checkbox.checked = checkBox.checked;
  3393. checkbox.label = checkBox.label;
  3394. checkbox.title = checkBox.title || '';
  3395. checkbox.classList.add('PopUp_checkbox');
  3396. contCheckbox.appendChild(checkbox)
  3397.  
  3398. const checkboxLabel = document.createElement('label');
  3399. checkboxLabel.innerText = checkBox.label;
  3400. checkboxLabel.title = checkBox.title || '';
  3401. checkboxLabel.setAttribute('for', checkbox.id);
  3402. contCheckbox.appendChild(checkboxLabel);
  3403.  
  3404. this.checkboxes.push(checkbox);
  3405. }
  3406.  
  3407. this.clearCheckBox = () => {
  3408. this.middle.classList.add('PopUp_hideBlock');
  3409. while (this.checkboxes.length) {
  3410. this.checkboxes.pop().parentNode.remove();
  3411. }
  3412. }
  3413.  
  3414. this.setMsgText = (text) => {
  3415. this.msgText.innerHTML = text;
  3416. }
  3417.  
  3418. this.getCheckBoxes = () => {
  3419. const checkBoxes = [];
  3420.  
  3421. for (const checkBox of this.checkboxes) {
  3422. checkBoxes.push({
  3423. name: checkBox.dataset.name,
  3424. label: checkBox.label,
  3425. checked: checkBox.checked
  3426. });
  3427. }
  3428.  
  3429. return checkBoxes;
  3430. }
  3431.  
  3432. this.confirm = async (msg, buttOpt, checkBoxes = []) => {
  3433. this.clearButtons();
  3434. this.clearCheckBox();
  3435. return new Promise((complete, failed) => {
  3436. this.setMsgText(msg);
  3437. if (!buttOpt) {
  3438. buttOpt = [{ msg: 'Ok', result: true, isInput: false }];
  3439. }
  3440. for (const checkBox of checkBoxes) {
  3441. this.addCheckBox(checkBox);
  3442. }
  3443. for (let butt of buttOpt) {
  3444. this.addButton(butt, (result) => {
  3445. result = result || butt.result;
  3446. complete(result);
  3447. popup.hide();
  3448. });
  3449. if (butt.isCancel) {
  3450. this.dialogPromice = {func: complete, result: butt.result};
  3451. }
  3452. }
  3453. this.show();
  3454. });
  3455. }
  3456.  
  3457. document.addEventListener('DOMContentLoaded', init);
  3458. });
  3459.  
  3460. /**
  3461. * Script control panel
  3462. *
  3463. * Панель управления скриптом
  3464. */
  3465. const scriptMenu = new (function () {
  3466.  
  3467. this.mainMenu,
  3468. this.buttons = [],
  3469. this.checkboxes = [];
  3470. this.option = {
  3471. showMenu: false,
  3472. showDetails: {}
  3473. };
  3474.  
  3475. this.init = function (option = {}) {
  3476. this.option = Object.assign(this.option, option);
  3477. this.option.showDetails = this.loadShowDetails();
  3478. addStyle();
  3479. addBlocks();
  3480. }
  3481.  
  3482. const addStyle = () => {
  3483. style = document.createElement('style');
  3484. style.innerText = `
  3485. .scriptMenu_status {
  3486. position: absolute;
  3487. z-index: 10001;
  3488. /* max-height: 30px; */
  3489. top: -1px;
  3490. left: 30%;
  3491. cursor: pointer;
  3492. border-radius: 0px 0px 10px 10px;
  3493. background: #190e08e6;
  3494. border: 1px #ce9767 solid;
  3495. font-size: 18px;
  3496. font-family: sans-serif;
  3497. font-weight: 600;
  3498. font-stretch: condensed;
  3499. letter-spacing: 1px;
  3500. color: #fce1ac;
  3501. text-shadow: 0px 0px 1px;
  3502. transition: 0.5s;
  3503. padding: 2px 10px 3px;
  3504. }
  3505. .scriptMenu_statusHide {
  3506. top: -35px;
  3507. height: 30px;
  3508. overflow: hidden;
  3509. }
  3510. .scriptMenu_label {
  3511. position: absolute;
  3512. top: 30%;
  3513. left: -4px;
  3514. z-index: 9999;
  3515. cursor: pointer;
  3516. width: 30px;
  3517. height: 30px;
  3518. background: radial-gradient(circle, #47a41b 0%, #1a2f04 100%);
  3519. border: 1px solid #1a2f04;
  3520. border-radius: 5px;
  3521. box-shadow:
  3522. inset 0px 2px 4px #83ce26,
  3523. inset 0px -4px 6px #1a2f04,
  3524. 0px 0px 2px black,
  3525. 0px 0px 0px 2px #ce9767;
  3526. }
  3527. .scriptMenu_label:hover {
  3528. filter: brightness(1.2);
  3529. }
  3530. .scriptMenu_arrowLabel {
  3531. width: 100%;
  3532. height: 100%;
  3533. background-size: 75%;
  3534. background-position: center;
  3535. background-repeat: no-repeat;
  3536. 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");
  3537. box-shadow: 0px 1px 2px #000;
  3538. border-radius: 5px;
  3539. filter: drop-shadow(0px 1px 2px #000D);
  3540. }
  3541. .scriptMenu_main {
  3542. position: absolute;
  3543. max-width: 285px;
  3544. z-index: 9999;
  3545. top: 50%;
  3546. transform: translateY(-40%);
  3547. background: #190e08e6;
  3548. border: 1px #ce9767 solid;
  3549. border-radius: 0px 10px 10px 0px;
  3550. border-left: none;
  3551. padding: 5px 10px 5px 5px;
  3552. box-sizing: border-box;
  3553. font-size: 15px;
  3554. font-family: sans-serif;
  3555. font-weight: 600;
  3556. font-stretch: condensed;
  3557. letter-spacing: 1px;
  3558. color: #fce1ac;
  3559. text-shadow: 0px 0px 1px;
  3560. transition: 1s;
  3561. display: flex;
  3562. flex-direction: column;
  3563. flex-wrap: nowrap;
  3564. }
  3565. .scriptMenu_showMenu {
  3566. display: none;
  3567. }
  3568. .scriptMenu_showMenu:checked~.scriptMenu_main {
  3569. left: 0px;
  3570. }
  3571. .scriptMenu_showMenu:not(:checked)~.scriptMenu_main {
  3572. left: -300px;
  3573. }
  3574. .scriptMenu_divInput {
  3575. margin: 2px;
  3576. }
  3577. .scriptMenu_divInputText {
  3578. margin: 2px;
  3579. align-self: center;
  3580. display: flex;
  3581. }
  3582. .scriptMenu_checkbox {
  3583. position: absolute;
  3584. z-index: -1;
  3585. opacity: 0;
  3586. }
  3587. .scriptMenu_checkbox+label {
  3588. display: inline-flex;
  3589. align-items: center;
  3590. user-select: none;
  3591. }
  3592. .scriptMenu_checkbox+label::before {
  3593. content: '';
  3594. display: inline-block;
  3595. width: 20px;
  3596. height: 20px;
  3597. border: 1px solid #cf9250;
  3598. border-radius: 7px;
  3599. margin-right: 7px;
  3600. }
  3601. .scriptMenu_checkbox:checked+label::before {
  3602. 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");
  3603. }
  3604. .scriptMenu_close {
  3605. width: 40px;
  3606. height: 40px;
  3607. position: absolute;
  3608. right: -18px;
  3609. top: -18px;
  3610. border: 3px solid #c18550;
  3611. border-radius: 20px;
  3612. background: radial-gradient(circle, rgba(190,30,35,1) 0%, rgba(0,0,0,1) 100%);
  3613. background-position-y: 3px;
  3614. box-shadow: -1px 1px 3px black;
  3615. cursor: pointer;
  3616. box-sizing: border-box;
  3617. }
  3618. .scriptMenu_close:hover {
  3619. filter: brightness(1.2);
  3620. }
  3621. .scriptMenu_crossClose {
  3622. width: 100%;
  3623. height: 100%;
  3624. background-size: 65%;
  3625. background-position: center;
  3626. background-repeat: no-repeat;
  3627. 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")
  3628. }
  3629. .scriptMenu_button {
  3630. user-select: none;
  3631. border-radius: 5px;
  3632. cursor: pointer;
  3633. padding: 5px 14px 8px;
  3634. margin: 4px;
  3635. background: radial-gradient(circle, rgba(165,120,56,1) 80%, rgba(0,0,0,1) 110%);
  3636. box-shadow: inset 0px -4px 6px #442901, inset 0px 1px 6px #442901, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 2px #ce9767;
  3637. }
  3638. .scriptMenu_button:hover {
  3639. filter: brightness(1.2);
  3640. }
  3641. .scriptMenu_button:active {
  3642. box-shadow: inset 0px 4px 6px #442901, inset 0px 4px 6px #442901, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 2px #ce9767;
  3643. }
  3644. .scriptMenu_buttonText {
  3645. color: #fce5b7;
  3646. text-shadow: 0px 1px 2px black;
  3647. text-align: center;
  3648. }
  3649. .scriptMenu_header {
  3650. text-align: center;
  3651. align-self: center;
  3652. font-size: 15px;
  3653. margin: 0px 15px;
  3654. }
  3655. .scriptMenu_header a {
  3656. color: #fce5b7;
  3657. text-decoration: none;
  3658. }
  3659. .scriptMenu_InputText {
  3660. text-align: center;
  3661. width: 130px;
  3662. height: 24px;
  3663. border: 1px solid #cf9250;
  3664. border-radius: 9px;
  3665. background: transparent;
  3666. color: #fce1ac;
  3667. padding: 0px 10px;
  3668. box-sizing: border-box;
  3669. }
  3670. .scriptMenu_InputText:focus {
  3671. filter: brightness(1.2);
  3672. outline: 0;
  3673. }
  3674. .scriptMenu_InputText::placeholder {
  3675. color: #fce1ac75;
  3676. }
  3677. .scriptMenu_Summary {
  3678. cursor: pointer;
  3679. margin-left: 7px;
  3680. }
  3681. .scriptMenu_Details {
  3682. align-self: center;
  3683. }
  3684. `;
  3685. document.head.appendChild(style);
  3686. }
  3687.  
  3688. const addBlocks = () => {
  3689. const main = document.createElement('div');
  3690. document.body.appendChild(main);
  3691.  
  3692. this.status = document.createElement('div');
  3693. this.status.classList.add('scriptMenu_status');
  3694. this.setStatus('');
  3695. main.appendChild(this.status);
  3696.  
  3697. const label = document.createElement('label');
  3698. label.classList.add('scriptMenu_label');
  3699. label.setAttribute('for', 'checkbox_showMenu');
  3700. main.appendChild(label);
  3701.  
  3702. const arrowLabel = document.createElement('div');
  3703. arrowLabel.classList.add('scriptMenu_arrowLabel');
  3704. label.appendChild(arrowLabel);
  3705.  
  3706. const checkbox = document.createElement('input');
  3707. checkbox.type = 'checkbox';
  3708. checkbox.id = 'checkbox_showMenu';
  3709. checkbox.checked = this.option.showMenu;
  3710. checkbox.classList.add('scriptMenu_showMenu');
  3711. main.appendChild(checkbox);
  3712.  
  3713. this.mainMenu = document.createElement('div');
  3714. this.mainMenu.classList.add('scriptMenu_main');
  3715. main.appendChild(this.mainMenu);
  3716.  
  3717. const closeButton = document.createElement('label');
  3718. closeButton.classList.add('scriptMenu_close');
  3719. closeButton.setAttribute('for', 'checkbox_showMenu');
  3720. this.mainMenu.appendChild(closeButton);
  3721.  
  3722. const crossClose = document.createElement('div');
  3723. crossClose.classList.add('scriptMenu_crossClose');
  3724. closeButton.appendChild(crossClose);
  3725. }
  3726.  
  3727. this.setStatus = (text, onclick) => {
  3728. if (!text) {
  3729. this.status.classList.add('scriptMenu_statusHide');
  3730. } else {
  3731. this.status.classList.remove('scriptMenu_statusHide');
  3732. this.status.innerHTML = text;
  3733. }
  3734.  
  3735. if (typeof onclick == 'function') {
  3736. this.status.addEventListener("click", onclick, {
  3737. once: true
  3738. });
  3739. }
  3740. }
  3741.  
  3742. /**
  3743. * Adding a text element
  3744. *
  3745. * Добавление текстового элемента
  3746. * @param {String} text text // текст
  3747. * @param {Function} func Click function // функция по клику
  3748. * @param {HTMLDivElement} main parent // родитель
  3749. */
  3750. this.addHeader = (text, func, main) => {
  3751. main = main || this.mainMenu;
  3752. const header = document.createElement('div');
  3753. header.classList.add('scriptMenu_header');
  3754. header.innerHTML = text;
  3755. if (typeof func == 'function') {
  3756. header.addEventListener('click', func);
  3757. }
  3758. main.appendChild(header);
  3759. }
  3760.  
  3761. /**
  3762. * Adding a button
  3763. *
  3764. * Добавление кнопки
  3765. * @param {String} text
  3766. * @param {Function} func
  3767. * @param {String} title
  3768. * @param {HTMLDivElement} main parent // родитель
  3769. */
  3770. this.addButton = (text, func, title, main) => {
  3771. main = main || this.mainMenu;
  3772. const button = document.createElement('div');
  3773. button.classList.add('scriptMenu_button');
  3774. button.title = title;
  3775. button.addEventListener('click', func);
  3776. main.appendChild(button);
  3777.  
  3778. const buttonText = document.createElement('div');
  3779. buttonText.classList.add('scriptMenu_buttonText');
  3780. buttonText.innerText = text;
  3781. button.appendChild(buttonText);
  3782. this.buttons.push(button);
  3783.  
  3784. return button;
  3785. }
  3786.  
  3787. /**
  3788. * Adding checkbox
  3789. *
  3790. * Добавление чекбокса
  3791. * @param {String} label
  3792. * @param {String} title
  3793. * @param {HTMLDivElement} main parent // родитель
  3794. * @returns
  3795. */
  3796. this.addCheckbox = (label, title, main) => {
  3797. main = main || this.mainMenu;
  3798. const divCheckbox = document.createElement('div');
  3799. divCheckbox.classList.add('scriptMenu_divInput');
  3800. divCheckbox.title = title;
  3801. main.appendChild(divCheckbox);
  3802.  
  3803. const checkbox = document.createElement('input');
  3804. checkbox.type = 'checkbox';
  3805. checkbox.id = 'scriptMenuCheckbox' + this.checkboxes.length;
  3806. checkbox.classList.add('scriptMenu_checkbox');
  3807. divCheckbox.appendChild(checkbox)
  3808.  
  3809. const checkboxLabel = document.createElement('label');
  3810. checkboxLabel.innerText = label;
  3811. checkboxLabel.setAttribute('for', checkbox.id);
  3812. divCheckbox.appendChild(checkboxLabel);
  3813.  
  3814. this.checkboxes.push(checkbox);
  3815. return checkbox;
  3816. }
  3817.  
  3818. /**
  3819. * Adding input field
  3820. *
  3821. * Добавление поля ввода
  3822. * @param {String} title
  3823. * @param {String} placeholder
  3824. * @param {HTMLDivElement} main parent // родитель
  3825. * @returns
  3826. */
  3827. this.addInputText = (title, placeholder, main) => {
  3828. main = main || this.mainMenu;
  3829. const divInputText = document.createElement('div');
  3830. divInputText.classList.add('scriptMenu_divInputText');
  3831. divInputText.title = title;
  3832. main.appendChild(divInputText);
  3833.  
  3834. const newInputText = document.createElement('input');
  3835. newInputText.type = 'text';
  3836. if (placeholder) {
  3837. newInputText.placeholder = placeholder;
  3838. }
  3839. newInputText.classList.add('scriptMenu_InputText');
  3840. divInputText.appendChild(newInputText)
  3841. return newInputText;
  3842. }
  3843.  
  3844. /**
  3845. * Adds a dropdown block
  3846. *
  3847. * Добавляет раскрывающийся блок
  3848. * @param {String} summary
  3849. * @param {String} name
  3850. * @returns
  3851. */
  3852. this.addDetails = (summaryText, name = null) => {
  3853. const details = document.createElement('details');
  3854. details.classList.add('scriptMenu_Details');
  3855. this.mainMenu.appendChild(details);
  3856.  
  3857. const summary = document.createElement('summary');
  3858. summary.classList.add('scriptMenu_Summary');
  3859. summary.innerText = summaryText;
  3860. if (name) {
  3861. const self = this;
  3862. details.open = this.option.showDetails[name];
  3863. details.dataset.name = name;
  3864. summary.addEventListener('click', () => {
  3865. self.option.showDetails[details.dataset.name] = !details.open;
  3866. self.saveShowDetails(self.option.showDetails);
  3867. });
  3868. }
  3869. details.appendChild(summary);
  3870.  
  3871. return details;
  3872. }
  3873.  
  3874. /**
  3875. * Saving the expanded state of the details blocks
  3876. *
  3877. * Сохранение состояния развенутости блоков details
  3878. * @param {*} value
  3879. */
  3880. this.saveShowDetails = (value) => {
  3881. localStorage.setItem('scriptMenu_showDetails', JSON.stringify(value));
  3882. }
  3883.  
  3884. /**
  3885. * Loading the state of expanded blocks details
  3886. *
  3887. * Загрузка состояния развенутости блоков details
  3888. * @returns
  3889. */
  3890. this.loadShowDetails = () => {
  3891. let showDetails = localStorage.getItem('scriptMenu_showDetails');
  3892.  
  3893. if (!showDetails) {
  3894. return {};
  3895. }
  3896.  
  3897. try {
  3898. showDetails = JSON.parse(showDetails);
  3899. } catch (e) {
  3900. return {};
  3901. }
  3902.  
  3903. return showDetails;
  3904. }
  3905. });
  3906.  
  3907. /**
  3908. * Пример использования
  3909. scriptMenu.init();
  3910. scriptMenu.addHeader('v1.508');
  3911. scriptMenu.addCheckbox('testHack', 'Тестовый взлом игры!');
  3912. scriptMenu.addButton('Запуск!', () => console.log('click'), 'подсказака');
  3913. scriptMenu.addInputText('input подсказака');
  3914. */
  3915. /**
  3916. * Game Library
  3917. *
  3918. * Игровая библиотека
  3919. */
  3920. class Library {
  3921. defaultLibUrl = 'https://heroesru-a.akamaihd.net/vk/v1101/lib/lib.json';
  3922.  
  3923. constructor() {
  3924. if (!Library.instance) {
  3925. Library.instance = this;
  3926. }
  3927.  
  3928. return Library.instance;
  3929. }
  3930.  
  3931. async load() {
  3932. try {
  3933. await this.getUrlLib();
  3934. console.log(this.defaultLibUrl);
  3935. this.data = await fetch(this.defaultLibUrl).then(e => e.json())
  3936. } catch (error) {
  3937. console.error('Не удалось загрузить библиотеку', error)
  3938. }
  3939. }
  3940.  
  3941. async getUrlLib() {
  3942. try {
  3943. const db = new Database('hw_cache', 'cache');
  3944. await db.open();
  3945. const cacheLibFullUrl = await db.get('lib/lib.json.gz', false);
  3946. this.defaultLibUrl = cacheLibFullUrl.fullUrl.split('.gz').shift();
  3947. } catch(e) {}
  3948. }
  3949.  
  3950. getData(id) {
  3951. return this.data[id];
  3952. }
  3953. }
  3954.  
  3955. this.lib = new Library();
  3956. /**
  3957. * Database
  3958. *
  3959. * База данных
  3960. */
  3961. class Database {
  3962. constructor(dbName, storeName) {
  3963. this.dbName = dbName;
  3964. this.storeName = storeName;
  3965. this.db = null;
  3966. }
  3967.  
  3968. async open() {
  3969. return new Promise((resolve, reject) => {
  3970. const request = indexedDB.open(this.dbName);
  3971.  
  3972. request.onerror = () => {
  3973. reject(new Error(`Failed to open database ${this.dbName}`));
  3974. };
  3975.  
  3976. request.onsuccess = () => {
  3977. this.db = request.result;
  3978. resolve();
  3979. };
  3980.  
  3981. request.onupgradeneeded = (event) => {
  3982. const db = event.target.result;
  3983. if (!db.objectStoreNames.contains(this.storeName)) {
  3984. db.createObjectStore(this.storeName);
  3985. }
  3986. };
  3987. });
  3988. }
  3989.  
  3990. async set(key, value) {
  3991. return new Promise((resolve, reject) => {
  3992. const transaction = this.db.transaction([this.storeName], 'readwrite');
  3993. const store = transaction.objectStore(this.storeName);
  3994. const request = store.put(value, key);
  3995.  
  3996. request.onerror = () => {
  3997. reject(new Error(`Failed to save value with key ${key}`));
  3998. };
  3999.  
  4000. request.onsuccess = () => {
  4001. resolve();
  4002. };
  4003. });
  4004. }
  4005.  
  4006. async get(key, def) {
  4007. return new Promise((resolve, reject) => {
  4008. const transaction = this.db.transaction([this.storeName], 'readonly');
  4009. const store = transaction.objectStore(this.storeName);
  4010. const request = store.get(key);
  4011.  
  4012. request.onerror = () => {
  4013. resolve(def);
  4014. };
  4015.  
  4016. request.onsuccess = () => {
  4017. resolve(request.result);
  4018. };
  4019. });
  4020. }
  4021.  
  4022. async delete(key) {
  4023. return new Promise((resolve, reject) => {
  4024. const transaction = this.db.transaction([this.storeName], 'readwrite');
  4025. const store = transaction.objectStore(this.storeName);
  4026. const request = store.delete(key);
  4027.  
  4028. request.onerror = () => {
  4029. reject(new Error(`Failed to delete value with key ${key}`));
  4030. };
  4031.  
  4032. request.onsuccess = () => {
  4033. resolve();
  4034. };
  4035. });
  4036. }
  4037. }
  4038.  
  4039. /**
  4040. * Returns the stored value
  4041. *
  4042. * Возвращает сохраненное значение
  4043. */
  4044. function getSaveVal(saveName, def) {
  4045. const result = storage.get(saveName, def);
  4046. return result;
  4047. }
  4048.  
  4049. /**
  4050. * Stores value
  4051. *
  4052. * Сохраняет значение
  4053. */
  4054. function setSaveVal(saveName, value) {
  4055. storage.set(saveName, value);
  4056. }
  4057.  
  4058. /**
  4059. * Database initialization
  4060. *
  4061. * Инициализация базы данных
  4062. */
  4063. const db = new Database(GM_info.script.name, 'settings');
  4064.  
  4065. /**
  4066. * Data store
  4067. *
  4068. * Хранилище данных
  4069. */
  4070. const storage = {
  4071. userId: 0,
  4072. /**
  4073. * Default values
  4074. *
  4075. * Значения по умолчанию
  4076. */
  4077. values: [
  4078. ...Object.entries(checkboxes).map(e => ({ [e[0]]: e[1].default })),
  4079. ...Object.entries(inputs).map(e => ({ [e[0]]: e[1].default })),
  4080. ].reduce((acc, obj) => ({ ...acc, ...obj }), {}),
  4081. name: GM_info.script.name,
  4082. get: function (key, def) {
  4083. if (key in this.values) {
  4084. return this.values[key];
  4085. }
  4086. return def;
  4087. },
  4088. set: function (key, value) {
  4089. this.values[key] = value;
  4090. db.set(this.userId, this.values).catch(
  4091. e => null
  4092. );
  4093. localStorage[this.name + ':' + key] = value;
  4094. },
  4095. delete: function (key) {
  4096. delete this.values[key];
  4097. db.set(this.userId, this.values);
  4098. delete localStorage[this.name + ':' + key];
  4099. }
  4100. }
  4101.  
  4102. /**
  4103. * Returns all keys from localStorage that start with prefix (for migration)
  4104. *
  4105. * Возвращает все ключи из localStorage которые начинаются с prefix (для миграции)
  4106. */
  4107. function getAllValuesStartingWith(prefix) {
  4108. const values = [];
  4109. for (let i = 0; i < localStorage.length; i++) {
  4110. const key = localStorage.key(i);
  4111. if (key.startsWith(prefix)) {
  4112. const val = localStorage.getItem(key);
  4113. const keyValue = key.split(':')[1];
  4114. values.push({ key: keyValue, val });
  4115. }
  4116. }
  4117. return values;
  4118. }
  4119.  
  4120. /**
  4121. * Opens or migrates to a database
  4122. *
  4123. * Открывает или мигрирует в базу данных
  4124. */
  4125. async function openOrMigrateDatabase(userId) {
  4126. storage.userId = userId;
  4127. try {
  4128. await db.open();
  4129. } catch(e) {
  4130. return;
  4131. }
  4132. let settings = await db.get(userId, false);
  4133.  
  4134. if (settings) {
  4135. storage.values = settings;
  4136. return;
  4137. }
  4138.  
  4139. const values = getAllValuesStartingWith(GM_info.script.name);
  4140. for (const value of values) {
  4141. let val = null;
  4142. try {
  4143. val = JSON.parse(value.val);
  4144. } catch {
  4145. break;
  4146. }
  4147. storage.values[value.key] = val;
  4148. }
  4149. await db.set(userId, storage.values);
  4150. }
  4151.  
  4152. /**
  4153. * Sending expeditions
  4154. *
  4155. * Отправка экспедиций
  4156. */
  4157. function checkExpedition() {
  4158. return new Promise((resolve, reject) => {
  4159. const expedition = new Expedition(resolve, reject);
  4160. expedition.start();
  4161. });
  4162. }
  4163.  
  4164. class Expedition {
  4165. checkExpedInfo = {
  4166. calls: [
  4167. {
  4168. name: 'expeditionGet',
  4169. args: {},
  4170. ident: 'expeditionGet',
  4171. },
  4172. {
  4173. name: 'heroGetAll',
  4174. args: {},
  4175. ident: 'heroGetAll',
  4176. },
  4177. ],
  4178. };
  4179.  
  4180. constructor(resolve, reject) {
  4181. this.resolve = resolve;
  4182. this.reject = reject;
  4183. }
  4184.  
  4185. async start() {
  4186. const data = await Send(JSON.stringify(this.checkExpedInfo));
  4187.  
  4188. const expedInfo = data.results[0].result.response;
  4189. const dataHeroes = data.results[1].result.response;
  4190. const dataExped = { useHeroes: [], exped: [] };
  4191. const calls = [];
  4192.  
  4193. /**
  4194. * Adding expeditions to collect
  4195. * Добавляем экспедиции для сбора
  4196. */
  4197. let countGet = 0;
  4198. for (var n in expedInfo) {
  4199. const exped = expedInfo[n];
  4200. const dateNow = Date.now() / 1000;
  4201. if (exped.status == 2 && exped.endTime != 0 && dateNow > exped.endTime) {
  4202. countGet++;
  4203. calls.push({
  4204. name: 'expeditionFarm',
  4205. args: { expeditionId: exped.id },
  4206. ident: 'expeditionFarm_' + exped.id,
  4207. });
  4208. } else {
  4209. dataExped.useHeroes = dataExped.useHeroes.concat(exped.heroes);
  4210. }
  4211. if (exped.status == 1) {
  4212. dataExped.exped.push({ id: exped.id, power: exped.power });
  4213. }
  4214. }
  4215. dataExped.exped = dataExped.exped.sort((a, b) => b.power - a.power);
  4216.  
  4217. /**
  4218. * Putting together a list of heroes
  4219. * Собираем список героев
  4220. */
  4221. const heroesArr = [];
  4222. for (let n in dataHeroes) {
  4223. const hero = dataHeroes[n];
  4224. if (hero.xp > 0 && !dataExped.useHeroes.includes(hero.id)) {
  4225. let heroPower = hero.power;
  4226. // Лара Крофт * 3
  4227. if (hero.id == 63 && hero.color >= 16) {
  4228. heroPower *= 3;
  4229. }
  4230. heroesArr.push({ id: hero.id, power: heroPower });
  4231. }
  4232. }
  4233.  
  4234. /**
  4235. * Adding expeditions to send
  4236. * Добавляем экспедиции для отправки
  4237. */
  4238. let countSend = 0;
  4239. heroesArr.sort((a, b) => a.power - b.power);
  4240. for (const exped of dataExped.exped) {
  4241. let heroesIds = this.selectionHeroes(heroesArr, exped.power);
  4242. if (heroesIds && heroesIds.length > 4) {
  4243. for (let q in heroesArr) {
  4244. if (heroesIds.includes(heroesArr[q].id)) {
  4245. delete heroesArr[q];
  4246. }
  4247. }
  4248. countSend++;
  4249. calls.push({
  4250. name: 'expeditionSendHeroes',
  4251. args: {
  4252. expeditionId: exped.id,
  4253. heroes: heroesIds,
  4254. },
  4255. ident: 'expeditionSendHeroes_' + exped.id,
  4256. });
  4257. }
  4258. }
  4259.  
  4260. if (calls.length) {
  4261. await Send({ calls });
  4262. this.end(I18N('EXPEDITIONS_SENT', {countGet, countSend}));
  4263. return;
  4264. }
  4265.  
  4266. this.end(I18N('EXPEDITIONS_NOTHING'));
  4267. }
  4268.  
  4269. /**
  4270. * Selection of heroes for expeditions
  4271. *
  4272. * Подбор героев для экспедиций
  4273. */
  4274. selectionHeroes(heroes, power) {
  4275. const resultHeroers = [];
  4276. const heroesIds = [];
  4277. for (let q = 0; q < 5; q++) {
  4278. for (let i in heroes) {
  4279. let hero = heroes[i];
  4280. if (heroesIds.includes(hero.id)) {
  4281. continue;
  4282. }
  4283.  
  4284. const summ = resultHeroers.reduce((acc, hero) => acc + hero.power, 0);
  4285. const need = Math.round((power - summ) / (5 - resultHeroers.length));
  4286. if (hero.power > need) {
  4287. resultHeroers.push(hero);
  4288. heroesIds.push(hero.id);
  4289. break;
  4290. }
  4291. }
  4292. }
  4293.  
  4294. const summ = resultHeroers.reduce((acc, hero) => acc + hero.power, 0);
  4295. if (summ < power) {
  4296. return false;
  4297. }
  4298. return heroesIds;
  4299. }
  4300.  
  4301. /**
  4302. * Ends expedition script
  4303. *
  4304. * Завершает скрипт экспедиции
  4305. */
  4306. end(msg) {
  4307. setProgress(msg, true);
  4308. this.resolve();
  4309. }
  4310. }
  4311.  
  4312. /**
  4313. * Walkthrough of the dungeon
  4314. *
  4315. * Прохождение подземелья
  4316. */
  4317. function testDungeon() {
  4318. return new Promise((resolve, reject) => {
  4319. const dung = new executeDungeon(resolve, reject);
  4320. const titanit = getInput('countTitanit');
  4321. dung.start(titanit);
  4322. });
  4323. }
  4324.  
  4325. /**
  4326. * Walkthrough of the dungeon
  4327. *
  4328. * Прохождение подземелья
  4329. */
  4330. function executeDungeon(resolve, reject) {
  4331. dungeonActivity = 0;
  4332. maxDungeonActivity = 150;
  4333.  
  4334. titanGetAll = [];
  4335.  
  4336. teams = {
  4337. heroes: [],
  4338. earth: [],
  4339. fire: [],
  4340. neutral: [],
  4341. water: [],
  4342. }
  4343.  
  4344. titanStats = [];
  4345.  
  4346. titansStates = {};
  4347.  
  4348. callsExecuteDungeon = {
  4349. calls: [{
  4350. name: "dungeonGetInfo",
  4351. args: {},
  4352. ident: "dungeonGetInfo"
  4353. }, {
  4354. name: "teamGetAll",
  4355. args: {},
  4356. ident: "teamGetAll"
  4357. }, {
  4358. name: "teamGetFavor",
  4359. args: {},
  4360. ident: "teamGetFavor"
  4361. }, {
  4362. name: "clanGetInfo",
  4363. args: {},
  4364. ident: "clanGetInfo"
  4365. }, {
  4366. name: "titanGetAll",
  4367. args: {},
  4368. ident: "titanGetAll"
  4369. }, {
  4370. name: "inventoryGet",
  4371. args: {},
  4372. ident: "inventoryGet"
  4373. }]
  4374. }
  4375.  
  4376. this.start = function(titanit) {
  4377. maxDungeonActivity = titanit || getInput('countTitanit');
  4378. send(JSON.stringify(callsExecuteDungeon), startDungeon);
  4379. }
  4380.  
  4381. /**
  4382. * Getting data on the dungeon
  4383. *
  4384. * Получаем данные по подземелью
  4385. */
  4386. function startDungeon(e) {
  4387. res = e.results;
  4388. dungeonGetInfo = res[0].result.response;
  4389. if (!dungeonGetInfo) {
  4390. endDungeon('noDungeon', res);
  4391. return;
  4392. }
  4393. teamGetAll = res[1].result.response;
  4394. teamGetFavor = res[2].result.response;
  4395. dungeonActivity = res[3].result.response.stat.todayDungeonActivity;
  4396. titanGetAll = Object.values(res[4].result.response);
  4397. countPredictionCard = res[5].result.response.consumable[81];
  4398.  
  4399. teams.hero = {
  4400. favor: teamGetFavor.dungeon_hero,
  4401. heroes: teamGetAll.dungeon_hero.filter(id => id < 6000),
  4402. teamNum: 0,
  4403. }
  4404. heroPet = teamGetAll.dungeon_hero.filter(id => id >= 6000).pop();
  4405. if (heroPet) {
  4406. teams.hero.pet = heroPet;
  4407. }
  4408.  
  4409. teams.neutral = {
  4410. favor: {},
  4411. heroes: getTitanTeam(titanGetAll, 'neutral'),
  4412. teamNum: 0,
  4413. };
  4414. teams.water = {
  4415. favor: {},
  4416. heroes: getTitanTeam(titanGetAll, 'water'),
  4417. teamNum: 0,
  4418. };
  4419. teams.fire = {
  4420. favor: {},
  4421. heroes: getTitanTeam(titanGetAll, 'fire'),
  4422. teamNum: 0,
  4423. };
  4424. teams.earth = {
  4425. favor: {},
  4426. heroes: getTitanTeam(titanGetAll, 'earth'),
  4427. teamNum: 0,
  4428. };
  4429.  
  4430.  
  4431. checkFloor(dungeonGetInfo);
  4432. }
  4433.  
  4434. function getTitanTeam(titans, type) {
  4435. switch (type) {
  4436. case 'neutral':
  4437. return titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  4438. case 'water':
  4439. return titans.filter(e => e.id.toString().slice(2, 3) == '0').map(e => e.id);
  4440. case 'fire':
  4441. return titans.filter(e => e.id.toString().slice(2, 3) == '1').map(e => e.id);
  4442. case 'earth':
  4443. return titans.filter(e => e.id.toString().slice(2, 3) == '2').map(e => e.id);
  4444. }
  4445. }
  4446.  
  4447. function getNeutralTeam() {
  4448. const titans = titanGetAll.filter(e => !titansStates[e.id]?.isDead)
  4449. return titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  4450. }
  4451.  
  4452. function fixTitanTeam(titans) {
  4453. titans.heroes = titans.heroes.filter(e => !titansStates[e]?.isDead);
  4454. return titans;
  4455. }
  4456.  
  4457. /**
  4458. * Checking the floor
  4459. *
  4460. * Проверяем этаж
  4461. */
  4462. async function checkFloor(dungeonInfo) {
  4463. if (!('floor' in dungeonInfo) || dungeonInfo.floor?.state == 2) {
  4464. saveProgress();
  4465. return;
  4466. }
  4467. // console.log(dungeonInfo, dungeonActivity);
  4468. setProgress(`${I18N('DUNGEON')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity}`);
  4469. if (dungeonActivity >= maxDungeonActivity) {
  4470. endDungeon('endDungeon', 'maxActive ' + dungeonActivity + '/' + maxDungeonActivity);
  4471. return;
  4472. }
  4473. titansStates = dungeonInfo.states.titans;
  4474. titanStats = titanObjToArray(titansStates);
  4475. const floorChoices = dungeonInfo.floor.userData;
  4476. const floorType = dungeonInfo.floorType;
  4477. //const primeElement = dungeonInfo.elements.prime;
  4478. if (floorType == "battle") {
  4479. const calls = [];
  4480. for (let teamNum in floorChoices) {
  4481. attackerType = floorChoices[teamNum].attackerType;
  4482. const args = fixTitanTeam(teams[attackerType]);
  4483. if (attackerType == 'neutral') {
  4484. args.heroes = getNeutralTeam();
  4485. }
  4486. if (!args.heroes.length) {
  4487. continue;
  4488. }
  4489. args.teamNum = teamNum;
  4490. calls.push({
  4491. name: "dungeonStartBattle",
  4492. args,
  4493. ident: "body_" + teamNum
  4494. })
  4495. }
  4496. if (!calls.length) {
  4497. endDungeon('endDungeon', 'All Dead');
  4498. return;
  4499. }
  4500. const battleDatas = await Send(JSON.stringify({ calls }))
  4501. .then(e => e.results.map(n => n.result.response))
  4502. const battleResults = [];
  4503. for (n in battleDatas) {
  4504. battleData = battleDatas[n]
  4505. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  4506. battleResults.push(await Calc(battleData).then(result => {
  4507. result.teamNum = n;
  4508. result.attackerType = floorChoices[n].attackerType;
  4509. return result;
  4510. }));
  4511. }
  4512. processingPromises(battleResults)
  4513. }
  4514. }
  4515.  
  4516. function processingPromises(results) {
  4517. let selectBattle = results[0];
  4518. if (results.length < 2) {
  4519. // console.log(selectBattle);
  4520. if (!selectBattle.result.win) {
  4521. endDungeon('dungeonEndBattle\n', selectBattle);
  4522. return;
  4523. }
  4524. endBattle(selectBattle);
  4525. return;
  4526. }
  4527.  
  4528. selectBattle = false;
  4529. let bestState = -1000;
  4530. for (const result of results) {
  4531. const recovery = getState(result);
  4532. if (recovery > bestState) {
  4533. bestState = recovery;
  4534. selectBattle = result
  4535. }
  4536. }
  4537. // console.log(selectBattle.teamNum, results);
  4538. if (!selectBattle || bestState <= -1000) {
  4539. endDungeon('dungeonEndBattle\n', results);
  4540. return;
  4541. }
  4542.  
  4543. startBattle(selectBattle.teamNum, selectBattle.attackerType)
  4544. .then(endBattle);
  4545. }
  4546.  
  4547. /**
  4548. * Let's start the fight
  4549. *
  4550. * Начинаем бой
  4551. */
  4552. function startBattle(teamNum, attackerType) {
  4553. return new Promise(function (resolve, reject) {
  4554. args = fixTitanTeam(teams[attackerType]);
  4555. args.teamNum = teamNum;
  4556. if (attackerType == 'neutral') {
  4557. const titans = titanGetAll.filter(e => !titansStates[e.id]?.isDead)
  4558. args.heroes = titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  4559. }
  4560. startBattleCall = {
  4561. calls: [{
  4562. name: "dungeonStartBattle",
  4563. args,
  4564. ident: "body"
  4565. }]
  4566. }
  4567. send(JSON.stringify(startBattleCall), resultBattle, {
  4568. resolve,
  4569. teamNum,
  4570. attackerType
  4571. });
  4572. });
  4573. }
  4574. /**
  4575. * Returns the result of the battle in a promise
  4576. *
  4577. * Возращает резульат боя в промис
  4578. */
  4579. function resultBattle(resultBattles, args) {
  4580. battleData = resultBattles.results[0].result.response;
  4581. battleType = "get_tower";
  4582. if (battleData.type == "dungeon_titan") {
  4583. battleType = "get_titan";
  4584. }
  4585. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  4586. BattleCalc(battleData, battleType, function (result) {
  4587. result.teamNum = args.teamNum;
  4588. result.attackerType = args.attackerType;
  4589. args.resolve(result);
  4590. });
  4591. }
  4592. /**
  4593. * Finishing the fight
  4594. *
  4595. * Заканчиваем бой
  4596. */
  4597. async function endBattle(battleInfo) {
  4598. if (battleInfo.result.win) {
  4599. const args = {
  4600. result: battleInfo.result,
  4601. progress: battleInfo.progress,
  4602. }
  4603. if (countPredictionCard > 0) {
  4604. args.isRaid = true;
  4605. } else {
  4606. const timer = getTimer(battleInfo.battleTime);
  4607. console.log(timer);
  4608. await countdownTimer(timer, `${I18N('DUNGEON')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity}`);
  4609. }
  4610. const calls = [{
  4611. name: "dungeonEndBattle",
  4612. args,
  4613. ident: "body"
  4614. }];
  4615. lastDungeonBattleData = null;
  4616. send(JSON.stringify({ calls }), resultEndBattle);
  4617. } else {
  4618. endDungeon('dungeonEndBattle win: false\n', battleInfo);
  4619. }
  4620. }
  4621.  
  4622. /**
  4623. * Getting and processing battle results
  4624. *
  4625. * Получаем и обрабатываем результаты боя
  4626. */
  4627. function resultEndBattle(e) {
  4628. if ('error' in e) {
  4629. popup.confirm(I18N('ERROR_MSG', {
  4630. name: e.error.name,
  4631. description: e.error.description,
  4632. }));
  4633. endDungeon('errorRequest', e);
  4634. return;
  4635. }
  4636. battleResult = e.results[0].result.response;
  4637. if ('error' in battleResult) {
  4638. endDungeon('errorBattleResult', battleResult);
  4639. return;
  4640. }
  4641. dungeonGetInfo = battleResult.dungeon ?? battleResult;
  4642. dungeonActivity += battleResult.reward.dungeonActivity ?? 0;
  4643. checkFloor(dungeonGetInfo);
  4644. }
  4645.  
  4646. /**
  4647. * Returns the coefficient of condition of the
  4648. * difference in titanium before and after the battle
  4649. *
  4650. * Возвращает коэффициент состояния титанов после боя
  4651. */
  4652. function getState(result) {
  4653. if (!result.result.win) {
  4654. return -1000;
  4655. }
  4656.  
  4657. let beforeSumFactor = 0;
  4658. const beforeTitans = result.battleData.attackers;
  4659. for (let titanId in beforeTitans) {
  4660. const titan = beforeTitans[titanId];
  4661. const state = titan.state;
  4662. let factor = 1;
  4663. if (state) {
  4664. const hp = state.hp / titan.hp;
  4665. const energy = state.energy / 1e3;
  4666. factor = hp + energy / 20
  4667. }
  4668. beforeSumFactor += factor;
  4669. }
  4670.  
  4671. let afterSumFactor = 0;
  4672. const afterTitans = result.progress[0].attackers.heroes;
  4673. for (let titanId in afterTitans) {
  4674. const titan = afterTitans[titanId];
  4675. const hp = titan.hp / beforeTitans[titanId].hp;
  4676. const energy = titan.energy / 1e3;
  4677. const factor = hp + energy / 20;
  4678. afterSumFactor += factor;
  4679. }
  4680. return afterSumFactor - beforeSumFactor;
  4681. }
  4682.  
  4683. /**
  4684. * Converts an object with IDs to an array with IDs
  4685. *
  4686. * Преобразует объект с идетификаторами в массив с идетификаторами
  4687. */
  4688. function titanObjToArray(obj) {
  4689. let titans = [];
  4690. for (let id in obj) {
  4691. obj[id].id = id;
  4692. titans.push(obj[id]);
  4693. }
  4694. return titans;
  4695. }
  4696.  
  4697. function saveProgress() {
  4698. let saveProgressCall = {
  4699. calls: [{
  4700. name: "dungeonSaveProgress",
  4701. args: {},
  4702. ident: "body"
  4703. }]
  4704. }
  4705. send(JSON.stringify(saveProgressCall), resultEndBattle);
  4706. }
  4707.  
  4708. function endDungeon(reason, info) {
  4709. console.warn(reason, info);
  4710. setProgress(`${I18N('DUNGEON')} ${I18N('COMPLETED')}`, true);
  4711. resolve();
  4712. }
  4713. }
  4714.  
  4715. /**
  4716. * Passing the tower
  4717. *
  4718. * Прохождение башни
  4719. */
  4720. function testTower() {
  4721. return new Promise((resolve, reject) => {
  4722. tower = new executeTower(resolve, reject);
  4723. tower.start();
  4724. });
  4725. }
  4726.  
  4727. /**
  4728. * Passing the tower
  4729. *
  4730. * Прохождение башни
  4731. */
  4732. function executeTower(resolve, reject) {
  4733. lastTowerInfo = {};
  4734.  
  4735. scullCoin = 0;
  4736.  
  4737. heroGetAll = [];
  4738.  
  4739. heroesStates = {};
  4740.  
  4741. argsBattle = {
  4742. heroes: [],
  4743. favor: {},
  4744. };
  4745.  
  4746. callsExecuteTower = {
  4747. calls: [{
  4748. name: "towerGetInfo",
  4749. args: {},
  4750. ident: "towerGetInfo"
  4751. }, {
  4752. name: "teamGetAll",
  4753. args: {},
  4754. ident: "teamGetAll"
  4755. }, {
  4756. name: "teamGetFavor",
  4757. args: {},
  4758. ident: "teamGetFavor"
  4759. }, {
  4760. name: "inventoryGet",
  4761. args: {},
  4762. ident: "inventoryGet"
  4763. }, {
  4764. name: "heroGetAll",
  4765. args: {},
  4766. ident: "heroGetAll"
  4767. }]
  4768. }
  4769.  
  4770. buffIds = [
  4771. {id: 0, cost: 0, isBuy: false}, // plug // заглушка
  4772. {id: 1, cost: 1, isBuy: true}, // 3% attack // 3% атака
  4773. {id: 2, cost: 6, isBuy: true}, // 2% attack // 2% атака
  4774. {id: 3, cost: 16, isBuy: true}, // 4% attack // 4% атака
  4775. {id: 4, cost: 40, isBuy: true}, // 8% attack // 8% атака
  4776. {id: 5, cost: 1, isBuy: true}, // 10% armor // 10% броня
  4777. {id: 6, cost: 6, isBuy: true}, // 5% armor // 5% броня
  4778. {id: 7, cost: 16, isBuy: true}, // 10% armor // 10% броня
  4779. {id: 8, cost: 40, isBuy: true}, // 20% armor // 20% броня
  4780. { id: 9, cost: 1, isBuy: true }, // 10% protection from magic // 10% защита от магии
  4781. { id: 10, cost: 6, isBuy: true }, // 5% protection from magic // 5% защита от магии
  4782. { id: 11, cost: 16, isBuy: true }, // 10% protection from magic // 10% защита от магии
  4783. { id: 12, cost: 40, isBuy: true }, // 20% protection from magic // 20% защита от магии
  4784. { id: 13, cost: 1, isBuy: false }, // 40% health hero // 40% здоровья герою
  4785. { id: 14, cost: 6, isBuy: false }, // 40% health hero // 40% здоровья герою
  4786. { id: 15, cost: 16, isBuy: false }, // 80% health hero // 80% здоровья герою
  4787. { id: 16, cost: 40, isBuy: false }, // 40% health to all heroes // 40% здоровья всем героям
  4788. { id: 17, cost: 1, isBuy: false }, // 40% energy to the hero // 40% энергии герою
  4789. { id: 18, cost: 3, isBuy: false }, // 40% energy to the hero // 40% энергии герою
  4790. { id: 19, cost: 8, isBuy: false }, // 80% energy to the hero // 80% энергии герою
  4791. { id: 20, cost: 20, isBuy: false }, // 40% energy to all heroes // 40% энергии всем героям
  4792. { id: 21, cost: 40, isBuy: false }, // Hero Resurrection // Воскрешение героя
  4793. ]
  4794.  
  4795. this.start = function () {
  4796. send(JSON.stringify(callsExecuteTower), startTower);
  4797. }
  4798.  
  4799. /**
  4800. * Getting data on the Tower
  4801. *
  4802. * Получаем данные по башне
  4803. */
  4804. function startTower(e) {
  4805. res = e.results;
  4806. towerGetInfo = res[0].result.response;
  4807. if (!towerGetInfo) {
  4808. endTower('noTower', res);
  4809. return;
  4810. }
  4811. teamGetAll = res[1].result.response;
  4812. teamGetFavor = res[2].result.response;
  4813. inventoryGet = res[3].result.response;
  4814. heroGetAll = Object.values(res[4].result.response);
  4815.  
  4816. scullCoin = inventoryGet.coin[7] ?? 0;
  4817.  
  4818. argsBattle.favor = teamGetFavor.tower;
  4819. argsBattle.heroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  4820. pet = teamGetAll.tower.filter(id => id >= 6000).pop();
  4821. if (pet) {
  4822. argsBattle.pet = pet;
  4823. }
  4824.  
  4825. checkFloor(towerGetInfo);
  4826. }
  4827.  
  4828. function fixHeroesTeam(argsBattle) {
  4829. let fixHeroes = argsBattle.heroes.filter(e => !heroesStates[e]?.isDead);
  4830. if (fixHeroes.length < 5) {
  4831. heroGetAll = heroGetAll.filter(e => !heroesStates[e.id]?.isDead);
  4832. fixHeroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  4833. Object.keys(argsBattle.favor).forEach(e => {
  4834. if (!fixHeroes.includes(+e)) {
  4835. delete argsBattle.favor[e];
  4836. }
  4837. })
  4838. }
  4839. argsBattle.heroes = fixHeroes;
  4840. return argsBattle;
  4841. }
  4842.  
  4843. /**
  4844. * Check the floor
  4845. *
  4846. * Проверяем этаж
  4847. */
  4848. function checkFloor(towerInfo) {
  4849. lastTowerInfo = towerInfo;
  4850. maySkipFloor = +towerInfo.maySkipFloor;
  4851. floorNumber = +towerInfo.floorNumber;
  4852. heroesStates = towerInfo.states.heroes;
  4853. floorInfo = towerInfo.floor;
  4854.  
  4855. /**
  4856. * Is there at least one chest open on the floor
  4857. * Открыт ли на этаже хоть один сундук
  4858. */
  4859. isOpenChest = false;
  4860. if (towerInfo.floorType == "chest") {
  4861. isOpenChest = towerInfo.floor.chests.reduce((n, e) => n + e.opened, 0);
  4862. }
  4863.  
  4864. setProgress(`${I18N('TOWER')}: ${I18N('FLOOR')} ${floorNumber}`);
  4865. if (floorNumber > 49) {
  4866. if (isOpenChest) {
  4867. endTower('alreadyOpenChest 50 floor', floorNumber);
  4868. return;
  4869. }
  4870. }
  4871. /**
  4872. * If the chest is open and you can skip floors, then move on
  4873. * Если сундук открыт и можно скипать этажи, то переходим дальше
  4874. */
  4875. if (towerInfo.mayFullSkip && +towerInfo.teamLevel == 130) {
  4876. if (isOpenChest) {
  4877. nextOpenChest(floorNumber);
  4878. } else {
  4879. nextChestOpen(floorNumber);
  4880. }
  4881. return;
  4882. }
  4883.  
  4884. // console.log(towerInfo, scullCoin);
  4885. switch (towerInfo.floorType) {
  4886. case "battle":
  4887. if (floorNumber <= maySkipFloor) {
  4888. skipFloor();
  4889. return;
  4890. }
  4891. if (floorInfo.state == 2) {
  4892. nextFloor();
  4893. return;
  4894. }
  4895. startBattle().then(endBattle);
  4896. return;
  4897. case "buff":
  4898. checkBuff(towerInfo);
  4899. return;
  4900. case "chest":
  4901. openChest(floorNumber);
  4902. return;
  4903. default:
  4904. console.log('!', towerInfo.floorType, towerInfo);
  4905. break;
  4906. }
  4907. }
  4908.  
  4909. /**
  4910. * Let's start the fight
  4911. *
  4912. * Начинаем бой
  4913. */
  4914. function startBattle() {
  4915. return new Promise(function (resolve, reject) {
  4916. towerStartBattle = {
  4917. calls: [{
  4918. name: "towerStartBattle",
  4919. args: fixHeroesTeam(argsBattle),
  4920. ident: "body"
  4921. }]
  4922. }
  4923. send(JSON.stringify(towerStartBattle), resultBattle, resolve);
  4924. });
  4925. }
  4926. /**
  4927. * Returns the result of the battle in a promise
  4928. *
  4929. * Возращает резульат боя в промис
  4930. */
  4931. function resultBattle(resultBattles, resolve) {
  4932. battleData = resultBattles.results[0].result.response;
  4933. battleType = "get_tower";
  4934. BattleCalc(battleData, battleType, function (result) {
  4935. resolve(result);
  4936. });
  4937. }
  4938. /**
  4939. * Finishing the fight
  4940. *
  4941. * Заканчиваем бой
  4942. */
  4943. function endBattle(battleInfo) {
  4944. if (battleInfo.result.stars >= 3) {
  4945. endBattleCall = {
  4946. calls: [{
  4947. name: "towerEndBattle",
  4948. args: {
  4949. result: battleInfo.result,
  4950. progress: battleInfo.progress,
  4951. },
  4952. ident: "body"
  4953. }]
  4954. }
  4955. send(JSON.stringify(endBattleCall), resultEndBattle);
  4956. } else {
  4957. endTower('towerEndBattle win: false\n', battleInfo);
  4958. }
  4959. }
  4960.  
  4961. /**
  4962. * Getting and processing battle results
  4963. *
  4964. * Получаем и обрабатываем результаты боя
  4965. */
  4966. function resultEndBattle(e) {
  4967. battleResult = e.results[0].result.response;
  4968. if ('error' in battleResult) {
  4969. endTower('errorBattleResult', battleResult);
  4970. return;
  4971. }
  4972. if ('reward' in battleResult) {
  4973. scullCoin += battleResult.reward?.coin[7] ?? 0;
  4974. }
  4975. nextFloor();
  4976. }
  4977.  
  4978. function nextFloor() {
  4979. nextFloorCall = {
  4980. calls: [{
  4981. name: "towerNextFloor",
  4982. args: {},
  4983. ident: "body"
  4984. }]
  4985. }
  4986. send(JSON.stringify(nextFloorCall), checkDataFloor);
  4987. }
  4988.  
  4989. function openChest(floorNumber) {
  4990. floorNumber = floorNumber || 0;
  4991. openChestCall = {
  4992. calls: [{
  4993. name: "towerOpenChest",
  4994. args: {
  4995. num: 2
  4996. },
  4997. ident: "body"
  4998. }]
  4999. }
  5000. send(JSON.stringify(openChestCall), floorNumber < 50 ? nextFloor : lastChest);
  5001. }
  5002.  
  5003. function lastChest() {
  5004. endTower('openChest 50 floor', floorNumber);
  5005. }
  5006.  
  5007. function skipFloor() {
  5008. skipFloorCall = {
  5009. calls: [{
  5010. name: "towerSkipFloor",
  5011. args: {},
  5012. ident: "body"
  5013. }]
  5014. }
  5015. send(JSON.stringify(skipFloorCall), checkDataFloor);
  5016. }
  5017.  
  5018. function checkBuff(towerInfo) {
  5019. buffArr = towerInfo.floor;
  5020. promises = [];
  5021. for (let buff of buffArr) {
  5022. buffInfo = buffIds[buff.id];
  5023. if (buffInfo.isBuy && buffInfo.cost <= scullCoin) {
  5024. scullCoin -= buffInfo.cost;
  5025. promises.push(buyBuff(buff.id));
  5026. }
  5027. }
  5028. Promise.all(promises).then(nextFloor);
  5029. }
  5030.  
  5031. function buyBuff(buffId) {
  5032. return new Promise(function (resolve, reject) {
  5033. buyBuffCall = {
  5034. calls: [{
  5035. name: "towerBuyBuff",
  5036. args: {
  5037. buffId
  5038. },
  5039. ident: "body"
  5040. }]
  5041. }
  5042. send(JSON.stringify(buyBuffCall), resolve);
  5043. });
  5044. }
  5045.  
  5046. function checkDataFloor(result) {
  5047. towerInfo = result.results[0].result.response;
  5048. if ('reward' in towerInfo && towerInfo.reward?.coin) {
  5049. scullCoin += towerInfo.reward?.coin[7] ?? 0;
  5050. }
  5051. if ('tower' in towerInfo) {
  5052. towerInfo = towerInfo.tower;
  5053. }
  5054. if ('skullReward' in towerInfo) {
  5055. scullCoin += towerInfo.skullReward?.coin[7] ?? 0;
  5056. }
  5057. checkFloor(towerInfo);
  5058. }
  5059. /**
  5060. * Getting tower rewards
  5061. *
  5062. * Получаем награды башни
  5063. */
  5064. function farmTowerRewards(reason) {
  5065. let { pointRewards, points } = lastTowerInfo;
  5066. let pointsAll = Object.getOwnPropertyNames(pointRewards);
  5067. let farmPoints = pointsAll.filter(e => +e <= +points && !pointRewards[e]);
  5068. if (!farmPoints.length) {
  5069. return;
  5070. }
  5071. let farmTowerRewardsCall = {
  5072. calls: [{
  5073. name: "tower_farmPointRewards",
  5074. args: {
  5075. points: farmPoints
  5076. },
  5077. ident: "tower_farmPointRewards"
  5078. }]
  5079. }
  5080.  
  5081. if (scullCoin > 0 && reason == 'openChest 50 floor') {
  5082. farmTowerRewardsCall.calls.push({
  5083. name: "tower_farmSkullReward",
  5084. args: {},
  5085. ident: "tower_farmSkullReward"
  5086. });
  5087. }
  5088.  
  5089. send(JSON.stringify(farmTowerRewardsCall), () => { });
  5090. }
  5091.  
  5092. function fullSkipTower() {
  5093. /**
  5094. * Next chest
  5095. *
  5096. * Следующий сундук
  5097. */
  5098. function nextChest(n) {
  5099. return {
  5100. name: "towerNextChest",
  5101. args: {},
  5102. ident: "group_" + n + "_body"
  5103. }
  5104. }
  5105. /**
  5106. * Open chest
  5107. *
  5108. * Открыть сундук
  5109. */
  5110. function openChest(n) {
  5111. return {
  5112. name: "towerOpenChest",
  5113. args: {
  5114. "num": 2
  5115. },
  5116. ident: "group_" + n + "_body"
  5117. }
  5118. }
  5119.  
  5120. const fullSkipTowerCall = {
  5121. calls: []
  5122. }
  5123.  
  5124. let n = 0;
  5125. for (let i = 0; i < 15; i++) {
  5126. fullSkipTowerCall.calls.push(nextChest(++n));
  5127. fullSkipTowerCall.calls.push(openChest(++n));
  5128. }
  5129.  
  5130. send(JSON.stringify(fullSkipTowerCall), data => {
  5131. data.results[0] = data.results[28];
  5132. checkDataFloor(data);
  5133. });
  5134. }
  5135.  
  5136. function nextChestOpen(floorNumber) {
  5137. const calls = [{
  5138. name: "towerOpenChest",
  5139. args: {
  5140. num: 2
  5141. },
  5142. ident: "towerOpenChest"
  5143. }];
  5144.  
  5145. Send(JSON.stringify({ calls })).then(e => {
  5146. nextOpenChest(floorNumber);
  5147. });
  5148. }
  5149.  
  5150. function nextOpenChest(floorNumber) {
  5151. if (floorNumber > 49) {
  5152. endTower('openChest 50 floor', floorNumber);
  5153. return;
  5154. }
  5155. if (floorNumber == 1) {
  5156. fullSkipTower();
  5157. return;
  5158. }
  5159.  
  5160. let nextOpenChestCall = {
  5161. calls: [{
  5162. name: "towerNextChest",
  5163. args: {},
  5164. ident: "towerNextChest"
  5165. }, {
  5166. name: "towerOpenChest",
  5167. args: {
  5168. num: 2
  5169. },
  5170. ident: "towerOpenChest"
  5171. }]
  5172. }
  5173. send(JSON.stringify(nextOpenChestCall), checkDataFloor);
  5174. }
  5175.  
  5176. function endTower(reason, info) {
  5177. console.log(reason, info);
  5178. if (reason != 'noTower') {
  5179. farmTowerRewards(reason);
  5180. }
  5181. setProgress(`${I18N('TOWER')} ${I18N('COMPLETED')}!`, true);
  5182. resolve();
  5183. }
  5184. }
  5185.  
  5186. /**
  5187. * Passage of the arena of the titans
  5188. *
  5189. * Прохождение арены титанов
  5190. */
  5191. function testTitanArena() {
  5192. return new Promise((resolve, reject) => {
  5193. titAren = new executeTitanArena(resolve, reject);
  5194. titAren.start();
  5195. });
  5196. }
  5197.  
  5198. /**
  5199. * Passage of the arena of the titans
  5200. *
  5201. * Прохождение арены титанов
  5202. */
  5203. function executeTitanArena(resolve, reject) {
  5204. let titan_arena = [];
  5205. let finishListBattle = [];
  5206. /**
  5207. * ID of the current batch
  5208. *
  5209. * Идетификатор текущей пачки
  5210. */
  5211. let currentRival = 0;
  5212. /**
  5213. * Number of attempts to finish off the pack
  5214. *
  5215. * Количество попыток добития пачки
  5216. */
  5217. let attempts = 0;
  5218. /**
  5219. * Was there an attempt to finish off the current shooting range
  5220. *
  5221. * Была ли попытка добития текущего тира
  5222. */
  5223. let isCheckCurrentTier = false;
  5224. /**
  5225. * Current shooting range
  5226. *
  5227. * Текущий тир
  5228. */
  5229. let currTier = 0;
  5230. /**
  5231. * Number of battles on the current dash
  5232. *
  5233. * Количество битв на текущем тире
  5234. */
  5235. let countRivalsTier = 0;
  5236.  
  5237. let callsStart = {
  5238. calls: [{
  5239. name: "titanArenaGetStatus",
  5240. args: {},
  5241. ident: "titanArenaGetStatus"
  5242. }, {
  5243. name: "teamGetAll",
  5244. args: {},
  5245. ident: "teamGetAll"
  5246. }]
  5247. }
  5248.  
  5249. this.start = function () {
  5250. send(JSON.stringify(callsStart), startTitanArena);
  5251. }
  5252.  
  5253. function startTitanArena(data) {
  5254. let titanArena = data.results[0].result.response;
  5255. if (titanArena.status == 'disabled') {
  5256. endTitanArena('disabled', titanArena);
  5257. return;
  5258. }
  5259.  
  5260. let teamGetAll = data.results[1].result.response;
  5261. titan_arena = teamGetAll.titan_arena;
  5262.  
  5263. checkTier(titanArena)
  5264. }
  5265.  
  5266. function checkTier(titanArena) {
  5267. if (titanArena.status == "peace_time") {
  5268. endTitanArena('Peace_time', titanArena);
  5269. return;
  5270. }
  5271. currTier = titanArena.tier;
  5272. if (currTier) {
  5273. setProgress(`${I18N('TITAN_ARENA')}: ${I18N('LEVEL')} ${currTier}`);
  5274. }
  5275.  
  5276. if (titanArena.status == "completed_tier") {
  5277. titanArenaCompleteTier();
  5278. return;
  5279. }
  5280. /**
  5281. * Checking for the possibility of a raid
  5282. * Проверка на возможность рейда
  5283. */
  5284. if (titanArena.canRaid) {
  5285. titanArenaStartRaid();
  5286. return;
  5287. }
  5288. /**
  5289. * Check was an attempt to achieve the current shooting range
  5290. * Проверка была ли попытка добития текущего тира
  5291. */
  5292. if (!isCheckCurrentTier) {
  5293. checkRivals(titanArena.rivals);
  5294. return;
  5295. }
  5296.  
  5297. endTitanArena('Done or not canRaid', titanArena);
  5298. }
  5299. /**
  5300. * Submit dash information for verification
  5301. *
  5302. * Отправка информации о тире на проверку
  5303. */
  5304. function checkResultInfo(data) {
  5305. let titanArena = data.results[0].result.response;
  5306. checkTier(titanArena);
  5307. }
  5308. /**
  5309. * Finish the current tier
  5310. *
  5311. * Завершить текущий тир
  5312. */
  5313. function titanArenaCompleteTier() {
  5314. isCheckCurrentTier = false;
  5315. let calls = [{
  5316. name: "titanArenaCompleteTier",
  5317. args: {},
  5318. ident: "body"
  5319. }];
  5320. send(JSON.stringify({calls}), checkResultInfo);
  5321. }
  5322. /**
  5323. * Gathering points to be completed
  5324. *
  5325. * Собираем точки которые нужно добить
  5326. */
  5327. function checkRivals(rivals) {
  5328. finishListBattle = [];
  5329. for (let n in rivals) {
  5330. if (rivals[n].attackScore < 250) {
  5331. finishListBattle.push(n);
  5332. }
  5333. }
  5334. console.log('checkRivals', finishListBattle);
  5335. countRivalsTier = finishListBattle.length;
  5336. roundRivals();
  5337. }
  5338. /**
  5339. * Selecting the next point to finish off
  5340. *
  5341. * Выбор следующей точки для добития
  5342. */
  5343. function roundRivals() {
  5344. let countRivals = finishListBattle.length;
  5345. if (!countRivals) {
  5346. /**
  5347. * Whole range checked
  5348. *
  5349. * Весь тир проверен
  5350. */
  5351. isCheckCurrentTier = true;
  5352. titanArenaGetStatus();
  5353. return;
  5354. }
  5355. // setProgress('TitanArena: Уровень ' + currTier + ' Бои: ' + (countRivalsTier - countRivals + 1) + '/' + countRivalsTier);
  5356. currentRival = finishListBattle.pop();
  5357. attempts = +currentRival;
  5358. // console.log('roundRivals', currentRival);
  5359. titanArenaStartBattle(currentRival);
  5360. }
  5361. /**
  5362. * The start of a solo battle
  5363. *
  5364. * Начало одиночной битвы
  5365. */
  5366. function titanArenaStartBattle(rivalId) {
  5367. let calls = [{
  5368. name: "titanArenaStartBattle",
  5369. args: {
  5370. rivalId: rivalId,
  5371. titans: titan_arena
  5372. },
  5373. ident: "body"
  5374. }];
  5375. send(JSON.stringify({calls}), calcResult);
  5376. }
  5377. /**
  5378. * Calculation of the results of the battle
  5379. *
  5380. * Расчет результатов боя
  5381. */
  5382. function calcResult(data) {
  5383. let battlesInfo = data.results[0].result.response.battle;
  5384. /**
  5385. * If attempts are equal to the current battle number we make
  5386. * Если попытки равны номеру текущего боя делаем прерасчет
  5387. */
  5388. if (attempts == currentRival) {
  5389. preCalcBattle(battlesInfo);
  5390. return;
  5391. }
  5392. /**
  5393. * If there are still attempts, we calculate a new battle
  5394. * Если попытки еще есть делаем расчет нового боя
  5395. */
  5396. if (attempts > 0) {
  5397. attempts--;
  5398. calcBattleResult(battlesInfo)
  5399. .then(resultCalcBattle);
  5400. return;
  5401. }
  5402. /**
  5403. * Otherwise, go to the next opponent
  5404. * Иначе переходим к следующему сопернику
  5405. */
  5406. roundRivals();
  5407. }
  5408. /**
  5409. * Processing the results of the battle calculation
  5410. *
  5411. * Обработка результатов расчета битвы
  5412. */
  5413. function resultCalcBattle(resultBattle) {
  5414. // console.log('resultCalcBattle', currentRival, attempts, resultBattle.result.win);
  5415. /**
  5416. * If the current calculation of victory is not a chance or the attempt ended with the finish the battle
  5417. * Если текущий расчет победа или шансов нет или попытки кончились завершаем бой
  5418. */
  5419. if (resultBattle.result.win || !attempts) {
  5420. titanArenaEndBattle({
  5421. progress: resultBattle.progress,
  5422. result: resultBattle.result,
  5423. rivalId: resultBattle.battleData.typeId
  5424. });
  5425. return;
  5426. }
  5427. /**
  5428. * If not victory and there are attempts we start a new battle
  5429. * Если не победа и есть попытки начинаем новый бой
  5430. */
  5431. titanArenaStartBattle(resultBattle.battleData.typeId);
  5432. }
  5433. /**
  5434. * Returns the promise of calculating the results of the battle
  5435. *
  5436. * Возращает промис расчета результатов битвы
  5437. */
  5438. function getBattleInfo(battle, isRandSeed) {
  5439. return new Promise(function (resolve) {
  5440. if (isRandSeed) {
  5441. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  5442. }
  5443. // console.log(battle.seed);
  5444. BattleCalc(battle, "get_titanClanPvp", e => resolve(e));
  5445. });
  5446. }
  5447. /**
  5448. * Recalculate battles
  5449. *
  5450. * Прерасчтет битвы
  5451. */
  5452. function preCalcBattle(battle) {
  5453. let actions = [getBattleInfo(battle, false)];
  5454. const countTestBattle = getInput('countTestBattle');
  5455. for (let i = 0; i < countTestBattle; i++) {
  5456. actions.push(getBattleInfo(battle, true));
  5457. }
  5458. Promise.all(actions)
  5459. .then(resultPreCalcBattle);
  5460. }
  5461. /**
  5462. * Processing the results of the battle recalculation
  5463. *
  5464. * Обработка результатов прерасчета битвы
  5465. */
  5466. function resultPreCalcBattle(e) {
  5467. let wins = e.map(n => n.result.win);
  5468. let firstBattle = e.shift();
  5469. let countWin = wins.reduce((w, s) => w + s);
  5470. const countTestBattle = getInput('countTestBattle');
  5471. console.log('resultPreCalcBattle', `${countWin}/${countTestBattle}`)
  5472. if (countWin > 0) {
  5473. attempts = getInput('countAutoBattle');
  5474. } else {
  5475. attempts = 0;
  5476. }
  5477. resultCalcBattle(firstBattle);
  5478. }
  5479.  
  5480. /**
  5481. * Complete an arena battle
  5482. *
  5483. * Завершить битву на арене
  5484. */
  5485. function titanArenaEndBattle(args) {
  5486. let calls = [{
  5487. name: "titanArenaEndBattle",
  5488. args,
  5489. ident: "body"
  5490. }];
  5491. send(JSON.stringify({calls}), resultTitanArenaEndBattle);
  5492. }
  5493.  
  5494. function resultTitanArenaEndBattle(e) {
  5495. let attackScore = e.results[0].result.response.attackScore;
  5496. let numReval = countRivalsTier - finishListBattle.length;
  5497. setProgress(`${I18N('TITAN_ARENA')}: ${I18N('LEVEL')} ${currTier} </br>${I18N('BATTLES')}: ${numReval}/${countRivalsTier} - ${attackScore}`);
  5498. /**
  5499. * TODO: Might need to improve the results.
  5500. * TODO: Возможно стоит сделать улучшение результатов
  5501. */
  5502. // console.log('resultTitanArenaEndBattle', e)
  5503. console.log('resultTitanArenaEndBattle', numReval + '/' + countRivalsTier, attempts)
  5504. roundRivals();
  5505. }
  5506. /**
  5507. * Arena State
  5508. *
  5509. * Состояние арены
  5510. */
  5511. function titanArenaGetStatus() {
  5512. let calls = [{
  5513. name: "titanArenaGetStatus",
  5514. args: {},
  5515. ident: "body"
  5516. }];
  5517. send(JSON.stringify({calls}), checkResultInfo);
  5518. }
  5519. /**
  5520. * Arena Raid Request
  5521. *
  5522. * Запрос рейда арены
  5523. */
  5524. function titanArenaStartRaid() {
  5525. let calls = [{
  5526. name: "titanArenaStartRaid",
  5527. args: {
  5528. titans: titan_arena
  5529. },
  5530. ident: "body"
  5531. }];
  5532. send(JSON.stringify({calls}), calcResults);
  5533. }
  5534.  
  5535. function calcResults(data) {
  5536. let battlesInfo = data.results[0].result.response;
  5537. let {attackers, rivals} = battlesInfo;
  5538.  
  5539. let promises = [];
  5540. for (let n in rivals) {
  5541. rival = rivals[n];
  5542. promises.push(calcBattleResult({
  5543. attackers: attackers,
  5544. defenders: [rival.team],
  5545. seed: rival.seed,
  5546. typeId: n,
  5547. }));
  5548. }
  5549.  
  5550. Promise.all(promises)
  5551. .then(results => {
  5552. const endResults = {};
  5553. for (let info of results) {
  5554. let id = info.battleData.typeId;
  5555. endResults[id] = {
  5556. progress: info.progress,
  5557. result: info.result,
  5558. }
  5559. }
  5560. titanArenaEndRaid(endResults);
  5561. });
  5562. }
  5563.  
  5564. function calcBattleResult(battleData) {
  5565. return new Promise(function (resolve, reject) {
  5566. BattleCalc(battleData, "get_titanClanPvp", resolve);
  5567. });
  5568. }
  5569.  
  5570. /**
  5571. * Sending Raid Results
  5572. *
  5573. * Отправка результатов рейда
  5574. */
  5575. function titanArenaEndRaid(results) {
  5576. titanArenaEndRaidCall = {
  5577. calls: [{
  5578. name: "titanArenaEndRaid",
  5579. args: {
  5580. results
  5581. },
  5582. ident: "body"
  5583. }]
  5584. }
  5585. send(JSON.stringify(titanArenaEndRaidCall), checkRaidResults);
  5586. }
  5587.  
  5588. function checkRaidResults(data) {
  5589. results = data.results[0].result.response.results;
  5590. isSucsesRaid = true;
  5591. for (let i in results) {
  5592. isSucsesRaid &&= (results[i].attackScore >= 250);
  5593. }
  5594.  
  5595. if (isSucsesRaid) {
  5596. titanArenaCompleteTier();
  5597. } else {
  5598. titanArenaGetStatus();
  5599. }
  5600. }
  5601.  
  5602. function titanArenaFarmDailyReward() {
  5603. titanArenaFarmDailyRewardCall = {
  5604. calls: [{
  5605. name: "titanArenaFarmDailyReward",
  5606. args: {},
  5607. ident: "body"
  5608. }]
  5609. }
  5610. send(JSON.stringify(titanArenaFarmDailyRewardCall), () => {console.log('Done farm daily reward')});
  5611. }
  5612.  
  5613. function endTitanArena(reason, info) {
  5614. if (!['Peace_time', 'disabled'].includes(reason)) {
  5615. titanArenaFarmDailyReward();
  5616. }
  5617. console.log(reason, info);
  5618. setProgress(`${I18N('TITAN_ARENA')} ${I18N('COMPLETED')}!`, true);
  5619. resolve();
  5620. }
  5621. }
  5622.  
  5623. function hackGame() {
  5624. self = this;
  5625. selfGame = null;
  5626. bindId = 1e9;
  5627. this.libGame = null;
  5628.  
  5629. /**
  5630. * List of correspondence of used classes to their names
  5631. *
  5632. * Список соответствия используемых классов их названиям
  5633. */
  5634. ObjectsList = [
  5635. {name:"BattlePresets", prop:"game.battle.controller.thread.BattlePresets"},
  5636. {name:"DataStorage", prop:"game.data.storage.DataStorage"},
  5637. {name:"BattleConfigStorage", prop:"game.data.storage.battle.BattleConfigStorage"},
  5638. {name:"BattleInstantPlay", prop:"game.battle.controller.instant.BattleInstantPlay"},
  5639. {name:"MultiBattleResult", prop:"game.battle.controller.MultiBattleResult"},
  5640.  
  5641. {name:"PlayerMissionData", prop:"game.model.user.mission.PlayerMissionData"},
  5642. {name:"PlayerMissionBattle", prop:"game.model.user.mission.PlayerMissionBattle"},
  5643. {name:"GameModel", prop:"game.model.GameModel"},
  5644. {name:"CommandManager", prop:"game.command.CommandManager"},
  5645. {name:"MissionCommandList", prop:"game.command.rpc.mission.MissionCommandList"},
  5646. {name:"RPCCommandBase", prop:"game.command.rpc.RPCCommandBase"},
  5647. {name:"PlayerTowerData", prop:"game.model.user.tower.PlayerTowerData"},
  5648. {name:"TowerCommandList", prop:"game.command.tower.TowerCommandList"},
  5649. {name:"PlayerHeroTeamResolver", prop:"game.model.user.hero.PlayerHeroTeamResolver"},
  5650. {name:"BattlePausePopup", prop:"game.view.popup.battle.BattlePausePopup"},
  5651. {name:"BattlePopup", prop:"game.view.popup.battle.BattlePopup"},
  5652. {name:"DisplayObjectContainer", prop:"starling.display.DisplayObjectContainer"},
  5653. {name:"GuiClipContainer", prop:"engine.core.clipgui.GuiClipContainer"},
  5654. {name:"BattlePausePopupClip", prop:"game.view.popup.battle.BattlePausePopupClip"},
  5655. {name:"ClipLabel", prop:"game.view.gui.components.ClipLabel"},
  5656. {name:"ClipLabelBase", prop:"game.view.gui.components.ClipLabelBase"},
  5657. {name:"Translate", prop:"com.progrestar.common.lang.Translate"},
  5658. {name:"ClipButtonLabeledCentered", prop:"game.view.gui.components.ClipButtonLabeledCentered"},
  5659. {name:"BattlePausePopupMediator", prop:"game.mediator.gui.popup.battle.BattlePausePopupMediator"},
  5660. {name:"SettingToggleButton", prop:"game.mechanics.settings.popup.view.SettingToggleButton"},
  5661. {name:"PlayerDungeonData", prop:"game.mechanics.dungeon.model.PlayerDungeonData"},
  5662. {name:"NextDayUpdatedManager", prop:"game.model.user.NextDayUpdatedManager"},
  5663. {name:"BattleController", prop:"game.battle.controller.BattleController"},
  5664. {name:"BattleSettingsModel", prop:"game.battle.controller.BattleSettingsModel"},
  5665. {name:"BooleanProperty", prop:"engine.core.utils.property.BooleanProperty"},
  5666. {name:"RuleStorage", prop:"game.data.storage.rule.RuleStorage"},
  5667. {name:"BattleConfig", prop:"battle.BattleConfig"},
  5668. {name:"BattleGuiMediator", prop:"game.battle.gui.BattleGuiMediator"},
  5669. {name:"BooleanPropertyWriteable", prop:"engine.core.utils.property.BooleanPropertyWriteable"},
  5670. { name: "BattleLogEncoder", prop: "battle.log.BattleLogEncoder" },
  5671. { name: "BattleLogReader", prop: "battle.log.BattleLogReader" },
  5672. { name: "PlayerSubscriptionInfoValueObject", prop: "game.model.user.subscription.PlayerSubscriptionInfoValueObject" },
  5673. ];
  5674.  
  5675. /**
  5676. * Contains the game classes needed to write and override game methods
  5677. *
  5678. * Содержит классы игры необходимые для написания и подмены методов игры
  5679. */
  5680. Game = {
  5681. /**
  5682. * Function 'e'
  5683. * Функция 'e'
  5684. */
  5685. bindFunc: function (a, b) {
  5686. if (null == b)
  5687. return null;
  5688. null == b.__id__ && (b.__id__ = bindId++);
  5689. var c;
  5690. null == a.hx__closures__ ? a.hx__closures__ = {} :
  5691. c = a.hx__closures__[b.__id__];
  5692. null == c && (c = b.bind(a), a.hx__closures__[b.__id__] = c);
  5693. return c
  5694. },
  5695. };
  5696.  
  5697. /**
  5698. * Connects to game objects via the object creation event
  5699. *
  5700. * Подключается к объектам игры через событие создания объекта
  5701. */
  5702. function connectGame() {
  5703. for (let obj of ObjectsList) {
  5704. /**
  5705. * https: //stackoverflow.com/questions/42611719/how-to-intercept-and-modify-a-specific-property-for-any-object
  5706. */
  5707. Object.defineProperty(Object.prototype, obj.prop, {
  5708. set: function (value) {
  5709. if (!selfGame) {
  5710. selfGame = this;
  5711. }
  5712. if (!Game[obj.name]) {
  5713. Game[obj.name] = value;
  5714. }
  5715. // console.log('set ' + obj.prop, this, value);
  5716. this[obj.prop + '_'] = value;
  5717. },
  5718. get: function () {
  5719. // console.log('get ' + obj.prop, this);
  5720. return this[obj.prop + '_'];
  5721. }
  5722. });
  5723. }
  5724. }
  5725.  
  5726. /**
  5727. * Game.BattlePresets
  5728. * @param {bool} a isReplay
  5729. * @param {bool} b autoToggleable
  5730. * @param {bool} c auto On Start
  5731. * @param {object} d config
  5732. * @param {bool} f showBothTeams
  5733. */
  5734. /**
  5735. * Returns the results of the battle to the callback function
  5736. * Возвращает в функцию callback результаты боя
  5737. * @param {*} battleData battle data данные боя
  5738. * @param {*} battleConfig combat configuration type options:
  5739. *
  5740. * тип конфигурации боя варианты:
  5741. *
  5742. * "get_invasion", "get_titanPvpManual", "get_titanPvp",
  5743. * "get_titanClanPvp","get_clanPvp","get_titan","get_boss",
  5744. * "get_tower","get_pve","get_pvpManual","get_pvp","get_core"
  5745. *
  5746. * You can specify the xYc function in the game.assets.storage.BattleAssetStorage class
  5747. *
  5748. * Можно уточнить в классе game.assets.storage.BattleAssetStorage функция xYc
  5749. * @param {*} callback функция в которую вернуться результаты боя
  5750. */
  5751. this.BattleCalc = function (battleData, battleConfig, callback) {
  5752. // battleConfig = battleConfig || getBattleType(battleData.type)
  5753. if (!Game.BattlePresets) throw Error('Use connectGame');
  5754. battlePresets = new Game.BattlePresets(!!battleData.progress, !1, !0, Game.DataStorage[getFn(Game.DataStorage, 24)][getF(Game.BattleConfigStorage, battleConfig)](), !1);
  5755. battleInstantPlay = new Game.BattleInstantPlay(battleData, battlePresets);
  5756. battleInstantPlay[getProtoFn(Game.BattleInstantPlay, 9)].add((battleInstant) => {
  5757. const battleResult = battleInstant[getF(Game.BattleInstantPlay, 'get_result')]();
  5758. const battleData = battleInstant[getF(Game.BattleInstantPlay, 'get_rawBattleInfo')]();
  5759. const battleLog = Game.BattleLogEncoder.read(new Game.BattleLogReader(battleResult[getProtoFn(Game.MultiBattleResult, 2)][0]));
  5760. const timeLimit = battlePresets[getF(Game.BattlePresets, 'get_timeLimit')]();
  5761. const battleTime = Math.max(...battleLog.map((e) => (e.time < timeLimit && e.time !== 168.8 ? e.time : 0)));
  5762. callback({
  5763. battleTime,
  5764. battleData,
  5765. progress: battleResult[getF(Game.MultiBattleResult, 'get_progress')](),
  5766. result: battleResult[getF(Game.MultiBattleResult, 'get_result')]()
  5767. })
  5768. });
  5769. battleInstantPlay.start();
  5770. }
  5771.  
  5772. /**
  5773. * Returns a function with the specified name from the class
  5774. *
  5775. * Возвращает из класса функцию с указанным именем
  5776. * @param {Object} classF Class // класс
  5777. * @param {String} nameF function name // имя функции
  5778. * @param {String} pos name and alias order // порядок имени и псевдонима
  5779. * @returns
  5780. */
  5781. function getF(classF, nameF, pos) {
  5782. pos = pos || false;
  5783. let prop = Object.entries(classF.prototype.__properties__)
  5784. if (!pos) {
  5785. return prop.filter((e) => e[1] == nameF).pop()[0];
  5786. } else {
  5787. return prop.filter((e) => e[0] == nameF).pop()[1];
  5788. }
  5789. }
  5790.  
  5791. /**
  5792. * Returns a function with the specified name from the class
  5793. *
  5794. * Возвращает из класса функцию с указанным именем
  5795. * @param {Object} classF Class // класс
  5796. * @param {String} nameF function name // имя функции
  5797. * @returns
  5798. */
  5799. function getFnP(classF, nameF) {
  5800. let prop = Object.entries(classF.__properties__)
  5801. return prop.filter((e) => e[1] == nameF).pop()[0];
  5802. }
  5803.  
  5804. /**
  5805. * Returns the function name with the specified ordinal from the class
  5806. *
  5807. * Возвращает имя функции с указаным порядковым номером из класса
  5808. * @param {Object} classF Class // класс
  5809. * @param {Number} nF Order number of function // порядковый номер функции
  5810. * @returns
  5811. */
  5812. function getFn(classF, nF) {
  5813. let prop = Object.keys(classF);
  5814. return prop[nF];
  5815. }
  5816.  
  5817. /**
  5818. * Returns the name of the function with the specified serial number from the prototype of the class
  5819. *
  5820. * Возвращает имя функции с указаным порядковым номером из прототипа класса
  5821. * @param {Object} classF Class // класс
  5822. * @param {Number} nF Order number of function // порядковый номер функции
  5823. * @returns
  5824. */
  5825. function getProtoFn(classF, nF) {
  5826. let prop = Object.keys(classF.prototype);
  5827. return prop[nF];
  5828. }
  5829. /**
  5830. * Description of replaced functions
  5831. *
  5832. * Описание подменяемых функций
  5833. */
  5834. replaceFunction = {
  5835. company: function() {
  5836. let PMD_12 = getProtoFn(Game.PlayerMissionData, 12);
  5837. let oldSkipMisson = Game.PlayerMissionData.prototype[PMD_12];
  5838. Game.PlayerMissionData.prototype[PMD_12] = function (a, b, c) {
  5839. if (!isChecked('passBattle')) {
  5840. oldSkipMisson.call(this, a, b, c);
  5841. return;
  5842. }
  5843.  
  5844. try {
  5845. this[getProtoFn(Game.PlayerMissionData, 9)] = new Game.PlayerMissionBattle(a, b, c);
  5846.  
  5847. var a = new Game.BattlePresets(!1, !1, !0, Game.DataStorage[getFn(Game.DataStorage, 24)][getProtoFn(Game.BattleConfigStorage, 20)](), !1);
  5848. a = new Game.BattleInstantPlay(c, a);
  5849. a[getProtoFn(Game.BattleInstantPlay, 9)].add(Game.bindFunc(this, this.P$h));
  5850. a.start()
  5851. } catch (error) {
  5852. console.error('company', error)
  5853. oldSkipMisson.call(this, a, b, c);
  5854. }
  5855. }
  5856.  
  5857. Game.PlayerMissionData.prototype.P$h = function (a) {
  5858. let GM_2 = getFn(Game.GameModel, 2);
  5859. let GM_P2 = getProtoFn(Game.GameModel, 2);
  5860. let CM_20 = getProtoFn(Game.CommandManager, 20);
  5861. let MCL_2 = getProtoFn(Game.MissionCommandList, 2);
  5862. let MBR_15 = getF(Game.MultiBattleResult, "get_result");
  5863. let RPCCB_15 = getProtoFn(Game.RPCCommandBase, 16);
  5864. let PMD_32 = getProtoFn(Game.PlayerMissionData, 32);
  5865. Game.GameModel[GM_2]()[GM_P2][CM_20][MCL_2](a[MBR_15]())[RPCCB_15](Game.bindFunc(this, this[PMD_32]))
  5866. }
  5867. },
  5868. tower: function() {
  5869. let PTD_67 = getProtoFn(Game.PlayerTowerData, 67);
  5870. let oldSkipTower = Game.PlayerTowerData.prototype[PTD_67];
  5871. Game.PlayerTowerData.prototype[PTD_67] = function (a) {
  5872. if (!isChecked('passBattle')) {
  5873. oldSkipTower.call(this, a);
  5874. return;
  5875. }
  5876. try {
  5877. var p = new Game.BattlePresets(!1, !1, !0, Game.DataStorage[getFn(Game.DataStorage, 24)][getProtoFn(Game.BattleConfigStorage,20)](), !1);
  5878. a = new Game.BattleInstantPlay(a, p);
  5879. a[getProtoFn(Game.BattleInstantPlay, 9)].add(Game.bindFunc(this, this.P$h));
  5880. a.start()
  5881. } catch (error) {
  5882. console.error('tower', error)
  5883. oldSkipMisson.call(this, a, b, c);
  5884. }
  5885. }
  5886.  
  5887. Game.PlayerTowerData.prototype.P$h = function (a) {
  5888. const GM_2 = getFnP(Game.GameModel, "get_instance");
  5889. const GM_P2 = getProtoFn(Game.GameModel, 2);
  5890. const CM_29 = getProtoFn(Game.CommandManager, 29);
  5891. const TCL_5 = getProtoFn(Game.TowerCommandList, 5);
  5892. const MBR_15 = getF(Game.MultiBattleResult, "get_result");
  5893. const RPCCB_15 = getProtoFn(Game.RPCCommandBase, 17);
  5894. const PTD_78 = getProtoFn(Game.PlayerTowerData, 78);
  5895. Game.GameModel[GM_2]()[GM_P2][CM_29][TCL_5](a[MBR_15]())[RPCCB_15](Game.bindFunc(this, this[PTD_78]));
  5896. }
  5897. },
  5898. // skipSelectHero: function() {
  5899. // if (!HOST) throw Error('Use connectGame');
  5900. // Game.PlayerHeroTeamResolver.prototype[getProtoFn(Game.PlayerHeroTeamResolver, 3)] = () => false;
  5901. // },
  5902. passBattle: function() {
  5903. let BPP_4 = getProtoFn(Game.BattlePausePopup, 4);
  5904. let oldPassBattle = Game.BattlePausePopup.prototype[BPP_4];
  5905. Game.BattlePausePopup.prototype[BPP_4] = function (a) {
  5906. if (!isChecked('passBattle')) {
  5907. oldPassBattle.call(this, a);
  5908. return;
  5909. }
  5910. try {
  5911. Game.BattlePopup.prototype[getProtoFn(Game.BattlePausePopup, 4)].call(this, a);
  5912. this[getProtoFn(Game.BattlePausePopup, 3)]();
  5913. this[getProtoFn(Game.DisplayObjectContainer, 3)](this.clip[getProtoFn(Game.GuiClipContainer, 2)]());
  5914. this.clip[getProtoFn(Game.BattlePausePopupClip, 1)][getProtoFn(Game.ClipLabelBase, 9)](Game.Translate.translate("UI_POPUP_BATTLE_PAUSE"));
  5915.  
  5916. 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)])));
  5917. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 2)](
  5918. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 14)](),
  5919. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 13)]() ?
  5920. (q = this[getProtoFn(Game.BattlePausePopup, 1)], Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 18)])) :
  5921. (q = this[getProtoFn(Game.BattlePausePopup, 1)], Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 18)]))
  5922. );
  5923.  
  5924. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 0)][getProtoFn(Game.ClipLabelBase, 24)]();
  5925. this.clip[getProtoFn(Game.BattlePausePopupClip, 3)][getProtoFn(Game.SettingToggleButton, 3)](this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 9)]());
  5926. this.clip[getProtoFn(Game.BattlePausePopupClip, 4)][getProtoFn(Game.SettingToggleButton, 3)](this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 10)]());
  5927. this.clip[getProtoFn(Game.BattlePausePopupClip, 6)][getProtoFn(Game.SettingToggleButton, 3)](this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 11)]());
  5928. } catch(error) {
  5929. console.error('passBattle', error)
  5930. oldPassBattle.call(this, a);
  5931. }
  5932. }
  5933.  
  5934. let retreatButtonLabel = getF(Game.BattlePausePopupMediator, "get_retreatButtonLabel");
  5935. let oldFunc = Game.BattlePausePopupMediator.prototype[retreatButtonLabel];
  5936. Game.BattlePausePopupMediator.prototype[retreatButtonLabel] = function () {
  5937. if (isChecked('passBattle')) {
  5938. return I18N('BTN_PASS');
  5939. } else {
  5940. return oldFunc.call(this);
  5941. }
  5942. }
  5943. },
  5944. endlessCards: function() {
  5945. let PDD_20 = getProtoFn(Game.PlayerDungeonData, 20);
  5946. let oldEndlessCards = Game.PlayerDungeonData.prototype[PDD_20];
  5947. Game.PlayerDungeonData.prototype[PDD_20] = function () {
  5948. if (countPredictionCard <= 0) {
  5949. return true;
  5950. } else {
  5951. return oldEndlessCards.call(this);
  5952. }
  5953. }
  5954. },
  5955. speedBattle: function () {
  5956. const get_timeScale = getF(Game.BattleController, "get_timeScale");
  5957. const oldSpeedBattle = Game.BattleController.prototype[get_timeScale];
  5958. Game.BattleController.prototype[get_timeScale] = function () {
  5959. const speedBattle = Number.parseFloat(getInput('speedBattle'));
  5960. if (!speedBattle) {
  5961. return oldSpeedBattle.call(this);
  5962. }
  5963. try {
  5964. const BC_12 = getProtoFn(Game.BattleController, 12);
  5965. const BSM_12 = getProtoFn(Game.BattleSettingsModel, 12);
  5966. const BP_get_value = getF(Game.BooleanProperty, "get_value");
  5967. if (this[BC_12][BSM_12][BP_get_value]()) {
  5968. return 0;
  5969. }
  5970. const BSM_2 = getProtoFn(Game.BattleSettingsModel, 2);
  5971. const BC_49 = getProtoFn(Game.BattleController, 49);
  5972. const BSM_1 = getProtoFn(Game.BattleSettingsModel, 1);
  5973. const BC_14 = getProtoFn(Game.BattleController, 14);
  5974. const BC_3 = getFn(Game.BattleController, 3);
  5975. if (this[BC_12][BSM_2][BP_get_value]()) {
  5976. var a = speedBattle * this[BC_49]();
  5977. } else {
  5978. a = this[BC_12][BSM_1][BP_get_value]();
  5979. const maxSpeed = Math.max(...this[BC_14]);
  5980. const multiple = a == this[BC_14].indexOf(maxSpeed) ? (maxSpeed >= 4 ? speedBattle : this[BC_14][a]) : this[BC_14][a];
  5981. a = multiple * Game.BattleController[BC_3][BP_get_value]() * this[BC_49]();
  5982. }
  5983. const BSM_24 = getProtoFn(Game.BattleSettingsModel, 24);
  5984. a > this[BC_12][BSM_24][BP_get_value]() && (a = this[BC_12][BSM_24][BP_get_value]());
  5985. const DS_23 = getFn(Game.DataStorage, 23);
  5986. const get_battleSpeedMultiplier = getF(Game.RuleStorage, "get_battleSpeedMultiplier", true);
  5987. var b = Game.DataStorage[DS_23][get_battleSpeedMultiplier]();
  5988. const R_1 = getFn(selfGame.Reflect, 1);
  5989. const BC_1 = getFn(Game.BattleController, 1);
  5990. const get_config = getF(Game.BattlePresets, "get_config");
  5991. 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"));
  5992. return a
  5993. } catch(error) {
  5994. console.error('passBatspeedBattletle', error)
  5995. return oldSpeedBattle.call(this);
  5996. }
  5997. }
  5998. },
  5999.  
  6000. /**
  6001. * Acceleration button without Valkyries favor
  6002. *
  6003. * Кнопка ускорения без Покровительства Валькирий
  6004. */
  6005. battleFastKey: function () {
  6006. const BGM_43 = getProtoFn(Game.BattleGuiMediator, 43);
  6007. const oldBattleFastKey = Game.BattleGuiMediator.prototype[BGM_43];
  6008. Game.BattleGuiMediator.prototype[BGM_43] = function () {
  6009. let flag = true;
  6010. //console.log(flag)
  6011. if (!flag) {
  6012. return oldBattleFastKey.call(this);
  6013. }
  6014. try {
  6015. const BGM_9 = getProtoFn(Game.BattleGuiMediator, 9);
  6016. const BGM_10 = getProtoFn(Game.BattleGuiMediator, 10);
  6017. const BPW_0 = getProtoFn(Game.BooleanPropertyWriteable, 0);
  6018. this[BGM_9][BPW_0](true);
  6019. this[BGM_10][BPW_0](true);
  6020. } catch (error) {
  6021. console.error(error);
  6022. return oldBattleFastKey.call(this);
  6023. }
  6024. }
  6025. },
  6026. fastSeason: function () {
  6027. const GameNavigator = selfGame["game.screen.navigator.GameNavigator"];
  6028. const oldFuncName = getProtoFn(GameNavigator, 16);
  6029. const newFuncName = getProtoFn(GameNavigator, 14);
  6030. const oldFastSeason = GameNavigator.prototype[oldFuncName];
  6031. const newFastSeason = GameNavigator.prototype[newFuncName];
  6032. GameNavigator.prototype[oldFuncName] = function (a, b) {
  6033. if (isChecked('fastSeason')) {
  6034. return newFastSeason.apply(this, [a]);
  6035. } else {
  6036. return oldFastSeason.apply(this, [a, b]);
  6037. }
  6038. }
  6039. },
  6040. ShowChestReward: function () {
  6041. const TitanArtifactChest = selfGame["game.mechanics.titan_arena.mediator.chest.TitanArtifactChestRewardPopupMediator"];
  6042. const getOpenAmountTitan = getF(TitanArtifactChest, "get_openAmount");
  6043. const oldGetOpenAmountTitan = TitanArtifactChest.prototype[getOpenAmountTitan];
  6044. TitanArtifactChest.prototype[getOpenAmountTitan] = function () {
  6045. if (correctShowOpenArtifact) {
  6046. correctShowOpenArtifact--;
  6047. return 100;
  6048. }
  6049. return oldGetOpenAmountTitan.call(this);
  6050. }
  6051.  
  6052. const ArtifactChest = selfGame["game.view.popup.artifactchest.rewardpopup.ArtifactChestRewardPopupMediator"];
  6053. const getOpenAmount = getF(ArtifactChest, "get_openAmount");
  6054. const oldGetOpenAmount = ArtifactChest.prototype[getOpenAmount];
  6055. ArtifactChest.prototype[getOpenAmount] = function () {
  6056. if (correctShowOpenArtifact) {
  6057. correctShowOpenArtifact--;
  6058. return 100;
  6059. }
  6060. return oldGetOpenAmount.call(this);
  6061. }
  6062.  
  6063. },
  6064. fixCompany: function () {
  6065. const GameBattleView = selfGame["game.mediator.gui.popup.battle.GameBattleView"];
  6066. const BattleThread = selfGame["game.battle.controller.thread.BattleThread"];
  6067. const getOnViewDisposed = getF(BattleThread, 'get_onViewDisposed');
  6068. const getThread = getF(GameBattleView, 'get_thread');
  6069. const oldFunc = GameBattleView.prototype[getThread];
  6070. GameBattleView.prototype[getThread] = function () {
  6071. return oldFunc.call(this) || {
  6072. [getOnViewDisposed]: async () => { }
  6073. }
  6074. }
  6075. }
  6076. }
  6077.  
  6078. /**
  6079. * Starts replacing recorded functions
  6080. *
  6081. * Запускает замену записанных функций
  6082. */
  6083. this.activateHacks = function () {
  6084. if (!selfGame) throw Error('Use connectGame');
  6085. for (let func in replaceFunction) {
  6086. replaceFunction[func]();
  6087. }
  6088. }
  6089.  
  6090. /**
  6091. * Returns the game object
  6092. *
  6093. * Возвращает объект игры
  6094. */
  6095. this.getSelfGame = function () {
  6096. return selfGame;
  6097. }
  6098.  
  6099. /**
  6100. * Updates game data
  6101. *
  6102. * Обновляет данные игры
  6103. */
  6104. this.refreshGame = function () {
  6105. (new Game.NextDayUpdatedManager)[getProtoFn(Game.NextDayUpdatedManager, 5)]();
  6106. try {
  6107. cheats.refreshInventory();
  6108. } catch (e) { }
  6109. }
  6110.  
  6111. /**
  6112. * Update inventory
  6113. *
  6114. * Обновляет инвентарь
  6115. */
  6116. this.refreshInventory = async function () {
  6117. const GM_INST = getFnP(Game.GameModel, "get_instance");
  6118. const GM_0 = getProtoFn(Game.GameModel, 0);
  6119. const P_24 = getProtoFn(selfGame["game.model.user.Player"], 24);
  6120. const Player = Game.GameModel[GM_INST]()[GM_0];
  6121. Player[P_24] = new selfGame["game.model.user.inventory.PlayerInventory"]
  6122. Player[P_24].init(await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"}]}').then(e => e.results[0].result.response))
  6123. }
  6124.  
  6125. /**
  6126. * Change the play screen on windowName
  6127. *
  6128. * Сменить экран игры на windowName
  6129. *
  6130. * Possible options:
  6131. *
  6132. * Возможные варианты:
  6133. *
  6134. * 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
  6135. */
  6136. this.goNavigtor = function (windowName) {
  6137. let mechanicStorage = selfGame["game.data.storage.mechanic.MechanicStorage"];
  6138. let window = mechanicStorage[windowName];
  6139. let event = new selfGame["game.mediator.gui.popup.PopupStashEventParams"];
  6140. let Game = selfGame['Game'];
  6141. let navigator = getF(Game, "get_navigator")
  6142. let navigate = getProtoFn(selfGame["game.screen.navigator.GameNavigator"], 18)
  6143. let instance = getFnP(Game, 'get_instance');
  6144. Game[instance]()[navigator]()[navigate](window, event);
  6145. }
  6146.  
  6147. /**
  6148. * Move to the sanctuary cheats.goSanctuary()
  6149. *
  6150. * Переместиться в святилище cheats.goSanctuary()
  6151. */
  6152. this.goSanctuary = () => {
  6153. this.goNavigtor("SANCTUARY");
  6154. }
  6155.  
  6156. /**
  6157. * Go to Guild War
  6158. *
  6159. * Перейти к Войне Гильдий
  6160. */
  6161. this.goClanWar = function() {
  6162. let instance = getFnP(Game.GameModel, 'get_instance')
  6163. let player = Game.GameModel[instance]().A;
  6164. let clanWarSelect = selfGame["game.mechanics.cross_clan_war.popup.selectMode.CrossClanWarSelectModeMediator"];
  6165. new clanWarSelect(player).open();
  6166. }
  6167.  
  6168. /**
  6169. * Go to BrawlShop
  6170. *
  6171. * Переместиться в BrawlShop
  6172. */
  6173. this.goBrawlShop = () => {
  6174. const instance = getFnP(Game.GameModel, 'get_instance')
  6175. const P_36 = getProtoFn(selfGame["game.model.user.Player"], 36);
  6176. const PSD_0 = getProtoFn(selfGame["game.model.user.shop.PlayerShopData"], 0);
  6177. const IM_0 = getProtoFn(selfGame["haxe.ds.IntMap"], 0);
  6178. const PSDE_4 = getProtoFn(selfGame["game.model.user.shop.PlayerShopDataEntry"], 4);
  6179.  
  6180. const player = Game.GameModel[instance]().A;
  6181. const shop = player[P_36][PSD_0][IM_0][1038][PSDE_4];
  6182. const shopPopup = new selfGame["game.mechanics.brawl.mediator.BrawlShopPopupMediator"](player, shop)
  6183. shopPopup.open(new selfGame["game.mediator.gui.popup.PopupStashEventParams"])
  6184. }
  6185.  
  6186. /**
  6187. * Returns all stores from game data
  6188. *
  6189. * Возвращает все магазины из данных игры
  6190. */
  6191. this.getShops = () => {
  6192. const instance = getFnP(Game.GameModel, 'get_instance')
  6193. const P_36 = getProtoFn(selfGame["game.model.user.Player"], 36);
  6194. const PSD_0 = getProtoFn(selfGame["game.model.user.shop.PlayerShopData"], 0);
  6195. const IM_0 = getProtoFn(selfGame["haxe.ds.IntMap"], 0);
  6196.  
  6197. const player = Game.GameModel[instance]().A;
  6198. return player[P_36][PSD_0][IM_0];
  6199. }
  6200.  
  6201. /**
  6202. * Returns the store from the game data by ID
  6203. *
  6204. * Возвращает магазин из данных игры по идетификатору
  6205. */
  6206. this.getShop = (id) => {
  6207. const PSDE_4 = getProtoFn(selfGame["game.model.user.shop.PlayerShopDataEntry"], 4);
  6208. const shops = this.getShops();
  6209. const shop = shops[id]?.[PSDE_4];
  6210. return shop;
  6211. }
  6212.  
  6213. /**
  6214. * Change island map
  6215. *
  6216. * Сменить карту острова
  6217. */
  6218. this.changeIslandMap = (mapId = 2) => {
  6219. const GameInst = getFnP(selfGame['Game'], 'get_instance');
  6220. const GM_0 = getProtoFn(Game.GameModel, 0);
  6221. const P_59 = getProtoFn(selfGame["game.model.user.Player"], 59);
  6222. const Player = Game.GameModel[GameInst]()[GM_0];
  6223. Player[P_59].$({ id: mapId, seasonAdventure: { id: mapId, startDate: 1701914400, endDate: 1709690400, closed: false } });
  6224.  
  6225. const GN_15 = getProtoFn(selfGame["game.screen.navigator.GameNavigator"], 15)
  6226. const navigator = getF(selfGame['Game'], "get_navigator");
  6227. selfGame['Game'][GameInst]()[navigator]()[GN_15](new selfGame["game.mediator.gui.popup.PopupStashEventParams"]);
  6228. }
  6229.  
  6230. /**
  6231. * Game library availability tracker
  6232. *
  6233. * Отслеживание доступности игровой библиотеки
  6234. */
  6235. function checkLibLoad() {
  6236. timeout = setTimeout(() => {
  6237. if (Game.GameModel) {
  6238. changeLib();
  6239. } else {
  6240. checkLibLoad();
  6241. }
  6242. }, 100)
  6243. }
  6244.  
  6245. /**
  6246. * Game library data spoofing
  6247. *
  6248. * Подмена данных игровой библиотеки
  6249. */
  6250. function changeLib() {
  6251. console.log('lib connect');
  6252. const originalStartFunc = Game.GameModel.prototype.start;
  6253. Game.GameModel.prototype.start = function (a, b, c) {
  6254. self.libGame = b.raw;
  6255. try {
  6256. const levels = b.raw.seasonAdventure.level;
  6257. for (const id in levels) {
  6258. const level = levels[id];
  6259. level.clientData.graphics.fogged = level.clientData.graphics.visible
  6260. }
  6261. } catch (e) {
  6262. console.warn(e);
  6263. }
  6264. originalStartFunc.call(this, a, b, c);
  6265. }
  6266. }
  6267.  
  6268. /**
  6269. * Returns the value of a language constant
  6270. *
  6271. * Возвращает значение языковой константы
  6272. * @param {*} langConst language constant // языковая константа
  6273. * @returns
  6274. */
  6275. this.translate = function (langConst) {
  6276. return Game.Translate.translate(langConst);
  6277. }
  6278.  
  6279. connectGame();
  6280. checkLibLoad();
  6281. }
  6282.  
  6283. /**
  6284. * Auto collection of gifts
  6285. *
  6286. * Автосбор подарков
  6287. */
  6288. function getAutoGifts() {
  6289. let valName = 'giftSendIds_' + userInfo.id;
  6290.  
  6291. if (!localStorage['clearGift' + userInfo.id]) {
  6292. localStorage[valName] = '';
  6293. localStorage['clearGift' + userInfo.id] = '+';
  6294. }
  6295.  
  6296. if (!localStorage[valName]) {
  6297. localStorage[valName] = '';
  6298. }
  6299.  
  6300. const now = Date.now();
  6301. const body = JSON.stringify({ now });
  6302. const signature = window['\x73\x69\x67\x6e'](now);
  6303. /**
  6304. * Submit a request to receive gift codes
  6305. *
  6306. * Отправка запроса для получения кодов подарков
  6307. */
  6308. fetch('https://zingery.ru/heroes/getGifts.php', {
  6309. method: 'POST',
  6310. headers: {
  6311. 'X-Request-Signature': signature,
  6312. 'X-Script-Name': GM_info.script.name,
  6313. 'X-Script-Version': GM_info.script.version,
  6314. 'X-Script-Author': GM_info.script.author,
  6315. },
  6316. body
  6317. }).then(
  6318. response => response.json()
  6319. ).then(
  6320. data => {
  6321. let freebieCheckCalls = {
  6322. calls: []
  6323. }
  6324. data.forEach((giftId, n) => {
  6325. if (localStorage[valName].includes(giftId)) return;
  6326. freebieCheckCalls.calls.push({
  6327. name: "registration",
  6328. args: {
  6329. user: { referrer: {} },
  6330. giftId
  6331. },
  6332. context: {
  6333. actionTs: Math.floor(performance.now()),
  6334. cookie: window?.NXAppInfo?.session_id || null
  6335. },
  6336. ident: giftId
  6337. });
  6338. });
  6339.  
  6340. if (!freebieCheckCalls.calls.length) {
  6341. return;
  6342. }
  6343.  
  6344. send(JSON.stringify(freebieCheckCalls), e => {
  6345. let countGetGifts = 0;
  6346. const gifts = [];
  6347. for (check of e.results) {
  6348. gifts.push(check.ident);
  6349. if (check.result.response != null) {
  6350. countGetGifts++;
  6351. }
  6352. }
  6353. const saveGifts = localStorage[valName].split(';');
  6354. localStorage[valName] = [...saveGifts, ...gifts].slice(-50).join(';');
  6355. console.log(`${I18N('GIFTS')}: ${countGetGifts}`);
  6356. });
  6357. }
  6358. )
  6359. }
  6360.  
  6361. /**
  6362. * To fill the kills in the Forge of Souls
  6363. *
  6364. * Набить килов в горниле душ
  6365. */
  6366. async function bossRatingEvent() {
  6367. const topGet = await Send(JSON.stringify({ calls: [{ name: "topGet", args: { type: "bossRatingTop", extraId: 0 }, ident: "body" }] }));
  6368. if (!topGet || !topGet.results[0].result.response[0]) {
  6369. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  6370. return;
  6371. }
  6372. const replayId = topGet.results[0].result.response[0].userData.replayId;
  6373. const result = await Send(JSON.stringify({
  6374. calls: [
  6375. { name: "battleGetReplay", args: { id: replayId }, ident: "battleGetReplay" },
  6376. { name: "heroGetAll", args: {}, ident: "heroGetAll" },
  6377. { name: "pet_getAll", args: {}, ident: "pet_getAll" },
  6378. { name: "offerGetAll", args: {}, ident: "offerGetAll" }
  6379. ]
  6380. }));
  6381. const bossEventInfo = result.results[3].result.response.find(e => e.offerType == "bossEvent");
  6382. if (!bossEventInfo) {
  6383. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  6384. return;
  6385. }
  6386. const usedHeroes = bossEventInfo.progress.usedHeroes;
  6387. const party = Object.values(result.results[0].result.response.replay.attackers);
  6388. const availableHeroes = Object.values(result.results[1].result.response).map(e => e.id);
  6389. const availablePets = Object.values(result.results[2].result.response).map(e => e.id);
  6390. const calls = [];
  6391. /**
  6392. * First pack
  6393. *
  6394. * Первая пачка
  6395. */
  6396. const args = {
  6397. heroes: [],
  6398. favor: {}
  6399. }
  6400. for (let hero of party) {
  6401. if (hero.id >= 6000 && availablePets.includes(hero.id)) {
  6402. args.pet = hero.id;
  6403. continue;
  6404. }
  6405. if (!availableHeroes.includes(hero.id) || usedHeroes.includes(hero.id)) {
  6406. continue;
  6407. }
  6408. args.heroes.push(hero.id);
  6409. if (hero.favorPetId) {
  6410. args.favor[hero.id] = hero.favorPetId;
  6411. }
  6412. }
  6413. if (args.heroes.length) {
  6414. calls.push({
  6415. name: "bossRatingEvent_startBattle",
  6416. args,
  6417. ident: "body_0"
  6418. });
  6419. }
  6420. /**
  6421. * Other packs
  6422. *
  6423. * Другие пачки
  6424. */
  6425. let heroes = [];
  6426. let count = 1;
  6427. while (heroId = availableHeroes.pop()) {
  6428. if (args.heroes.includes(heroId) || usedHeroes.includes(heroId)) {
  6429. continue;
  6430. }
  6431. heroes.push(heroId);
  6432. if (heroes.length == 5) {
  6433. calls.push({
  6434. name: "bossRatingEvent_startBattle",
  6435. args: {
  6436. heroes: [...heroes],
  6437. pet: availablePets[Math.floor(Math.random() * availablePets.length)]
  6438. },
  6439. ident: "body_" + count
  6440. });
  6441. heroes = [];
  6442. count++;
  6443. }
  6444. }
  6445.  
  6446. if (!calls.length) {
  6447. setProgress(`${I18N('NO_HEROES')}`, true);
  6448. return;
  6449. }
  6450.  
  6451. const resultBattles = await Send(JSON.stringify({ calls }));
  6452. console.log(resultBattles);
  6453. rewardBossRatingEvent();
  6454. }
  6455.  
  6456. /**
  6457. * Collecting Rewards from the Forge of Souls
  6458. *
  6459. * Сбор награды из Горнила Душ
  6460. */
  6461. function rewardBossRatingEvent() {
  6462. let rewardBossRatingCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  6463. send(rewardBossRatingCall, function (data) {
  6464. let bossEventInfo = data.results[0].result.response.find(e => e.offerType == "bossEvent");
  6465. if (!bossEventInfo) {
  6466. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  6467. return;
  6468. }
  6469.  
  6470. let farmedChests = bossEventInfo.progress.farmedChests;
  6471. let score = bossEventInfo.progress.score;
  6472. setProgress(`${I18N('DAMAGE_AMOUNT')}: ${score}`);
  6473. let revard = bossEventInfo.reward;
  6474.  
  6475. let getRewardCall = {
  6476. calls: []
  6477. }
  6478.  
  6479. let count = 0;
  6480. for (let i = 1; i < 10; i++) {
  6481. if (farmedChests.includes(i)) {
  6482. continue;
  6483. }
  6484. if (score < revard[i].score) {
  6485. break;
  6486. }
  6487. getRewardCall.calls.push({
  6488. name: "bossRatingEvent_getReward",
  6489. args: {
  6490. rewardId: i
  6491. },
  6492. ident: "body_" + i
  6493. });
  6494. count++;
  6495. }
  6496. if (!count) {
  6497. setProgress(`${I18N('NOTHING_TO_COLLECT')}`, true);
  6498. return;
  6499. }
  6500.  
  6501. send(JSON.stringify(getRewardCall), e => {
  6502. console.log(e);
  6503. setProgress(`${I18N('COLLECTED')} ${e?.results?.length} ${I18N('REWARD')}`, true);
  6504. });
  6505. });
  6506. }
  6507.  
  6508. /**
  6509. * Collect Easter eggs and event rewards
  6510. *
  6511. * Собрать пасхалки и награды событий
  6512. */
  6513. function offerFarmAllReward() {
  6514. const offerGetAllCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  6515. return Send(offerGetAllCall).then((data) => {
  6516. const offerGetAll = data.results[0].result.response.filter(e => e.type == "reward" && !e?.freeRewardObtained && e.reward);
  6517. if (!offerGetAll.length) {
  6518. setProgress(`${I18N('NOTHING_TO_COLLECT')}`, true);
  6519. return;
  6520. }
  6521.  
  6522. const calls = [];
  6523. for (let reward of offerGetAll) {
  6524. calls.push({
  6525. name: "offerFarmReward",
  6526. args: {
  6527. offerId: reward.id
  6528. },
  6529. ident: "offerFarmReward_" + reward.id
  6530. });
  6531. }
  6532.  
  6533. return Send(JSON.stringify({ calls })).then(e => {
  6534. console.log(e);
  6535. setProgress(`${I18N('COLLECTED')} ${e?.results?.length} ${I18N('REWARD')}`, true);
  6536. });
  6537. });
  6538. }
  6539.  
  6540. /**
  6541. * Assemble Outland
  6542. *
  6543. * Собрать запределье
  6544. */
  6545. function getOutland() {
  6546. return new Promise(function (resolve, reject) {
  6547. send('{"calls":[{"name":"bossGetAll","args":{},"ident":"bossGetAll"}]}', e => {
  6548. let bosses = e.results[0].result.response;
  6549.  
  6550. let bossRaidOpenChestCall = {
  6551. calls: []
  6552. };
  6553.  
  6554. for (let boss of bosses) {
  6555. if (boss.mayRaid) {
  6556. bossRaidOpenChestCall.calls.push({
  6557. name: "bossRaid",
  6558. args: {
  6559. bossId: boss.id
  6560. },
  6561. ident: "bossRaid_" + boss.id
  6562. });
  6563. bossRaidOpenChestCall.calls.push({
  6564. name: "bossOpenChest",
  6565. args: {
  6566. bossId: boss.id,
  6567. amount: 1,
  6568. starmoney: 0
  6569. },
  6570. ident: "bossOpenChest_" + boss.id
  6571. });
  6572. } else if (boss.chestId == 1) {
  6573. bossRaidOpenChestCall.calls.push({
  6574. name: "bossOpenChest",
  6575. args: {
  6576. bossId: boss.id,
  6577. amount: 1,
  6578. starmoney: 0
  6579. },
  6580. ident: "bossOpenChest_" + boss.id
  6581. });
  6582. }
  6583. }
  6584.  
  6585. if (!bossRaidOpenChestCall.calls.length) {
  6586. setProgress(`${I18N('OUTLAND')} ${I18N('NOTHING_TO_COLLECT')}`, true);
  6587. resolve();
  6588. return;
  6589. }
  6590.  
  6591. send(JSON.stringify(bossRaidOpenChestCall), e => {
  6592. setProgress(`${I18N('OUTLAND')} ${I18N('COLLECTED')}`, true);
  6593. resolve();
  6594. });
  6595. });
  6596. });
  6597. }
  6598.  
  6599. /**
  6600. * Collect all rewards
  6601. *
  6602. * Собрать все награды
  6603. */
  6604. function questAllFarm() {
  6605. return new Promise(function (resolve, reject) {
  6606. let questGetAllCall = {
  6607. calls: [{
  6608. name: "questGetAll",
  6609. args: {},
  6610. ident: "body"
  6611. }]
  6612. }
  6613. send(JSON.stringify(questGetAllCall), function (data) {
  6614. let questGetAll = data.results[0].result.response;
  6615. const questAllFarmCall = {
  6616. calls: []
  6617. }
  6618. let number = 0;
  6619. for (let quest of questGetAll) {
  6620. if (quest.id < 1e6 && quest.state == 2) {
  6621. questAllFarmCall.calls.push({
  6622. name: "questFarm",
  6623. args: {
  6624. questId: quest.id
  6625. },
  6626. ident: `group_${number}_body`
  6627. });
  6628. number++;
  6629. }
  6630. }
  6631.  
  6632. if (!questAllFarmCall.calls.length) {
  6633. setProgress(`${I18N('COLLECTED')} ${number} ${I18N('REWARD')}`, true);
  6634. resolve();
  6635. return;
  6636. }
  6637.  
  6638. send(JSON.stringify(questAllFarmCall), function (res) {
  6639. console.log(res);
  6640. setProgress(`${I18N('COLLECTED')} ${number} ${I18N('REWARD')}`, true);
  6641. resolve();
  6642. });
  6643. });
  6644. })
  6645. }
  6646.  
  6647. /**
  6648. * Mission auto repeat
  6649. *
  6650. * Автоповтор миссии
  6651. * isStopSendMission = false;
  6652. * isSendsMission = true;
  6653. **/
  6654. this.sendsMission = async function (param) {
  6655. if (isStopSendMission) {
  6656. isSendsMission = false;
  6657. console.log(I18N('STOPPED'));
  6658. setProgress('');
  6659. await popup.confirm(`${I18N('STOPPED')}<br>${I18N('REPETITIONS')}: ${param.count}`, [{
  6660. msg: 'Ok',
  6661. result: true
  6662. }, ])
  6663. return;
  6664. }
  6665. lastMissionBattleStart = Date.now();
  6666. let missionStartCall = {
  6667. "calls": [{
  6668. "name": "missionStart",
  6669. "args": lastMissionStart,
  6670. "ident": "body"
  6671. }]
  6672. }
  6673. /**
  6674. * Mission Request
  6675. *
  6676. * Запрос на выполнение мисии
  6677. */
  6678. SendRequest(JSON.stringify(missionStartCall), async e => {
  6679. if (e['error']) {
  6680. isSendsMission = false;
  6681. console.log(e['error']);
  6682. setProgress('');
  6683. let msg = e['error'].name + ' ' + e['error'].description + `<br>${I18N('REPETITIONS')}: ${param.count}`;
  6684. await popup.confirm(msg, [
  6685. {msg: 'Ok', result: true},
  6686. ])
  6687. return;
  6688. }
  6689. /**
  6690. * Mission data calculation
  6691. *
  6692. * Расчет данных мисии
  6693. */
  6694. BattleCalc(e.results[0].result.response, 'get_tower', async r => {
  6695. /** missionTimer */
  6696. let timer = getTimer(r.battleTime) + 5;
  6697. const period = Math.ceil((Date.now() - lastMissionBattleStart) / 1000);
  6698. if (period < timer) {
  6699. timer = timer - period;
  6700. await countdownTimer(timer, `${I18N('MISSIONS_PASSED')}: ${param.count}`);
  6701. }
  6702.  
  6703. let missionEndCall = {
  6704. "calls": [{
  6705. "name": "missionEnd",
  6706. "args": {
  6707. "id": param.id,
  6708. "result": r.result,
  6709. "progress": r.progress
  6710. },
  6711. "ident": "body"
  6712. }]
  6713. }
  6714. /**
  6715. * Mission Completion Request
  6716. *
  6717. * Запрос на завершение миссии
  6718. */
  6719. SendRequest(JSON.stringify(missionEndCall), async (e) => {
  6720. if (e['error']) {
  6721. isSendsMission = false;
  6722. console.log(e['error']);
  6723. setProgress('');
  6724. let msg = e['error'].name + ' ' + e['error'].description + `<br>${I18N('REPETITIONS')}: ${param.count}`;
  6725. await popup.confirm(msg, [
  6726. {msg: 'Ok', result: true},
  6727. ])
  6728. return;
  6729. }
  6730. r = e.results[0].result.response;
  6731. if (r['error']) {
  6732. isSendsMission = false;
  6733. console.log(r['error']);
  6734. setProgress('');
  6735. await popup.confirm(`<br>${I18N('REPETITIONS')}: ${param.count}` + ' 3 ' + r['error'], [
  6736. {msg: 'Ok', result: true},
  6737. ])
  6738. return;
  6739. }
  6740.  
  6741. param.count++;
  6742. setProgress(`${I18N('MISSIONS_PASSED')}: ${param.count} (${I18N('STOP')})`, false, () => {
  6743. isStopSendMission = true;
  6744. });
  6745. setTimeout(sendsMission, 1, param);
  6746. });
  6747. })
  6748. });
  6749. }
  6750.  
  6751. /**
  6752. * Opening of russian dolls
  6753. *
  6754. * Открытие матрешек
  6755. */
  6756. async function openRussianDolls(libId, amount) {
  6757. let sum = 0;
  6758. let sumResult = [];
  6759.  
  6760. while (amount) {
  6761. sum += amount;
  6762. setProgress(`${I18N('TOTAL_OPEN')} ${sum}`);
  6763. const calls = [{
  6764. name: "consumableUseLootBox",
  6765. args: { libId, amount },
  6766. ident: "body"
  6767. }];
  6768. const result = await Send(JSON.stringify({ calls })).then(e => e.results[0].result.response);
  6769. let newCount = 0;
  6770. for (let n of result) {
  6771. if (n?.consumable && n.consumable[libId]) {
  6772. newCount += n.consumable[libId]
  6773. }
  6774. }
  6775. sumResult = [...sumResult, ...result];
  6776. amount = newCount;
  6777. }
  6778.  
  6779. setProgress(`${I18N('TOTAL_OPEN')} ${sum}`, 5000);
  6780. return sumResult;
  6781. }
  6782.  
  6783. /**
  6784. * Collect all mail, except letters with energy and charges of the portal
  6785. *
  6786. * Собрать всю почту, кроме писем с энергией и зарядами портала
  6787. */
  6788. function mailGetAll() {
  6789. const getMailInfo = '{"calls":[{"name":"mailGetAll","args":{},"ident":"body"}]}';
  6790.  
  6791. return Send(getMailInfo).then(dataMail => {
  6792. const letters = dataMail.results[0].result.response.letters;
  6793. const letterIds = lettersFilter(letters);
  6794. if (!letterIds.length) {
  6795. setProgress(I18N('NOTHING_TO_COLLECT'), true);
  6796. return;
  6797. }
  6798.  
  6799. const calls = [
  6800. { name: "mailFarm", args: { letterIds }, ident: "body" }
  6801. ];
  6802.  
  6803. return Send(JSON.stringify({ calls })).then(res => {
  6804. const lettersIds = res.results[0].result.response;
  6805. if (lettersIds) {
  6806. const countLetters = Object.keys(lettersIds).length;
  6807. setProgress(`${I18N('RECEIVED')} ${countLetters} ${I18N('LETTERS')}`, true);
  6808. }
  6809. });
  6810. });
  6811. }
  6812.  
  6813. /**
  6814. * Filters received emails
  6815. *
  6816. * Фильтрует получаемые письма
  6817. */
  6818. function lettersFilter(letters) {
  6819. const lettersIds = [];
  6820. for (let l in letters) {
  6821. letter = letters[l];
  6822. const reward = letter.reward;
  6823. if (!reward) {
  6824. continue;
  6825. }
  6826. /**
  6827. * Mail Collection Exceptions
  6828. *
  6829. * Исключения на сбор писем
  6830. */
  6831. const isFarmLetter = !(
  6832. /** Portals // сферы портала */
  6833. (reward?.refillable ? reward.refillable[45] : false) ||
  6834. /** Energy // энергия */
  6835. (reward?.stamina ? reward.stamina : false) ||
  6836. /** accelerating energy gain // ускорение набора энергии */
  6837. (reward?.buff ? true : false) ||
  6838. /** VIP Points // вип очки */
  6839. (reward?.vipPoints ? reward.vipPoints : false) ||
  6840. /** souls of heroes // душы героев */
  6841. (reward?.fragmentHero ? true : false) ||
  6842. /** heroes // герои */
  6843. (reward?.bundleHeroReward ? true : false)
  6844. );
  6845. if (isFarmLetter) {
  6846. lettersIds.push(~~letter.id);
  6847. continue;
  6848. }
  6849. /**
  6850. * Если до окончания годности письма менее 24 часов,
  6851. * то оно собирается не смотря на исключения
  6852. */
  6853. const availableUntil = +letter?.availableUntil;
  6854. if (availableUntil) {
  6855. const maxTimeLeft = 24 * 60 * 60 * 1000;
  6856. const timeLeft = (new Date(availableUntil * 1000) - new Date())
  6857. console.log('Time left:', timeLeft)
  6858. if (timeLeft < maxTimeLeft) {
  6859. lettersIds.push(~~letter.id);
  6860. continue;
  6861. }
  6862. }
  6863. }
  6864. return lettersIds;
  6865. }
  6866.  
  6867. /**
  6868. * Displaying information about the areas of the portal and attempts on the VG
  6869. *
  6870. * Отображение информации о сферах портала и попытках на ВГ
  6871. */
  6872. async function justInfo() {
  6873. return new Promise(async (resolve, reject) => {
  6874. const calls = [{
  6875. name: "userGetInfo",
  6876. args: {},
  6877. ident: "userGetInfo"
  6878. },
  6879. {
  6880. name: "clanWarGetInfo",
  6881. args: {},
  6882. ident: "clanWarGetInfo"
  6883. },
  6884. {
  6885. name: "titanArenaGetStatus",
  6886. args: {},
  6887. ident: "titanArenaGetStatus"
  6888. }];
  6889. const result = await Send(JSON.stringify({ calls }));
  6890. const infos = result.results;
  6891. const portalSphere = infos[0].result.response.refillable.find(n => n.id == 45);
  6892. const clanWarMyTries = infos[1].result.response?.myTries ?? 0;
  6893. const arePointsMax = infos[1].result.response?.arePointsMax;
  6894. const titansLevel = +(infos[2].result.response?.tier ?? 0);
  6895. const titansStatus = infos[2].result.response?.status; //peace_time || battle
  6896.  
  6897. const sanctuaryButton = buttons['goToSanctuary'].button;
  6898. const clanWarButton = buttons['goToClanWar'].button;
  6899. const titansArenaButton = buttons['testTitanArena'].button;
  6900.  
  6901. if (portalSphere.amount) {
  6902. sanctuaryButton.style.color = portalSphere.amount >= 3 ? 'red' : 'brown';
  6903. sanctuaryButton.title = `${I18N('SANCTUARY_TITLE')}\n${portalSphere.amount} ${I18N('PORTALS')}`;
  6904. } else {
  6905. sanctuaryButton.style.color = '';
  6906. sanctuaryButton.title = I18N('SANCTUARY_TITLE');
  6907. }
  6908. if (clanWarMyTries && !arePointsMax) {
  6909. clanWarButton.style.color = 'red';
  6910. clanWarButton.title = `${I18N('GUILD_WAR_TITLE')}\n${clanWarMyTries}${I18N('ATTEMPTS')}`;
  6911. } else {
  6912. clanWarButton.style.color = '';
  6913. clanWarButton.title = I18N('GUILD_WAR_TITLE');
  6914. }
  6915.  
  6916. if (titansLevel < 7 && titansStatus == 'battle') {
  6917. const partColor = Math.floor(125 * titansLevel / 7);
  6918. titansArenaButton.style.color = `rgb(255,${partColor},${partColor})`;
  6919. titansArenaButton.title = `${I18N('TITAN_ARENA_TITLE')}\n${titansLevel} ${I18N('LEVEL')}`;
  6920. } else {
  6921. titansArenaButton.style.color = '';
  6922. titansArenaButton.title = I18N('TITAN_ARENA_TITLE');
  6923. }
  6924.  
  6925. setProgress('<img src="https://zingery.ru/heroes/portal.png" style="height: 25px;position: relative;top: 5px;"> ' + `${portalSphere.amount} </br> ${I18N('GUILD_WAR')}: ${clanWarMyTries}`, true);
  6926. resolve();
  6927. });
  6928. }
  6929.  
  6930. async function getDailyBonus() {
  6931. const dailyBonusInfo = await Send(JSON.stringify({
  6932. calls: [{
  6933. name: "dailyBonusGetInfo",
  6934. args: {},
  6935. ident: "body"
  6936. }]
  6937. })).then(e => e.results[0].result.response);
  6938. const { availableToday, availableVip, currentDay } = dailyBonusInfo;
  6939.  
  6940. if (!availableToday) {
  6941. console.log('Уже собрано');
  6942. return;
  6943. }
  6944.  
  6945. const currentVipPoints = +userInfo.vipPoints;
  6946. const dailyBonusStat = lib.getData('dailyBonusStatic');
  6947. const vipInfo = lib.getData('level').vip;
  6948. let currentVipLevel = 0;
  6949. for (let i in vipInfo) {
  6950. vipLvl = vipInfo[i];
  6951. if (currentVipPoints >= vipLvl.vipPoints) {
  6952. currentVipLevel = vipLvl.level;
  6953. }
  6954. }
  6955. const vipLevelDouble = dailyBonusStat[`${currentDay}_0_0`].vipLevelDouble;
  6956.  
  6957. const calls = [{
  6958. name: "dailyBonusFarm",
  6959. args: {
  6960. vip: availableVip && currentVipLevel >= vipLevelDouble ? 1 : 0
  6961. },
  6962. ident: "body"
  6963. }];
  6964.  
  6965. const result = await Send(JSON.stringify({ calls }));
  6966. if (result.error) {
  6967. console.error(result.error);
  6968. return;
  6969. }
  6970.  
  6971. const reward = result.results[0].result.response;
  6972. const type = Object.keys(reward).pop();
  6973. const itemId = Object.keys(reward[type]).pop();
  6974. const count = reward[type][itemId];
  6975. const itemName = cheats.translate(`LIB_${type.toUpperCase()}_NAME_${itemId}`);
  6976.  
  6977. console.log(`Ежедневная награда: Получено ${count} ${itemName}`, reward);
  6978. }
  6979.  
  6980. async function farmStamina(lootBoxId = 148) {
  6981. const lootBox = await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"}]}')
  6982. .then(e => e.results[0].result.response.consumable[148]);
  6983.  
  6984. /** Добавить другие ящики */
  6985. /**
  6986. * 144 - медная шкатулка
  6987. * 145 - бронзовая шкатулка
  6988. * 148 - платиновая шкатулка
  6989. */
  6990. if (!lootBox) {
  6991. setProgress(I18N('NO_BOXES'), true);
  6992. return;
  6993. }
  6994.  
  6995. let maxFarmEnergy = getSaveVal('maxFarmEnergy', 100);
  6996. const result = await popup.confirm(I18N('OPEN_LOOTBOX', { lootBox }), [
  6997. { result: false, isClose: true },
  6998. { msg: I18N('BTN_YES'), result: true },
  6999. { msg: I18N('STAMINA'), isInput: true, default: maxFarmEnergy },
  7000. ]);
  7001. if (!+result) {
  7002. return;
  7003. }
  7004.  
  7005. if ((typeof result) !== 'boolean' && Number.parseInt(result)) {
  7006. maxFarmEnergy = +result;
  7007. setSaveVal('maxFarmEnergy', maxFarmEnergy);
  7008. } else {
  7009. maxFarmEnergy = 0;
  7010. }
  7011.  
  7012. let collectEnergy = 0;
  7013. for (let count = lootBox; count > 0; count--) {
  7014. const result = await Send('{"calls":[{"name":"consumableUseLootBox","args":{"libId":148,"amount":1},"ident":"body"}]}')
  7015. .then(e => e.results[0].result.response[0]);
  7016. if ('stamina' in result) {
  7017. setProgress(`${I18N('OPEN')}: ${lootBox - count}/${lootBox} ${I18N('STAMINA')} +${result.stamina}<br>${I18N('STAMINA')}: ${collectEnergy}`, false);
  7018. console.log(`${ I18N('STAMINA') } + ${ result.stamina }`);
  7019. if (!maxFarmEnergy) {
  7020. return;
  7021. }
  7022. collectEnergy += +result.stamina;
  7023. if (collectEnergy >= maxFarmEnergy) {
  7024. console.log(`${I18N('STAMINA')} + ${ collectEnergy }`);
  7025. setProgress(`${I18N('STAMINA')} + ${ collectEnergy }`, false);
  7026. return;
  7027. }
  7028. } else {
  7029. setProgress(`${I18N('OPEN')}: ${lootBox - count}/${lootBox}<br>${I18N('STAMINA')}: ${collectEnergy}`, false);
  7030. console.log(result);
  7031. }
  7032. }
  7033.  
  7034. setProgress(I18N('BOXES_OVER'), true);
  7035. }
  7036.  
  7037. async function fillActive() {
  7038. const data = await Send(JSON.stringify({
  7039. calls: [{
  7040. name: "questGetAll",
  7041. args: {},
  7042. ident: "questGetAll"
  7043. }, {
  7044. name: "inventoryGet",
  7045. args: {},
  7046. ident: "inventoryGet"
  7047. }, {
  7048. name: "clanGetInfo",
  7049. args: {},
  7050. ident: "clanGetInfo"
  7051. }
  7052. ]
  7053. })).then(e => e.results.map(n => n.result.response));
  7054.  
  7055. const quests = data[0];
  7056. const inv = data[1];
  7057. const stat = data[2].stat;
  7058. const maxActive = 2000 - stat.todayItemsActivity;
  7059. if (maxActive <= 0) {
  7060. setProgress(I18N('NO_MORE_ACTIVITY'), true);
  7061. return;
  7062. }
  7063. let countGetActive = 0;
  7064. const quest = quests.find(e => e.id > 10046 && e.id < 10051);
  7065. if (quest) {
  7066. countGetActive = 1750 - quest.progress;
  7067. }
  7068. if (countGetActive <= 0) {
  7069. countGetActive = maxActive;
  7070. }
  7071. console.log(countGetActive);
  7072.  
  7073. countGetActive = +(await popup.confirm(I18N('EXCHANGE_ITEMS', { maxActive }), [
  7074. { result: false, isClose: true },
  7075. { msg: I18N('GET_ACTIVITY'), isInput: true, default: countGetActive.toString() },
  7076. ]));
  7077.  
  7078. if (!countGetActive) {
  7079. return;
  7080. }
  7081.  
  7082. if (countGetActive > maxActive) {
  7083. countGetActive = maxActive;
  7084. }
  7085.  
  7086. const items = lib.getData('inventoryItem');
  7087.  
  7088. let itemsInfo = [];
  7089. for (let type of ['gear', 'scroll']) {
  7090. for (let i in inv[type]) {
  7091. const v = items[type][i]?.enchantValue || 0;
  7092. itemsInfo.push({
  7093. id: i,
  7094. count: inv[type][i],
  7095. v,
  7096. type
  7097. })
  7098. }
  7099. const invType = 'fragment' + type.toLowerCase().charAt(0).toUpperCase() + type.slice(1);
  7100. for (let i in inv[invType]) {
  7101. const v = items[type][i]?.fragmentEnchantValue || 0;
  7102. itemsInfo.push({
  7103. id: i,
  7104. count: inv[invType][i],
  7105. v,
  7106. type: invType
  7107. })
  7108. }
  7109. }
  7110. itemsInfo = itemsInfo.filter(e => e.v < 4 && e.count > 200);
  7111. itemsInfo = itemsInfo.sort((a, b) => b.count - a.count);
  7112. console.log(itemsInfo);
  7113. const activeItem = itemsInfo.shift();
  7114. console.log(activeItem);
  7115. const countItem = Math.ceil(countGetActive / activeItem.v);
  7116. if (countItem > activeItem.count) {
  7117. setProgress(I18N('NOT_ENOUGH_ITEMS'), true);
  7118. console.log(activeItem);
  7119. return;
  7120. }
  7121.  
  7122. await Send(JSON.stringify({
  7123. calls: [{
  7124. name: "clanItemsForActivity",
  7125. args: {
  7126. items: {
  7127. [activeItem.type]: {
  7128. [activeItem.id]: countItem
  7129. }
  7130. }
  7131. },
  7132. ident: "body"
  7133. }]
  7134. })).then(e => {
  7135. /** TODO: Вывести потраченые предметы */
  7136. console.log(e);
  7137. setProgress(`${I18N('ACTIVITY_RECEIVED')}: ` + e.results[0].result.response, true);
  7138. });
  7139. }
  7140.  
  7141. async function buyHeroFragments() {
  7142. const result = await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"},{"name":"shopGetAll","args":{},"ident":"shopGetAll"}]}')
  7143. .then(e => e.results.map(n => n.result.response));
  7144. const inv = result[0];
  7145. const shops = Object.values(result[1]).filter(shop => [4, 5, 6, 8, 9, 10, 17].includes(shop.id));
  7146. const calls = [];
  7147.  
  7148. for (let shop of shops) {
  7149. const slots = Object.values(shop.slots);
  7150. for (const slot of slots) {
  7151. /* Уже куплено */
  7152. if (slot.bought) {
  7153. continue;
  7154. }
  7155. /* Не душа героя */
  7156. if (!('fragmentHero' in slot.reward)) {
  7157. continue;
  7158. }
  7159. const coin = Object.keys(slot.cost).pop();
  7160. const coinId = Object.keys(slot.cost[coin]).pop();
  7161. const stock = inv[coin][coinId] || 0;
  7162. /* Не хватает на покупку */
  7163. if (slot.cost[coin][coinId] > stock) {
  7164. continue;
  7165. }
  7166. inv[coin][coinId] -= slot.cost[coin][coinId];
  7167. calls.push({
  7168. name: "shopBuy",
  7169. args: {
  7170. shopId: shop.id,
  7171. slot: slot.id,
  7172. cost: slot.cost,
  7173. reward: slot.reward,
  7174. },
  7175. ident: `shopBuy_${shop.id}_${slot.id}`,
  7176. })
  7177. }
  7178. }
  7179.  
  7180. if (!calls.length) {
  7181. setProgress(I18N('NO_PURCHASABLE_HERO_SOULS'), true);
  7182. return;
  7183. }
  7184.  
  7185. const bought = await Send(JSON.stringify({ calls })).then(e => e.results.map(n => n.result.response));
  7186. if (!bought) {
  7187. console.log('что-то пошло не так')
  7188. return;
  7189. }
  7190.  
  7191. let countHeroSouls = 0;
  7192. for (const buy of bought) {
  7193. countHeroSouls += +Object.values(Object.values(buy).pop()).pop();
  7194. }
  7195. console.log(countHeroSouls, bought, calls);
  7196. setProgress(I18N('PURCHASED_HERO_SOULS', { countHeroSouls }), true);
  7197. }
  7198.  
  7199. /** Открыть платные сундуки в Запределье за 90 */
  7200. async function bossOpenChestPay() {
  7201. const info = await Send('{"calls":[{"name":"userGetInfo","args":{},"ident":"userGetInfo"},{"name":"bossGetAll","args":{},"ident":"bossGetAll"}]}')
  7202. .then(e => e.results.map(n => n.result.response));
  7203.  
  7204. const user = info[0];
  7205. const boses = info[1];
  7206.  
  7207. const currentStarMoney = user.starMoney;
  7208. if (currentStarMoney < 540) {
  7209. setProgress(I18N('NOT_ENOUGH_EMERALDS_540', { currentStarMoney }), true);
  7210. return;
  7211. }
  7212.  
  7213. const calls = [];
  7214.  
  7215. let n = 0;
  7216. const amount = 1;
  7217. for (let boss of boses) {
  7218. const bossId = boss.id;
  7219. if (boss.chestNum != 2) {
  7220. continue;
  7221. }
  7222. for (const starmoney of [90, 90, 0]) {
  7223. calls.push({
  7224. name: "bossOpenChest",
  7225. args: {
  7226. bossId,
  7227. amount,
  7228. starmoney
  7229. },
  7230. ident: "bossOpenChest_" + (++n)
  7231. });
  7232. }
  7233. }
  7234.  
  7235. if (!calls.length) {
  7236. setProgress(I18N('CHESTS_NOT_AVAILABLE'), true);
  7237. return;
  7238. }
  7239.  
  7240. const result = await Send(JSON.stringify({ calls }));
  7241. console.log(result);
  7242. if (result?.results) {
  7243. setProgress(`${I18N('OUTLAND_CHESTS_RECEIVED')}: ` + result.results.length, true);
  7244. } else {
  7245. setProgress(I18N('CHESTS_NOT_AVAILABLE'), true);
  7246. }
  7247. }
  7248.  
  7249. async function autoRaidAdventure() {
  7250. const calls = [
  7251. {
  7252. name: "userGetInfo",
  7253. args: {},
  7254. ident: "userGetInfo"
  7255. },
  7256. {
  7257. name: "adventure_raidGetInfo",
  7258. args: {},
  7259. ident: "adventure_raidGetInfo"
  7260. }
  7261. ];
  7262. const result = await Send(JSON.stringify({ calls }))
  7263. .then(e => e.results.map(n => n.result.response));
  7264.  
  7265. const portalSphere = result[0].refillable.find(n => n.id == 45);
  7266. const adventureRaid = Object.entries(result[1].raid).filter(e => e[1]).pop()
  7267. const adventureId = adventureRaid ? adventureRaid[0] : 0;
  7268.  
  7269. if (!portalSphere.amount || !adventureId) {
  7270. setProgress(I18N('RAID_NOT_AVAILABLE'), true);
  7271. return;
  7272. }
  7273.  
  7274. const countRaid = +(await popup.confirm(I18N('RAID_ADVENTURE', { adventureId }), [
  7275. { result: false, isClose: true },
  7276. { msg: I18N('RAID'), isInput: true, default: portalSphere.amount },
  7277. ]));
  7278.  
  7279. if (!countRaid) {
  7280. return;
  7281. }
  7282.  
  7283. if (countRaid > portalSphere.amount) {
  7284. countRaid = portalSphere.amount;
  7285. }
  7286.  
  7287. const resultRaid = await Send(JSON.stringify({
  7288. calls: [...Array(countRaid)].map((e, i) => ({
  7289. name: "adventure_raid",
  7290. args: {
  7291. adventureId
  7292. },
  7293. ident: `body_${i}`
  7294. }))
  7295. })).then(e => e.results.map(n => n.result.response));
  7296.  
  7297. if (!resultRaid.length) {
  7298. console.log(resultRaid);
  7299. setProgress(I18N('SOMETHING_WENT_WRONG'), true);
  7300. return;
  7301. }
  7302.  
  7303. console.log(resultRaid, adventureId, portalSphere.amount);
  7304. setProgress(I18N('ADVENTURE_COMPLETED', { adventureId, times: resultRaid.length }), true);
  7305. }
  7306.  
  7307. /** Вывести всю клановую статистику в консоль браузера */
  7308. async function clanStatistic() {
  7309. const copy = function (text) {
  7310. const copyTextarea = document.createElement("textarea");
  7311. copyTextarea.style.opacity = "0";
  7312. copyTextarea.textContent = text;
  7313. document.body.appendChild(copyTextarea);
  7314. copyTextarea.select();
  7315. document.execCommand("copy");
  7316. document.body.removeChild(copyTextarea);
  7317. delete copyTextarea;
  7318. }
  7319. const calls = [
  7320. { name: "clanGetInfo", args: {}, ident: "clanGetInfo" },
  7321. { name: "clanGetWeeklyStat", args: {}, ident: "clanGetWeeklyStat" },
  7322. { name: "clanGetLog", args: {}, ident: "clanGetLog" },
  7323. ];
  7324.  
  7325. const result = await Send(JSON.stringify({ calls }));
  7326.  
  7327. const dataClanInfo = result.results[0].result.response;
  7328. const dataClanStat = result.results[1].result.response;
  7329. const dataClanLog = result.results[2].result.response;
  7330.  
  7331. const membersStat = {};
  7332. for (let i = 0; i < dataClanStat.stat.length; i++) {
  7333. membersStat[dataClanStat.stat[i].id] = dataClanStat.stat[i];
  7334. }
  7335.  
  7336. const joinStat = {};
  7337. historyLog = dataClanLog.history;
  7338. for (let j in historyLog) {
  7339. his = historyLog[j];
  7340. if (his.event == 'join') {
  7341. joinStat[his.userId] = his.ctime;
  7342. }
  7343. }
  7344.  
  7345. const infoArr = [];
  7346. const members = dataClanInfo.clan.members;
  7347. for (let n in members) {
  7348. var member = [
  7349. n,
  7350. members[n].name,
  7351. members[n].level,
  7352. dataClanInfo.clan.warriors.includes(+n) ? 1 : 0,
  7353. (new Date(members[n].lastLoginTime * 1000)).toLocaleString().replace(',', ''),
  7354. joinStat[n] ? (new Date(joinStat[n] * 1000)).toLocaleString().replace(',', '') : '',
  7355. membersStat[n].activity.reverse().join('\t'),
  7356. membersStat[n].adventureStat.reverse().join('\t'),
  7357. membersStat[n].clanGifts.reverse().join('\t'),
  7358. membersStat[n].clanWarStat.reverse().join('\t'),
  7359. membersStat[n].dungeonActivity.reverse().join('\t'),
  7360. ];
  7361. infoArr.push(member);
  7362. }
  7363. const info = infoArr.sort((a, b) => (b[2] - a[2])).map((e) => e.join('\t')).join('\n');
  7364. console.log(info);
  7365. copy(info);
  7366. setProgress(I18N('CLAN_STAT_COPY'), true);
  7367. }
  7368.  
  7369. async function buyInStoreForGold() {
  7370. const result = await Send('{"calls":[{"name":"shopGetAll","args":{},"ident":"body"},{"name":"userGetInfo","args":{},"ident":"userGetInfo"}]}').then(e => e.results.map(n => n.result.response));
  7371. const shops = result[0];
  7372. const user = result[1];
  7373. let gold = user.gold;
  7374. const calls = [];
  7375. if (shops[17]) {
  7376. const slots = shops[17].slots;
  7377. for (let i = 1; i <= 2; i++) {
  7378. if (!slots[i].bought) {
  7379. const costGold = slots[i].cost.gold;
  7380. if ((gold - costGold) < 0) {
  7381. continue;
  7382. }
  7383. gold -= costGold;
  7384. calls.push({
  7385. name: "shopBuy",
  7386. args: {
  7387. shopId: 17,
  7388. slot: i,
  7389. cost: slots[i].cost,
  7390. reward: slots[i].reward,
  7391. },
  7392. ident: 'body_' + i,
  7393. })
  7394. }
  7395. }
  7396. }
  7397. const slots = shops[1].slots;
  7398. for (let i = 4; i <= 6; i++) {
  7399. if (!slots[i].bought && slots[i]?.cost?.gold) {
  7400. const costGold = slots[i].cost.gold;
  7401. if ((gold - costGold) < 0) {
  7402. continue;
  7403. }
  7404. gold -= costGold;
  7405. calls.push({
  7406. name: "shopBuy",
  7407. args: {
  7408. shopId: 1,
  7409. slot: i,
  7410. cost: slots[i].cost,
  7411. reward: slots[i].reward,
  7412. },
  7413. ident: 'body_' + i,
  7414. })
  7415. }
  7416. }
  7417.  
  7418. if (!calls.length) {
  7419. setProgress(I18N('NOTHING_BUY'), true);
  7420. return;
  7421. }
  7422.  
  7423. const resultBuy = await Send(JSON.stringify({ calls })).then(e => e.results.map(n => n.result.response));
  7424. console.log(resultBuy);
  7425. const countBuy = resultBuy.length;
  7426. setProgress(I18N('LOTS_BOUGHT', { countBuy }), true);
  7427. }
  7428.  
  7429. function rewardsAndMailFarm() {
  7430. return new Promise(function (resolve, reject) {
  7431. let questGetAllCall = {
  7432. calls: [{
  7433. name: "questGetAll",
  7434. args: {},
  7435. ident: "questGetAll"
  7436. }, {
  7437. name: "mailGetAll",
  7438. args: {},
  7439. ident: "mailGetAll"
  7440. }]
  7441. }
  7442. send(JSON.stringify(questGetAllCall), function (data) {
  7443. if (!data) return;
  7444. let questGetAll = data.results[0].result.response.filter(e => e.state == 2);
  7445. const questBattlePass = lib.getData('quest').battlePass;
  7446. const questChainBPass = lib.getData('battlePass').questChain;
  7447.  
  7448. const questAllFarmCall = {
  7449. calls: []
  7450. }
  7451. let number = 0;
  7452. for (let quest of questGetAll) {
  7453. if (quest.id > 1e6) {
  7454. const questInfo = questBattlePass[quest.id];
  7455. const chain = questChainBPass[questInfo.chain];
  7456. if (chain.requirement?.battlePassTicket) {
  7457. continue;
  7458. }
  7459. }
  7460. questAllFarmCall.calls.push({
  7461. name: "questFarm",
  7462. args: {
  7463. questId: quest.id
  7464. },
  7465. ident: `questFarm_${number}`
  7466. });
  7467. number++;
  7468. }
  7469.  
  7470. let letters = data?.results[1]?.result?.response?.letters;
  7471. letterIds = lettersFilter(letters);
  7472.  
  7473. if (letterIds.length) {
  7474. questAllFarmCall.calls.push({
  7475. name: "mailFarm",
  7476. args: { letterIds },
  7477. ident: "mailFarm"
  7478. })
  7479. }
  7480.  
  7481. if (!questAllFarmCall.calls.length) {
  7482. setProgress(I18N('NOTHING_TO_COLLECT'), true);
  7483. resolve();
  7484. return;
  7485. }
  7486.  
  7487. send(JSON.stringify(questAllFarmCall), function (res) {
  7488. let reSend = false;
  7489. let countQuests = 0;
  7490. let countMail = 0;
  7491. for (let call of res.results) {
  7492. if (call.ident.includes('questFarm')) {
  7493. countQuests++;
  7494. } else {
  7495. countMail = Object.keys(call.result.response).length;
  7496. }
  7497.  
  7498. /** TODO: Переписать чтоб не вызывать функцию дважды */
  7499. const newQuests = call.result.newQuests;
  7500. if (newQuests) {
  7501. for (let quest of newQuests) {
  7502. if (quest.id < 1e6 && quest.state == 2) {
  7503. reSend = true;
  7504. }
  7505. }
  7506. }
  7507. }
  7508. setProgress(I18N('COLLECT_REWARDS_AND_MAIL', { countQuests, countMail }), true);
  7509. if (reSend) {
  7510. rewardsAndMailFarm()
  7511. }
  7512. resolve();
  7513. });
  7514. });
  7515. })
  7516. }
  7517.  
  7518. class epicBrawl {
  7519. timeout = null;
  7520. time = null;
  7521.  
  7522. constructor() {
  7523. if (epicBrawl.inst) {
  7524. return epicBrawl.inst;
  7525. }
  7526. epicBrawl.inst = this;
  7527. return this;
  7528. }
  7529.  
  7530. runTimeout(func, timeDiff) {
  7531. const worker = new Worker(URL.createObjectURL(new Blob([`
  7532. self.onmessage = function(e) {
  7533. const timeDiff = e.data;
  7534.  
  7535. if (timeDiff > 0) {
  7536. setTimeout(() => {
  7537. self.postMessage(1);
  7538. self.close();
  7539. }, timeDiff);
  7540. }
  7541. };
  7542. `])));
  7543. worker.postMessage(timeDiff);
  7544. worker.onmessage = () => {
  7545. func();
  7546. };
  7547. return true;
  7548. }
  7549.  
  7550. timeDiff(date1, date2) {
  7551. const date1Obj = new Date(date1);
  7552. const date2Obj = new Date(date2);
  7553.  
  7554. const timeDiff = Math.abs(date2Obj - date1Obj);
  7555.  
  7556. const totalSeconds = timeDiff / 1000;
  7557. const minutes = Math.floor(totalSeconds / 60);
  7558. const seconds = Math.floor(totalSeconds % 60);
  7559.  
  7560. const formattedMinutes = String(minutes).padStart(2, '0');
  7561. const formattedSeconds = String(seconds).padStart(2, '0');
  7562.  
  7563. return `${formattedMinutes}:${formattedSeconds}`;
  7564. }
  7565.  
  7566. check() {
  7567. console.log(new Date(this.time))
  7568. if (Date.now() > this.time) {
  7569. this.timeout = null;
  7570. this.start()
  7571. return;
  7572. }
  7573. this.timeout = this.runTimeout(() => this.check(), 6e4);
  7574. return this.timeDiff(this.time, Date.now())
  7575. }
  7576.  
  7577. async start() {
  7578. if (this.timeout) {
  7579. const time = this.timeDiff(this.time, Date.now());
  7580. console.log(new Date(this.time))
  7581. setProgress(I18N('TIMER_ALREADY', { time }), false, hideProgress);
  7582. return;
  7583. }
  7584. setProgress(I18N('EPIC_BRAWL'), false, hideProgress);
  7585. 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));
  7586. const refill = teamInfo[2].refillable.find(n => n.id == 52)
  7587. this.time = (refill.lastRefill + 3600) * 1000
  7588. const attempts = refill.amount;
  7589. if (!attempts) {
  7590. console.log(new Date(this.time));
  7591. const time = this.check();
  7592. setProgress(I18N('NO_ATTEMPTS_TIMER_START', { time }), false, hideProgress);
  7593. return;
  7594. }
  7595.  
  7596. if (!teamInfo[0].epic_brawl) {
  7597. setProgress(I18N('NO_HEROES_PACK'), false, hideProgress);
  7598. return;
  7599. }
  7600.  
  7601. const args = {
  7602. heroes: teamInfo[0].epic_brawl.filter(e => e < 1000),
  7603. pet: teamInfo[0].epic_brawl.filter(e => e > 6000).pop(),
  7604. favor: teamInfo[1].epic_brawl,
  7605. }
  7606.  
  7607. let wins = 0;
  7608. let coins = 0;
  7609. let streak = { progress: 0, nextStage: 0 };
  7610. for (let i = attempts; i > 0; i--) {
  7611. const info = await Send(JSON.stringify({
  7612. calls: [
  7613. { name: "epicBrawl_getEnemy", args: {}, ident: "epicBrawl_getEnemy" }, { name: "epicBrawl_startBattle", args, ident: "epicBrawl_startBattle" }
  7614. ]
  7615. })).then(e => e.results.map(n => n.result.response));
  7616.  
  7617. const { progress, result } = await Calc(info[1].battle);
  7618. 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));
  7619.  
  7620. const resultInfo = endResult[0].result;
  7621. streak = endResult[1];
  7622.  
  7623. wins += resultInfo.win;
  7624. coins += resultInfo.reward ? resultInfo.reward.coin[39] : 0;
  7625.  
  7626. console.log(endResult[0].result)
  7627. if (endResult[1].progress == endResult[1].nextStage) {
  7628. const farm = await Send('{"calls":[{"name":"epicBrawl_farmWinStreak","args":{},"ident":"body"}]}').then(e => e.results[0].result.response);
  7629. coins += farm.coin[39];
  7630. }
  7631.  
  7632. setProgress(I18N('EPIC_BRAWL_RESULT', {
  7633. i, wins, attempts, coins,
  7634. progress: streak.progress,
  7635. nextStage: streak.nextStage,
  7636. end: '',
  7637. }), false, hideProgress);
  7638. }
  7639.  
  7640. console.log(new Date(this.time));
  7641. const time = this.check();
  7642. setProgress(I18N('EPIC_BRAWL_RESULT', {
  7643. wins, attempts, coins,
  7644. i: '',
  7645. progress: streak.progress,
  7646. nextStage: streak.nextStage,
  7647. end: I18N('ATTEMPT_ENDED', { time }),
  7648. }), false, hideProgress);
  7649. }
  7650. }
  7651.  
  7652. function countdownTimer(seconds, message) {
  7653. message = message || I18N('TIMER');
  7654. const stopTimer = Date.now() + seconds * 1e3
  7655. return new Promise(resolve => {
  7656. const interval = setInterval(async () => {
  7657. const now = Date.now();
  7658. setProgress(`${message} ${((stopTimer - now) / 1000).toFixed(2)}`, false);
  7659. if (now > stopTimer) {
  7660. clearInterval(interval);
  7661. setProgress('', 1);
  7662. resolve();
  7663. }
  7664. }, 100);
  7665. });
  7666. }
  7667.  
  7668. /** Набить килов в горниле душк */
  7669. async function bossRatingEventSouls() {
  7670. const data = await Send({
  7671. calls: [
  7672. { name: "heroGetAll", args: {}, ident: "teamGetAll" },
  7673. { name: "offerGetAll", args: {}, ident: "offerGetAll" },
  7674. { name: "pet_getAll", args: {}, ident: "pet_getAll" },
  7675. ]
  7676. });
  7677. const bossEventInfo = data.results[1].result.response.find(e => e.offerType == "bossEvent");
  7678. if (!bossEventInfo) {
  7679. setProgress('Эвент завершен', true);
  7680. return;
  7681. }
  7682.  
  7683. if (bossEventInfo.progress.score > 250) {
  7684. setProgress('Уже убито больше 250 врагов');
  7685. rewardBossRatingEventSouls();
  7686. return;
  7687. }
  7688. const availablePets = Object.values(data.results[2].result.response).map(e => e.id);
  7689. const heroGetAllList = data.results[0].result.response;
  7690. const usedHeroes = bossEventInfo.progress.usedHeroes;
  7691. const heroList = [];
  7692.  
  7693. for (let heroId in heroGetAllList) {
  7694. let hero = heroGetAllList[heroId];
  7695. if (usedHeroes.includes(hero.id)) {
  7696. continue;
  7697. }
  7698. heroList.push(hero.id);
  7699. }
  7700.  
  7701. if (!heroList.length) {
  7702. setProgress('Нет героев', true);
  7703. return;
  7704. }
  7705.  
  7706. const pet = availablePets.includes(6005) ? 6005 : availablePets[Math.floor(Math.random() * availablePets.length)];
  7707. const petLib = lib.getData('pet');
  7708. let count = 1;
  7709.  
  7710. for (const heroId of heroList) {
  7711. const args = {
  7712. heroes: [heroId],
  7713. pet
  7714. }
  7715. /** Поиск питомца для героя */
  7716. for (const petId of availablePets) {
  7717. if (petLib[petId].favorHeroes.includes(heroId)) {
  7718. args.favor = {
  7719. [heroId]: petId
  7720. }
  7721. break;
  7722. }
  7723. }
  7724.  
  7725. const calls = [{
  7726. name: "bossRatingEvent_startBattle",
  7727. args,
  7728. ident: "body"
  7729. }, {
  7730. name: "offerGetAll",
  7731. args: {},
  7732. ident: "offerGetAll"
  7733. }];
  7734.  
  7735. const res = await Send({ calls });
  7736. count++;
  7737.  
  7738. if ('error' in res) {
  7739. console.error(res.error);
  7740. setProgress('Перезагрузите игру и попробуйте позже', true);
  7741. return;
  7742. }
  7743.  
  7744. const eventInfo = res.results[1].result.response.find(e => e.offerType == "bossEvent");
  7745. if (eventInfo.progress.score > 250) {
  7746. break;
  7747. }
  7748. setProgress('Количество убитых врагов: ' + eventInfo.progress.score + '<br>Использовано ' + count + ' героев');
  7749. }
  7750.  
  7751. rewardBossRatingEventSouls();
  7752. }
  7753. /** Сбор награды из Горнила Душ */
  7754. async function rewardBossRatingEventSouls() {
  7755. const data = await Send({
  7756. calls: [
  7757. { name: "offerGetAll", args: {}, ident: "offerGetAll" }
  7758. ]
  7759. });
  7760.  
  7761. const bossEventInfo = data.results[0].result.response.find(e => e.offerType == "bossEvent");
  7762. if (!bossEventInfo) {
  7763. setProgress('Эвент завершен', true);
  7764. return;
  7765. }
  7766.  
  7767. const farmedChests = bossEventInfo.progress.farmedChests;
  7768. const score = bossEventInfo.progress.score;
  7769. // setProgress('Количество убитых врагов: ' + score);
  7770. const revard = bossEventInfo.reward;
  7771. const calls = [];
  7772.  
  7773. let count = 0;
  7774. for (let i = 1; i < 10; i++) {
  7775. if (farmedChests.includes(i)) {
  7776. continue;
  7777. }
  7778. if (score < revard[i].score) {
  7779. break;
  7780. }
  7781. calls.push({
  7782. name: "bossRatingEvent_getReward",
  7783. args: {
  7784. rewardId: i
  7785. },
  7786. ident: "body_" + i
  7787. });
  7788. count++;
  7789. }
  7790. if (!count) {
  7791. setProgress('Нечего собирать', true);
  7792. return;
  7793. }
  7794.  
  7795. Send({ calls }).then(e => {
  7796. console.log(e);
  7797. setProgress('Собрано ' + e?.results?.length + ' наград', true);
  7798. })
  7799. }
  7800. /**
  7801. * Spin the Seer
  7802. *
  7803. * Покрутить провидца
  7804. */
  7805. async function rollAscension() {
  7806. const refillable = await Send({calls:[
  7807. {
  7808. name:"userGetInfo",
  7809. args:{},
  7810. ident:"userGetInfo"
  7811. }
  7812. ]}).then(e => e.results[0].result.response.refillable);
  7813. const i47 = refillable.find(i => i.id == 47);
  7814. if (i47?.amount) {
  7815. await Send({ calls: [{ name: "ascensionChest_open", args: { paid: false, amount: 1 }, ident: "body" }] });
  7816. setProgress(I18N('DONE'), true);
  7817. } else {
  7818. setProgress(I18N('NOT_ENOUGH_AP'), true);
  7819. }
  7820. }
  7821.  
  7822. /**
  7823. * Collect gifts for the New Year
  7824. *
  7825. * Собрать подарки на новый год
  7826. */
  7827. function getGiftNewYear() {
  7828. Send({ calls: [{ name: "newYearGiftGet", args: { type: 0 }, ident: "body" }] }).then(e => {
  7829. const gifts = e.results[0].result.response.gifts;
  7830. const calls = gifts.filter(e => e.opened == 0).map(e => ({
  7831. name: "newYearGiftOpen",
  7832. args: {
  7833. giftId: e.id
  7834. },
  7835. ident: `body_${e.id}`
  7836. }));
  7837. if (!calls.length) {
  7838. setProgress(I18N('NY_NO_GIFTS'), 5000);
  7839. return;
  7840. }
  7841. Send({ calls }).then(e => {
  7842. console.log(e.results)
  7843. const msg = I18N('NY_GIFTS_COLLECTED', { count: e.results.length });
  7844. console.log(msg);
  7845. setProgress(msg, 5000);
  7846. });
  7847. })
  7848. }
  7849.  
  7850. async function updateArtifacts() {
  7851. const count = +await popup.confirm(I18N('SET_NUMBER_LEVELS'), [
  7852. { msg: I18N('BTN_GO'), isInput: true, default: 10 },
  7853. { result: false, isClose: true }
  7854. ]);
  7855. if (!count) {
  7856. return;
  7857. }
  7858. const quest = new questRun;
  7859. await quest.autoInit();
  7860. const heroes = Object.values(quest.questInfo['heroGetAll']);
  7861. const inventory = quest.questInfo['inventoryGet'];
  7862. const calls = [];
  7863. for (let i = count; i > 0; i--) {
  7864. const upArtifact = quest.getUpgradeArtifact();
  7865. if (!upArtifact.heroId) {
  7866. if (await popup.confirm(I18N('POSSIBLE_IMPROVE_LEVELS', { count: calls.length }), [
  7867. { msg: I18N('YES'), result: true },
  7868. { result: false, isClose: true }
  7869. ])) {
  7870. break;
  7871. } else {
  7872. return;
  7873. }
  7874. }
  7875. const hero = heroes.find(e => e.id == upArtifact.heroId);
  7876. hero.artifacts[upArtifact.slotId].level++;
  7877. inventory[upArtifact.costСurrency][upArtifact.costId] -= upArtifact.costValue;
  7878. calls.push({
  7879. name: "heroArtifactLevelUp",
  7880. args: {
  7881. heroId: upArtifact.heroId,
  7882. slotId: upArtifact.slotId
  7883. },
  7884. ident: `heroArtifactLevelUp_${i}`
  7885. });
  7886. }
  7887.  
  7888. if (!calls.length) {
  7889. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  7890. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  7891. return;
  7892. }
  7893.  
  7894. await Send(JSON.stringify({ calls })).then(e => {
  7895. if ('error' in e) {
  7896. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  7897. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  7898. } else {
  7899. console.log(I18N('IMPROVED_LEVELS', { count: e.results.length }));
  7900. setProgress(I18N('IMPROVED_LEVELS', { count: e.results.length }), false);
  7901. }
  7902. });
  7903. }
  7904.  
  7905. window.sign = a => {
  7906. const i = this['\x78\x79\x7a'];
  7907. return md5([i['\x6e\x61\x6d\x65'], i['\x76\x65\x72\x73\x69\x6f\x6e'], i['\x61\x75\x74\x68\x6f\x72'], ~(a % 1e3)]['\x6a\x6f\x69\x6e']('\x5f'))
  7908. }
  7909.  
  7910. async function updateSkins() {
  7911. const count = +await popup.confirm(I18N('SET_NUMBER_LEVELS'), [
  7912. { msg: I18N('BTN_GO'), isInput: true, default: 10 },
  7913. { result: false, isClose: true }
  7914. ]);
  7915. if (!count) {
  7916. return;
  7917. }
  7918.  
  7919. const quest = new questRun;
  7920. await quest.autoInit();
  7921. const heroes = Object.values(quest.questInfo['heroGetAll']);
  7922. const inventory = quest.questInfo['inventoryGet'];
  7923. const calls = [];
  7924. for (let i = count; i > 0; i--) {
  7925. const upSkin = quest.getUpgradeSkin();
  7926. if (!upSkin.heroId) {
  7927. if (await popup.confirm(I18N('POSSIBLE_IMPROVE_LEVELS', { count: calls.length }), [
  7928. { msg: I18N('YES'), result: true },
  7929. { result: false, isClose: true }
  7930. ])) {
  7931. break;
  7932. } else {
  7933. return;
  7934. }
  7935. }
  7936. const hero = heroes.find(e => e.id == upSkin.heroId);
  7937. hero.skins[upSkin.skinId]++;
  7938. inventory[upSkin.costСurrency][upSkin.costСurrencyId] -= upSkin.cost;
  7939. calls.push({
  7940. name: "heroSkinUpgrade",
  7941. args: {
  7942. heroId: upSkin.heroId,
  7943. skinId: upSkin.skinId
  7944. },
  7945. ident: `heroSkinUpgrade_${i}`
  7946. })
  7947. }
  7948.  
  7949. if (!calls.length) {
  7950. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  7951. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  7952. return;
  7953. }
  7954.  
  7955. await Send(JSON.stringify({ calls })).then(e => {
  7956. if ('error' in e) {
  7957. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  7958. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  7959. } else {
  7960. console.log(I18N('IMPROVED_LEVELS', { count: e.results.length }));
  7961. setProgress(I18N('IMPROVED_LEVELS', { count: e.results.length }), false);
  7962. }
  7963. });
  7964. }
  7965.  
  7966. function getQuestionInfo(img, nameOnly = false) {
  7967. const libHeroes = Object.values(lib.data.hero);
  7968. const parts = img.split(':');
  7969. const id = parts[1];
  7970. switch (parts[0]) {
  7971. case 'titanArtifact_id':
  7972. return cheats.translate("LIB_TITAN_ARTIFACT_NAME_" + id);
  7973. case 'titan':
  7974. return cheats.translate("LIB_HERO_NAME_" + id);
  7975. case 'skill':
  7976. return cheats.translate("LIB_SKILL_" + id);
  7977. case 'inventoryItem_gear':
  7978. return cheats.translate("LIB_GEAR_NAME_" + id);
  7979. case 'inventoryItem_coin':
  7980. return cheats.translate("LIB_COIN_NAME_" + id);
  7981. case 'artifact':
  7982. if (nameOnly) {
  7983. return cheats.translate("LIB_ARTIFACT_NAME_" + id);
  7984. }
  7985. heroes = libHeroes.filter(h => h.id < 100 && h.artifacts.includes(+id));
  7986. return {
  7987. /** Как называется этот артефакт? */
  7988. name: cheats.translate("LIB_ARTIFACT_NAME_" + id),
  7989. /** Какому герою принадлежит этот артефакт? */
  7990. heroes: heroes.map(h => cheats.translate("LIB_HERO_NAME_" + h.id))
  7991. };
  7992. case 'hero':
  7993. if (nameOnly) {
  7994. return cheats.translate("LIB_HERO_NAME_" + id);
  7995. }
  7996. artifacts = lib.data.hero[id].artifacts;
  7997. return {
  7998. /** Как зовут этого героя? */
  7999. name: cheats.translate("LIB_HERO_NAME_" + id),
  8000. /** Какой артефакт принадлежит этому герою? */
  8001. artifact: artifacts.map(a => cheats.translate("LIB_ARTIFACT_NAME_" + a))
  8002. };
  8003. }
  8004. }
  8005.  
  8006. function hintQuest(quest) {
  8007. const result = {};
  8008. if (quest?.questionIcon) {
  8009. const info = getQuestionInfo(quest.questionIcon);
  8010. if (info?.heroes) {
  8011. /** Какому герою принадлежит этот артефакт? */
  8012. result.answer = quest.answers.filter(e => info.heroes.includes(e.answerText.slice(1)));
  8013. }
  8014. if (info?.artifact) {
  8015. /** Какой артефакт принадлежит этому герою? */
  8016. result.answer = quest.answers.filter(e => info.artifact.includes(e.answerText.slice(1)));
  8017. }
  8018. if (typeof info == 'string') {
  8019. result.info = { name: info };
  8020. } else {
  8021. result.info = info;
  8022. }
  8023. }
  8024.  
  8025. if (quest.answers[0]?.answerIcon) {
  8026. result.answer = quest.answers.filter(e => quest.question.includes(getQuestionInfo(e.answerIcon, true)))
  8027. }
  8028.  
  8029. if ((!result?.answer || !result.answer.length) && !result.info?.name) {
  8030. return false;
  8031. }
  8032.  
  8033. let resultText = '';
  8034. if (result?.info) {
  8035. resultText += I18N('PICTURE') + result.info.name;
  8036. }
  8037. console.log(result);
  8038. if (result?.answer && result.answer.length) {
  8039. resultText += I18N('ANSWER') + result.answer[0].id + (!result.answer[0].answerIcon ? ' - ' + result.answer[0].answerText : '');
  8040. }
  8041.  
  8042. return resultText;
  8043. }
  8044.  
  8045. /**
  8046. * Attack of the minions of Asgard
  8047. *
  8048. * Атака прислужников Асгарда
  8049. */
  8050. function testRaidNodes() {
  8051. return new Promise((resolve, reject) => {
  8052. const tower = new executeRaidNodes(resolve, reject);
  8053. tower.start();
  8054. });
  8055. }
  8056.  
  8057. /**
  8058. * Attack of the minions of Asgard
  8059. *
  8060. * Атака прислужников Асгарда
  8061. */
  8062. function executeRaidNodes(resolve, reject) {
  8063. let raidData = {
  8064. teams: [],
  8065. favor: {},
  8066. nodes: [],
  8067. attempts: 0,
  8068. countExecuteBattles: 0,
  8069. cancelBattle: 0,
  8070. }
  8071.  
  8072. callsExecuteRaidNodes = {
  8073. calls: [{
  8074. name: "clanRaid_getInfo",
  8075. args: {},
  8076. ident: "clanRaid_getInfo"
  8077. }, {
  8078. name: "teamGetAll",
  8079. args: {},
  8080. ident: "teamGetAll"
  8081. }, {
  8082. name: "teamGetFavor",
  8083. args: {},
  8084. ident: "teamGetFavor"
  8085. }]
  8086. }
  8087.  
  8088. this.start = function () {
  8089. send(JSON.stringify(callsExecuteRaidNodes), startRaidNodes);
  8090. }
  8091.  
  8092. async function startRaidNodes(data) {
  8093. res = data.results;
  8094. clanRaidInfo = res[0].result.response;
  8095. teamGetAll = res[1].result.response;
  8096. teamGetFavor = res[2].result.response;
  8097.  
  8098. let index = 0;
  8099. let isNotFullPack = false;
  8100. for (let team of teamGetAll.clanRaid_nodes) {
  8101. if (team.length < 6) {
  8102. isNotFullPack = true;
  8103. }
  8104. raidData.teams.push({
  8105. data: {},
  8106. heroes: team.filter(id => id < 6000),
  8107. pet: team.filter(id => id >= 6000).pop(),
  8108. battleIndex: index++
  8109. });
  8110. }
  8111. raidData.favor = teamGetFavor.clanRaid_nodes;
  8112.  
  8113. if (isNotFullPack) {
  8114. if (await popup.confirm(I18N('MINIONS_WARNING'), [
  8115. { msg: I18N('BTN_NO'), result: true },
  8116. { msg: I18N('BTN_YES'), result: false },
  8117. ])) {
  8118. endRaidNodes('isNotFullPack');
  8119. return;
  8120. }
  8121. }
  8122.  
  8123. raidData.nodes = clanRaidInfo.nodes;
  8124. raidData.attempts = clanRaidInfo.attempts;
  8125. isCancalBattle = false;
  8126.  
  8127. checkNodes();
  8128. }
  8129.  
  8130. function getAttackNode() {
  8131. for (let nodeId in raidData.nodes) {
  8132. let node = raidData.nodes[nodeId];
  8133. let points = 0
  8134. for (team of node.teams) {
  8135. points += team.points;
  8136. }
  8137. let now = Date.now() / 1000;
  8138. if (!points && now > node.timestamps.start && now < node.timestamps.end) {
  8139. let countTeam = node.teams.length;
  8140. delete raidData.nodes[nodeId];
  8141. return {
  8142. nodeId,
  8143. countTeam
  8144. };
  8145. }
  8146. }
  8147. return null;
  8148. }
  8149.  
  8150. function checkNodes() {
  8151. setProgress(`${I18N('REMAINING_ATTEMPTS')}: ${raidData.attempts}`);
  8152. let nodeInfo = getAttackNode();
  8153. if (nodeInfo && raidData.attempts) {
  8154. startNodeBattles(nodeInfo);
  8155. return;
  8156. }
  8157.  
  8158. endRaidNodes('EndRaidNodes');
  8159. }
  8160.  
  8161. function startNodeBattles(nodeInfo) {
  8162. let {nodeId, countTeam} = nodeInfo;
  8163. let teams = raidData.teams.slice(0, countTeam);
  8164. let heroes = raidData.teams.map(e => e.heroes).flat();
  8165. let favor = {...raidData.favor};
  8166. for (let heroId in favor) {
  8167. if (!heroes.includes(+heroId)) {
  8168. delete favor[heroId];
  8169. }
  8170. }
  8171.  
  8172. let calls = [{
  8173. name: "clanRaid_startNodeBattles",
  8174. args: {
  8175. nodeId,
  8176. teams,
  8177. favor
  8178. },
  8179. ident: "body"
  8180. }];
  8181.  
  8182. send(JSON.stringify({calls}), resultNodeBattles);
  8183. }
  8184.  
  8185. function resultNodeBattles(e) {
  8186. if (e['error']) {
  8187. endRaidNodes('nodeBattlesError', e['error']);
  8188. return;
  8189. }
  8190.  
  8191. console.log(e);
  8192. let battles = e.results[0].result.response.battles;
  8193. let promises = [];
  8194. let battleIndex = 0;
  8195. for (let battle of battles) {
  8196. battle.battleIndex = battleIndex++;
  8197. promises.push(calcBattleResult(battle));
  8198. }
  8199.  
  8200. Promise.all(promises)
  8201. .then(results => {
  8202. const endResults = {};
  8203. let isAllWin = true;
  8204. for (let r of results) {
  8205. isAllWin &&= r.result.win;
  8206. }
  8207. if (!isAllWin) {
  8208. cancelEndNodeBattle(results[0]);
  8209. return;
  8210. }
  8211. raidData.countExecuteBattles = results.length;
  8212. let timeout = 500;
  8213. for (let r of results) {
  8214. setTimeout(endNodeBattle, timeout, r);
  8215. timeout += 500;
  8216. }
  8217. });
  8218. }
  8219. /**
  8220. * Returns the battle calculation promise
  8221. *
  8222. * Возвращает промис расчета боя
  8223. */
  8224. function calcBattleResult(battleData) {
  8225. return new Promise(function (resolve, reject) {
  8226. BattleCalc(battleData, "get_clanPvp", resolve);
  8227. });
  8228. }
  8229. /**
  8230. * Cancels the fight
  8231. *
  8232. * Отменяет бой
  8233. */
  8234. function cancelEndNodeBattle(r) {
  8235. const fixBattle = function (heroes) {
  8236. for (const ids in heroes) {
  8237. hero = heroes[ids];
  8238. hero.energy = random(1, 999);
  8239. if (hero.hp > 0) {
  8240. hero.hp = random(1, hero.hp);
  8241. }
  8242. }
  8243. }
  8244. fixBattle(r.progress[0].attackers.heroes);
  8245. fixBattle(r.progress[0].defenders.heroes);
  8246. endNodeBattle(r);
  8247. }
  8248. /**
  8249. * Ends the fight
  8250. *
  8251. * Завершает бой
  8252. */
  8253. function endNodeBattle(r) {
  8254. let nodeId = r.battleData.result.nodeId;
  8255. let battleIndex = r.battleData.battleIndex;
  8256. let calls = [{
  8257. name: "clanRaid_endNodeBattle",
  8258. args: {
  8259. nodeId,
  8260. battleIndex,
  8261. result: r.result,
  8262. progress: r.progress
  8263. },
  8264. ident: "body"
  8265. }]
  8266.  
  8267. SendRequest(JSON.stringify({calls}), battleResult);
  8268. }
  8269. /**
  8270. * Processing the results of the battle
  8271. *
  8272. * Обработка результатов боя
  8273. */
  8274. function battleResult(e) {
  8275. if (e['error']) {
  8276. endRaidNodes('missionEndError', e['error']);
  8277. return;
  8278. }
  8279. r = e.results[0].result.response;
  8280. if (r['error']) {
  8281. if (r.reason == "invalidBattle") {
  8282. raidData.cancelBattle++;
  8283. checkNodes();
  8284. } else {
  8285. endRaidNodes('missionEndError', e['error']);
  8286. }
  8287. return;
  8288. }
  8289.  
  8290. if (!(--raidData.countExecuteBattles)) {
  8291. raidData.attempts--;
  8292. checkNodes();
  8293. }
  8294. }
  8295. /**
  8296. * Completing a task
  8297. *
  8298. * Завершение задачи
  8299. */
  8300. function endRaidNodes(reason, info) {
  8301. isCancalBattle = true;
  8302. let textCancel = raidData.cancelBattle ? ` ${I18N('BATTLES_CANCELED')}: ${raidData.cancelBattle}` : '';
  8303. setProgress(`${I18N('MINION_RAID')} ${I18N('COMPLETED')}! ${textCancel}`, true);
  8304. console.log(reason, info);
  8305. resolve();
  8306. }
  8307. }
  8308.  
  8309. /**
  8310. * Asgard Boss Attack Replay
  8311. *
  8312. * Повтор атаки босса Асгарда
  8313. */
  8314. function testBossBattle() {
  8315. return new Promise((resolve, reject) => {
  8316. const bossBattle = new executeBossBattle(resolve, reject);
  8317. bossBattle.start(lastBossBattle, lastBossBattleInfo);
  8318. });
  8319. }
  8320.  
  8321. /**
  8322. * Asgard Boss Attack Replay
  8323. *
  8324. * Повтор атаки босса Асгарда
  8325. */
  8326. function executeBossBattle(resolve, reject) {
  8327. let lastBossBattleArgs = {};
  8328. let reachDamage = 0;
  8329. let countBattle = 0;
  8330. let countMaxBattle = 10;
  8331. let lastDamage = 0;
  8332.  
  8333. this.start = function (battleArg, battleInfo) {
  8334. lastBossBattleArgs = battleArg;
  8335. preCalcBattle(battleInfo);
  8336. }
  8337.  
  8338. function getBattleInfo(battle) {
  8339. return new Promise(function (resolve) {
  8340. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  8341. BattleCalc(battle, getBattleType(battle.type), e => {
  8342. let extra = e.progress[0].defenders.heroes[1].extra;
  8343. resolve(extra.damageTaken + extra.damageTakenNextLevel);
  8344. });
  8345. });
  8346. }
  8347.  
  8348. function preCalcBattle(battle) {
  8349. let actions = [];
  8350. const countTestBattle = getInput('countTestBattle');
  8351. for (let i = 0; i < countTestBattle; i++) {
  8352. actions.push(getBattleInfo(battle, true));
  8353. }
  8354. Promise.all(actions)
  8355. .then(resultPreCalcBattle);
  8356. }
  8357.  
  8358. function fixDamage(damage) {
  8359. for (let i = 1e6; i > 1; i /= 10) {
  8360. if (damage > i) {
  8361. let n = i / 10;
  8362. damage = Math.ceil(damage / n) * n;
  8363. break;
  8364. }
  8365. }
  8366. return damage;
  8367. }
  8368.  
  8369. async function resultPreCalcBattle(damages) {
  8370. let maxDamage = 0;
  8371. let minDamage = 1e10;
  8372. let avgDamage = 0;
  8373. for (let damage of damages) {
  8374. avgDamage += damage
  8375. if (damage > maxDamage) {
  8376. maxDamage = damage;
  8377. }
  8378. if (damage < minDamage) {
  8379. minDamage = damage;
  8380. }
  8381. }
  8382. avgDamage /= damages.length;
  8383. console.log(damages.map(e => e.toLocaleString()).join('\n'), avgDamage, maxDamage);
  8384.  
  8385. reachDamage = fixDamage(avgDamage);
  8386. const result = await popup.confirm(
  8387. `${I18N('ROUND_STAT')} ${damages.length} ${I18N('BATTLE')}:` +
  8388. `<br>${I18N('MINIMUM')}: ` + minDamage.toLocaleString() +
  8389. `<br>${I18N('MAXIMUM')}: ` + maxDamage.toLocaleString() +
  8390. `<br>${I18N('AVERAGE')}: ` + avgDamage.toLocaleString()
  8391. /*+ '<br>Поиск урона больше чем ' + reachDamage.toLocaleString()*/
  8392. , [
  8393. { msg: I18N('BTN_OK'), result: 0},
  8394. /* {msg: 'Погнали', isInput: true, default: reachDamage}, */
  8395. ])
  8396. if (result) {
  8397. reachDamage = result;
  8398. isCancalBossBattle = false;
  8399. startBossBattle();
  8400. return;
  8401. }
  8402. endBossBattle(I18N('BTN_CANCEL'));
  8403. }
  8404.  
  8405. function startBossBattle() {
  8406. countBattle++;
  8407. countMaxBattle = getInput('countAutoBattle');
  8408. if (countBattle > countMaxBattle) {
  8409. setProgress('Превышен лимит попыток: ' + countMaxBattle, true);
  8410. endBossBattle('Превышен лимит попыток: ' + countMaxBattle);
  8411. return;
  8412. }
  8413. let calls = [{
  8414. name: "clanRaid_startBossBattle",
  8415. args: lastBossBattleArgs,
  8416. ident: "body"
  8417. }];
  8418. send(JSON.stringify({calls}), calcResultBattle);
  8419. }
  8420.  
  8421. function calcResultBattle(e) {
  8422. BattleCalc(e.results[0].result.response.battle, "get_clanPvp", resultBattle);
  8423. }
  8424.  
  8425. async function resultBattle(e) {
  8426. let extra = e.progress[0].defenders.heroes[1].extra
  8427. resultDamage = extra.damageTaken + extra.damageTakenNextLevel
  8428. console.log(resultDamage);
  8429. scriptMenu.setStatus(countBattle + ') ' + resultDamage.toLocaleString());
  8430. lastDamage = resultDamage;
  8431. if (resultDamage > reachDamage && await popup.confirm(countBattle + ') Урон ' + resultDamage.toLocaleString(), [
  8432. {msg: 'Ок', result: true},
  8433. {msg: 'Не пойдет', result: false},
  8434. ])) {
  8435. endBattle(e, false);
  8436. return;
  8437. }
  8438. cancelEndBattle(e);
  8439. }
  8440.  
  8441. function cancelEndBattle (r) {
  8442. const fixBattle = function (heroes) {
  8443. for (const ids in heroes) {
  8444. hero = heroes[ids];
  8445. hero.energy = random(1, 999);
  8446. if (hero.hp > 0) {
  8447. hero.hp = random(1, hero.hp);
  8448. }
  8449. }
  8450. }
  8451. fixBattle(r.progress[0].attackers.heroes);
  8452. fixBattle(r.progress[0].defenders.heroes);
  8453. endBattle(r, true);
  8454. }
  8455.  
  8456. function endBattle(battleResult, isCancal) {
  8457. let calls = [{
  8458. name: "clanRaid_endBossBattle",
  8459. args: {
  8460. result: battleResult.result,
  8461. progress: battleResult.progress
  8462. },
  8463. ident: "body"
  8464. }];
  8465.  
  8466. send(JSON.stringify({calls}), e => {
  8467. console.log(e);
  8468. if (isCancal) {
  8469. startBossBattle();
  8470. return;
  8471. }
  8472. scriptMenu.setStatus('Босс пробит нанесен урон: ' + lastDamage);
  8473. setTimeout(() => {
  8474. scriptMenu.setStatus('');
  8475. }, 5000);
  8476. endBossBattle('Узпех!');
  8477. });
  8478. }
  8479.  
  8480. /**
  8481. * Completing a task
  8482. *
  8483. * Завершение задачи
  8484. */
  8485. function endBossBattle(reason, info) {
  8486. isCancalBossBattle = true;
  8487. console.log(reason, info);
  8488. resolve();
  8489. }
  8490. }
  8491.  
  8492. /**
  8493. * Auto-repeat attack
  8494. *
  8495. * Автоповтор атаки
  8496. */
  8497. function testAutoBattle() {
  8498. return new Promise((resolve, reject) => {
  8499. const bossBattle = new executeAutoBattle(resolve, reject);
  8500. bossBattle.start(lastBattleArg, lastBattleInfo);
  8501. });
  8502. }
  8503.  
  8504. /**
  8505. * Auto-repeat attack
  8506. *
  8507. * Автоповтор атаки
  8508. */
  8509. function executeAutoBattle(resolve, reject) {
  8510. let battleArg = {};
  8511. let countBattle = 0;
  8512. let countError = 0;
  8513. let findCoeff = 0;
  8514. let dataNotEeceived = 0;
  8515. const svgJustice = '<svg width="20" height="20" viewBox="0 0 124 125" xmlns="http://www.w3.org/2000/svg" style="fill: #fff;"><g><path d="m54 0h-1c-7.25 6.05-17.17 6.97-25.78 10.22-8.6 3.25-23.68 1.07-23.22 12.78s-0.47 24.08 1 35 2.36 18.36 7 28c4.43-8.31-3.26-18.88-3-30 0.26-11.11-2.26-25.29-1-37 11.88-4.16 26.27-0.42 36.77-9.23s20.53 6.05 29.23-0.77c-6.65-2.98-14.08-4.96-20-9z"/></g><g><path d="m108 5c-11.05 2.96-27.82 2.2-35.08 11.92s-14.91 14.71-22.67 23.33c-7.77 8.62-14.61 15.22-22.25 23.75 7.05 11.93 14.33 2.58 20.75-4.25 6.42-6.82 12.98-13.03 19.5-19.5s12.34-13.58 19.75-18.25c2.92 7.29-8.32 12.65-13.25 18.75-4.93 6.11-12.19 11.48-17.5 17.5s-12.31 11.38-17.25 17.75c10.34 14.49 17.06-3.04 26.77-10.23s15.98-16.89 26.48-24.52c10.5-7.64 12.09-24.46 14.75-36.25z"/></g><g><path d="m60 25c-11.52-6.74-24.53 8.28-38 6 0.84 9.61-1.96 20.2 2 29 5.53-4.04-4.15-23.2 4.33-26.67 8.48-3.48 18.14-1.1 24.67-8.33 2.73 0.3 4.81 2.98 7 0z"/></g><g><path d="m100 75c3.84-11.28 5.62-25.85 3-38-4.2 5.12-3.5 13.58-4 20s-3.52 13.18 1 18z"/></g><g><path d="m55 94c15.66-5.61 33.71-20.85 29-39-3.07 8.05-4.3 16.83-10.75 23.25s-14.76 8.35-18.25 15.75z"/></g><g><path d="m0 94v7c6.05 3.66 9.48 13.3 18 11-3.54-11.78 8.07-17.05 14-25 6.66 1.52 13.43 16.26 19 5-11.12-9.62-20.84-21.33-32-31-9.35 6.63 4.76 11.99 6 19-7.88 5.84-13.24 17.59-25 14z"/></g><g><path d="m82 125h26v-19h16v-1c-11.21-8.32-18.38-21.74-30-29-8.59 10.26-19.05 19.27-27 30h15v19z"/></g><g><path d="m68 110c-7.68-1.45-15.22 4.83-21.92-1.08s-11.94-5.72-18.08-11.92c-3.03 8.84 10.66 9.88 16.92 16.08s17.09 3.47 23.08-3.08z"/></g></svg>';
  8516. const svgBoss = '<svg width="20" height="20" viewBox="0 0 40 41" xmlns="http://www.w3.org/2000/svg" style="fill: #fff;"><g><path d="m21 12c-2.19-3.23 5.54-10.95-0.97-10.97-6.52-0.02 1.07 7.75-1.03 10.97-2.81 0.28-5.49-0.2-8-1-0.68 3.53 0.55 6.06 4 4 0.65 7.03 1.11 10.95 1.67 18.33 0.57 7.38 6.13 7.2 6.55-0.11 0.42-7.3 1.35-11.22 1.78-18.22 3.53 1.9 4.73-0.42 4-4-2.61 0.73-5.14 1.35-8 1m-1 17c-1.59-3.6-1.71-10.47 0-14 1.59 3.6 1.71 10.47 0 14z"/></g><g><path d="m6 19c-1.24-4.15 2.69-8.87 1-12-3.67 4.93-6.52 10.57-6 17 5.64-0.15 8.82 4.98 13 8 1.3-6.54-0.67-12.84-8-13z"/></g><g><path d="m33 7c0.38 5.57 2.86 14.79-7 15v10c4.13-2.88 7.55-7.97 13-8 0.48-6.46-2.29-12.06-6-17z"/></g></svg>';
  8517. const svgAttempt = '<svg width="20" height="20" viewBox="0 0 645 645" xmlns="http://www.w3.org/2000/svg" style="fill: #fff;"><g><path d="m442 26c-8.8 5.43-6.6 21.6-12.01 30.99-2.5 11.49-5.75 22.74-8.99 34.01-40.61-17.87-92.26-15.55-133.32-0.32-72.48 27.31-121.88 100.19-142.68 171.32 10.95-4.49 19.28-14.97 29.3-21.7 50.76-37.03 121.21-79.04 183.47-44.07 16.68 5.8 2.57 21.22-0.84 31.7-4.14 12.19-11.44 23.41-13.93 36.07 56.01-17.98 110.53-41.23 166-61-20.49-59.54-46.13-117.58-67-177z"/></g><g><path d="m563 547c23.89-16.34 36.1-45.65 47.68-71.32 23.57-62.18 7.55-133.48-28.38-186.98-15.1-22.67-31.75-47.63-54.3-63.7 1.15 14.03 6.71 26.8 8.22 40.78 12.08 61.99 15.82 148.76-48.15 183.29-10.46-0.54-15.99-16.1-24.32-22.82-8.2-7.58-14.24-19.47-23.75-24.25-4.88 59.04-11.18 117.71-15 177 62.9 5.42 126.11 9.6 189 15-4.84-9.83-17.31-15.4-24.77-24.23-9.02-7.06-17.8-15.13-26.23-22.77z"/></g><g><path d="m276 412c-10.69-15.84-30.13-25.9-43.77-40.23-15.39-12.46-30.17-25.94-45.48-38.52-15.82-11.86-29.44-28.88-46.75-37.25-19.07 24.63-39.96 48.68-60.25 72.75-18.71 24.89-42.41 47.33-58.75 73.25 22.4-2.87 44.99-13.6 66.67-13.67 0.06 22.8 10.69 42.82 20.41 62.59 49.09 93.66 166.6 114.55 261.92 96.08-6.07-9.2-22.11-9.75-31.92-16.08-59.45-26.79-138.88-75.54-127.08-151.92 21.66-2.39 43.42-4.37 65-7z"/></g></svg>';
  8518.  
  8519. this.start = function (battleArgs, battleInfo) {
  8520. battleArg = battleArgs;
  8521. preCalcBattle(battleInfo);
  8522. }
  8523. /**
  8524. * Returns a promise for combat recalculation
  8525. *
  8526. * Возвращает промис для прерасчета боя
  8527. */
  8528. function getBattleInfo(battle) {
  8529. return new Promise(function (resolve) {
  8530. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  8531. Calc(battle).then(e => {
  8532. e.coeff = calcCoeff(e, 'defenders');
  8533. resolve(e);
  8534. });
  8535. });
  8536. }
  8537. /**
  8538. * Battle recalculation
  8539. *
  8540. * Прерасчет боя
  8541. */
  8542. function preCalcBattle(battle) {
  8543. let actions = [];
  8544. const countTestBattle = getInput('countTestBattle');
  8545. for (let i = 0; i < countTestBattle; i++) {
  8546. actions.push(getBattleInfo(battle));
  8547. }
  8548. Promise.all(actions)
  8549. .then(resultPreCalcBattle);
  8550. }
  8551. /**
  8552. * Processing the results of the battle recalculation
  8553. *
  8554. * Обработка результатов прерасчета боя
  8555. */
  8556. async function resultPreCalcBattle(results) {
  8557. let countWin = results.reduce((s, w) => w.result.win + s, 0);
  8558. setProgress(`${I18N('CHANCE_TO_WIN')} ${Math.floor(countWin / results.length * 100)}% (${results.length})`, false, hideProgress);
  8559. if (countWin > 0) {
  8560. isCancalBattle = false;
  8561. startBattle();
  8562. return;
  8563. }
  8564.  
  8565. let minCoeff = 100;
  8566. let maxCoeff = -100;
  8567. let avgCoeff = 0;
  8568. results.forEach(e => {
  8569. if (e.coeff < minCoeff) minCoeff = e.coeff;
  8570. if (e.coeff > maxCoeff) maxCoeff = e.coeff;
  8571. avgCoeff += e.coeff;
  8572. });
  8573. avgCoeff /= results.length;
  8574.  
  8575. if (nameFuncStartBattle == 'invasion_bossStart' ||
  8576. nameFuncStartBattle == 'bossAttack') {
  8577. const result = await popup.confirm(
  8578. I18N('BOSS_VICTORY_IMPOSSIBLE', { battles: results.length }), [
  8579. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  8580. { msg: I18N('BTN_DO_IT'), result: true },
  8581. ])
  8582. if (result) {
  8583. isCancalBattle = false;
  8584. startBattle();
  8585. return;
  8586. }
  8587. setProgress(I18N('NOT_THIS_TIME'), true);
  8588. endAutoBattle('invasion_bossStart');
  8589. return;
  8590. }
  8591.  
  8592. const result = await popup.confirm(
  8593. I18N('VICTORY_IMPOSSIBLE') +
  8594. `<br>${I18N('ROUND_STAT')} ${results.length} ${I18N('BATTLE')}:` +
  8595. `<br>${I18N('MINIMUM')}: ` + minCoeff.toLocaleString() +
  8596. `<br>${I18N('MAXIMUM')}: ` + maxCoeff.toLocaleString() +
  8597. `<br>${I18N('AVERAGE')}: ` + avgCoeff.toLocaleString() +
  8598. `<br>${I18N('FIND_COEFF')} ` + avgCoeff.toLocaleString(), [
  8599. { msg: I18N('BTN_CANCEL'), result: 0, isCancel: true },
  8600. { msg: I18N('BTN_GO'), isInput: true, default: Math.round(avgCoeff * 1000) / 1000 },
  8601. ])
  8602. if (result) {
  8603. findCoeff = result;
  8604. isCancalBattle = false;
  8605. startBattle();
  8606. return;
  8607. }
  8608. setProgress(I18N('NOT_THIS_TIME'), true);
  8609. endAutoBattle(I18N('NOT_THIS_TIME'));
  8610. }
  8611.  
  8612. /**
  8613. * Calculation of the combat result coefficient
  8614. *
  8615. * Расчет коэфициента результата боя
  8616. */
  8617. function calcCoeff(result, packType) {
  8618. let beforeSumFactor = 0;
  8619. const beforePack = result.battleData[packType][0];
  8620. for (let heroId in beforePack) {
  8621. const hero = beforePack[heroId];
  8622. const state = hero.state;
  8623. let factor = 1;
  8624. if (state) {
  8625. const hp = state.hp / state.maxHp;
  8626. const energy = state.energy / 1e3;
  8627. factor = hp + energy / 20;
  8628. }
  8629. beforeSumFactor += factor;
  8630. }
  8631.  
  8632. let afterSumFactor = 0;
  8633. const afterPack = result.progress[0][packType].heroes;
  8634. for (let heroId in afterPack) {
  8635. const hero = afterPack[heroId];
  8636. const stateHp = beforePack[heroId]?.state?.hp || beforePack[heroId]?.stats?.hp;
  8637. const hp = hero.hp / stateHp;
  8638. const energy = hero.energy / 1e3;
  8639. const factor = hp + energy / 20;
  8640. afterSumFactor += factor;
  8641. }
  8642. const resultCoeff = -(afterSumFactor - beforeSumFactor);
  8643. return Math.round(resultCoeff * 1000) / 1000;
  8644. }
  8645. /**
  8646. * Start battle
  8647. *
  8648. * Начало боя
  8649. */
  8650. function startBattle() {
  8651. countBattle++;
  8652. const countMaxBattle = getInput('countAutoBattle');
  8653. // setProgress(countBattle + '/' + countMaxBattle);
  8654. if (countBattle > countMaxBattle) {
  8655. setProgress(`${I18N('RETRY_LIMIT_EXCEEDED')}: ${countMaxBattle}`, true);
  8656. endAutoBattle(`${I18N('RETRY_LIMIT_EXCEEDED')}: ${countMaxBattle}`)
  8657. return;
  8658. }
  8659. send({calls: [{
  8660. name: nameFuncStartBattle,
  8661. args: battleArg,
  8662. ident: "body"
  8663. }]}, calcResultBattle);
  8664. }
  8665. /**
  8666. * Battle calculation
  8667. *
  8668. * Расчет боя
  8669. */
  8670. async function calcResultBattle(e) {
  8671. if (!e) {
  8672. console.log('данные не были получены');
  8673. if (dataNotEeceived < 10) {
  8674. dataNotEeceived++;
  8675. startBattle();
  8676. return;
  8677. }
  8678. endAutoBattle('Error', 'данные не были получены ' + dataNotEeceived + ' раз');
  8679. return;
  8680. }
  8681. if ('error' in e) {
  8682. if (e.error.description === 'too many tries') {
  8683. invasionTimer += 100;
  8684. countBattle--;
  8685. countError++;
  8686. console.log(`Errors: ${countError}`, e.error);
  8687. startBattle();
  8688. return;
  8689. }
  8690. const result = await popup.confirm(I18N('ERROR_DURING_THE_BATTLE') + '<br>' + e.error.description, [
  8691. { msg: I18N('BTN_OK'), result: false },
  8692. { msg: I18N('RELOAD_GAME'), result: true },
  8693. ]);
  8694. endAutoBattle('Error', e.error);
  8695. if (result) {
  8696. location.reload();
  8697. }
  8698. return;
  8699. }
  8700. let battle = e.results[0].result.response.battle
  8701. if (nameFuncStartBattle == 'towerStartBattle' ||
  8702. nameFuncStartBattle == 'bossAttack' ||
  8703. nameFuncStartBattle == 'invasion_bossStart') {
  8704. battle = e.results[0].result.response;
  8705. }
  8706. lastBattleInfo = battle;
  8707. BattleCalc(battle, getBattleType(battle.type), resultBattle);
  8708. }
  8709. /**
  8710. * Processing the results of the battle
  8711. *
  8712. * Обработка результатов боя
  8713. */
  8714. function resultBattle(e) {
  8715. const isWin = e.result.win;
  8716. if (isWin) {
  8717. endBattle(e, false);
  8718. return;
  8719. }
  8720. const countMaxBattle = getInput('countAutoBattle');
  8721. if (findCoeff) {
  8722. const coeff = calcCoeff(e, 'defenders');
  8723. setProgress(`${countBattle}/${countMaxBattle}, ${coeff}`);
  8724. if (coeff > findCoeff) {
  8725. endBattle(e, false);
  8726. return;
  8727. }
  8728. } else {
  8729. if (nameFuncStartBattle == 'invasion_bossStart') {
  8730. const bossLvl = lastBattleInfo.typeId >= 130 ? lastBattleInfo.typeId : '';
  8731. const justice = lastBattleInfo?.effects?.attackers?.percentInOutDamageMod_any_99_100_300_99_1000 || 0;
  8732. setProgress(`${svgBoss} ${bossLvl} ${svgJustice} ${justice} <br>${svgAttempt} ${countBattle}/${countMaxBattle}`);
  8733. } else {
  8734. setProgress(`${countBattle}/${countMaxBattle}`);
  8735. }
  8736. }
  8737. if (nameFuncStartBattle == 'towerStartBattle' ||
  8738. nameFuncStartBattle == 'bossAttack' ||
  8739. nameFuncStartBattle == 'invasion_bossStart') {
  8740. startBattle();
  8741. return;
  8742. }
  8743. cancelEndBattle(e);
  8744. }
  8745. /**
  8746. * Cancel fight
  8747. *
  8748. * Отмена боя
  8749. */
  8750. function cancelEndBattle(r) {
  8751. const fixBattle = function (heroes) {
  8752. for (const ids in heroes) {
  8753. hero = heroes[ids];
  8754. hero.energy = random(1, 999);
  8755. if (hero.hp > 0) {
  8756. hero.hp = random(1, hero.hp);
  8757. }
  8758. }
  8759. }
  8760. fixBattle(r.progress[0].attackers.heroes);
  8761. fixBattle(r.progress[0].defenders.heroes);
  8762. endBattle(r, true);
  8763. }
  8764. /**
  8765. * End of the fight
  8766. *
  8767. * Завершение боя */
  8768. function endBattle(battleResult, isCancal) {
  8769. let calls = [{
  8770. name: nameFuncEndBattle,
  8771. args: {
  8772. result: battleResult.result,
  8773. progress: battleResult.progress
  8774. },
  8775. ident: "body"
  8776. }];
  8777.  
  8778. if (nameFuncStartBattle == 'invasion_bossStart') {
  8779. calls[0].args.id = lastBattleArg.id;
  8780. }
  8781.  
  8782. send(JSON.stringify({
  8783. calls
  8784. }), async e => {
  8785. console.log(e);
  8786. if (isCancal) {
  8787. startBattle();
  8788. return;
  8789. }
  8790.  
  8791. setProgress(`${I18N('SUCCESS')}!`, 5000)
  8792. if (nameFuncStartBattle == 'invasion_bossStart' ||
  8793. nameFuncStartBattle == 'bossAttack') {
  8794. const countMaxBattle = getInput('countAutoBattle');
  8795. const bossLvl = lastBattleInfo.typeId >= 130 ? lastBattleInfo.typeId : '';
  8796. const justice = lastBattleInfo?.effects?.attackers?.percentInOutDamageMod_any_99_100_300_99_1000 || 0;
  8797. const result = await popup.confirm(
  8798. I18N('BOSS_HAS_BEEN_DEF_TEXT', {
  8799. bossLvl: `${svgBoss} ${bossLvl} ${svgJustice} ${justice}`,
  8800. countBattle: svgAttempt + ' ' + countBattle,
  8801. countMaxBattle,
  8802. }),
  8803. [
  8804. { msg: I18N('BTN_OK'), result: 0 },
  8805. { msg: I18N('MAKE_A_SYNC'), result: 1 },
  8806. { msg: I18N('RELOAD_GAME'), result: 2 },
  8807. ]
  8808. );
  8809. if (result) {
  8810. if (result == 1) {
  8811. cheats.refreshGame();
  8812. }
  8813. if (result == 2) {
  8814. location.reload();
  8815. }
  8816. }
  8817.  
  8818. }
  8819. endAutoBattle(`${I18N('SUCCESS')}!`)
  8820. });
  8821. }
  8822. /**
  8823. * Completing a task
  8824. *
  8825. * Завершение задачи
  8826. */
  8827. function endAutoBattle(reason, info) {
  8828. isCancalBattle = true;
  8829. console.log(reason, info);
  8830. resolve();
  8831. }
  8832. }
  8833.  
  8834. function testDailyQuests() {
  8835. return new Promise((resolve, reject) => {
  8836. const quests = new dailyQuests(resolve, reject);
  8837. quests.init(questsInfo);
  8838. quests.start();
  8839. });
  8840. }
  8841.  
  8842. /**
  8843. * Automatic completion of daily quests
  8844. *
  8845. * Автоматическое выполнение ежедневных квестов
  8846. */
  8847. class dailyQuests {
  8848. /**
  8849. * Send(' {"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}').then(e => console.log(e))
  8850. * Send(' {"calls":[{"name":"heroGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  8851. * Send(' {"calls":[{"name":"titanGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  8852. * Send(' {"calls":[{"name":"inventoryGet","args":{},"ident":"body"}]}').then(e => console.log(e))
  8853. * Send(' {"calls":[{"name":"questGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  8854. * Send(' {"calls":[{"name":"bossGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  8855. */
  8856. callsList = [
  8857. "userGetInfo",
  8858. "heroGetAll",
  8859. "titanGetAll",
  8860. "inventoryGet",
  8861. "questGetAll",
  8862. "bossGetAll",
  8863. ]
  8864.  
  8865. dataQuests = {
  8866. 10001: {
  8867. description: 'Улучши умения героев 3 раза', // ++++++++++++++++
  8868. doItCall: () => {
  8869. const upgradeSkills = this.getUpgradeSkills();
  8870. return upgradeSkills.map(({ heroId, skill }, index) => ({ name: "heroUpgradeSkill", args: { heroId, skill }, "ident": `heroUpgradeSkill_${index}` }));
  8871. },
  8872. isWeCanDo: () => {
  8873. const upgradeSkills = this.getUpgradeSkills();
  8874. let sumGold = 0;
  8875. for (const skill of upgradeSkills) {
  8876. sumGold += this.skillCost(skill.value);
  8877. if (!skill.heroId) {
  8878. return false;
  8879. }
  8880. }
  8881. return this.questInfo['userGetInfo'].gold > sumGold;
  8882. },
  8883. },
  8884. 10002: {
  8885. description: 'Пройди 10 миссий', // --------------
  8886. isWeCanDo: () => false,
  8887. },
  8888. 10003: {
  8889. description: 'Пройди 3 героические миссии', // --------------
  8890. isWeCanDo: () => false,
  8891. },
  8892. 10004: {
  8893. description: 'Сразись 3 раза на Арене или Гранд Арене', // --------------
  8894. isWeCanDo: () => false,
  8895. },
  8896. 10006: {
  8897. description: 'Используй обмен изумрудов 1 раз', // ++++++++++++++++
  8898. doItCall: () => [{
  8899. name: "refillableAlchemyUse",
  8900. args: { multi: false },
  8901. ident: "refillableAlchemyUse"
  8902. }],
  8903. isWeCanDo: () => {
  8904. const starMoney = this.questInfo['userGetInfo'].starMoney;
  8905. return starMoney >= 20;
  8906. },
  8907. },
  8908. 10007: {
  8909. description: 'Соверши 1 призыв в Атриуме Душ', // ++++++++++++++++
  8910. doItCall: () => [{ name: "gacha_open", args: { ident: "heroGacha", free: true, pack: false }, ident: "gacha_open" }],
  8911. isWeCanDo: () => {
  8912. const soulCrystal = this.questInfo['inventoryGet'].coin[38];
  8913. return soulCrystal > 0;
  8914. },
  8915. },
  8916. 10016: {
  8917. description: 'Отправь подарки согильдийцам', // ++++++++++++++++
  8918. doItCall: () => [{ name: "clanSendDailyGifts", args: {}, ident: "clanSendDailyGifts" }],
  8919. isWeCanDo: () => true,
  8920. },
  8921. 10018: {
  8922. description: 'Используй зелье опыта', // ++++++++++++++++
  8923. doItCall: () => {
  8924. const expHero = this.getExpHero();
  8925. return [{
  8926. name: "consumableUseHeroXp",
  8927. args: {
  8928. heroId: expHero.heroId,
  8929. libId: expHero.libId,
  8930. amount: 1
  8931. },
  8932. ident: "consumableUseHeroXp"
  8933. }];
  8934. },
  8935. isWeCanDo: () => {
  8936. const expHero = this.getExpHero();
  8937. return expHero.heroId && expHero.libId;
  8938. },
  8939. },
  8940. 10019: {
  8941. description: 'Открой 1 сундук в Башне',
  8942. doItFunc: testTower,
  8943. isWeCanDo: () => false,
  8944. },
  8945. 10020: {
  8946. description: 'Открой 3 сундука в Запределье', // Готово
  8947. doItCall: () => {
  8948. return this.getOutlandChest();
  8949. },
  8950. isWeCanDo: () => {
  8951. const outlandChest = this.getOutlandChest();
  8952. return outlandChest.length > 0;
  8953. },
  8954. },
  8955. 10021: {
  8956. description: 'Собери 75 Титанита в Подземелье Гильдии',
  8957. isWeCanDo: () => false,
  8958. },
  8959. 10022: {
  8960. description: 'Собери 150 Титанита в Подземелье Гильдии',
  8961. doItFunc: testDungeon,
  8962. isWeCanDo: () => false,
  8963. },
  8964. 10023: {
  8965. description: 'Прокачай Дар Стихий на 1 уровень', // Готово
  8966. doItCall: () => {
  8967. const heroId = this.getHeroIdTitanGift();
  8968. return [
  8969. { name: "heroTitanGiftLevelUp", args: { heroId }, ident: "heroTitanGiftLevelUp" },
  8970. { name: "heroTitanGiftDrop", args: { heroId }, ident: "heroTitanGiftDrop" }
  8971. ]
  8972. },
  8973. isWeCanDo: () => {
  8974. const heroId = this.getHeroIdTitanGift();
  8975. return heroId;
  8976. },
  8977. },
  8978. 10024: {
  8979. description: 'Повысь уровень любого артефакта один раз', // Готово
  8980. doItCall: () => {
  8981. const upArtifact = this.getUpgradeArtifact();
  8982. return [
  8983. {
  8984. name: "heroArtifactLevelUp",
  8985. args: {
  8986. heroId: upArtifact.heroId,
  8987. slotId: upArtifact.slotId
  8988. },
  8989. ident: `heroArtifactLevelUp`
  8990. }
  8991. ];
  8992. },
  8993. isWeCanDo: () => {
  8994. const upgradeArtifact = this.getUpgradeArtifact();
  8995. return upgradeArtifact.heroId;
  8996. },
  8997. },
  8998. 10025: {
  8999. description: 'Начни 1 Экспедицию',
  9000. doItFunc: checkExpedition,
  9001. isWeCanDo: () => false,
  9002. },
  9003. 10026: {
  9004. description: 'Начни 4 Экспедиции', // --------------
  9005. doItFunc: checkExpedition,
  9006. isWeCanDo: () => false,
  9007. },
  9008. 10027: {
  9009. description: 'Победи в 1 бою Турнира Стихий',
  9010. doItFunc: testTitanArena,
  9011. isWeCanDo: () => false,
  9012. },
  9013. 10028: {
  9014. description: 'Повысь уровень любого артефакта титанов', // Готово
  9015. doItCall: () => {
  9016. const upTitanArtifact = this.getUpgradeTitanArtifact();
  9017. return [
  9018. {
  9019. name: "titanArtifactLevelUp",
  9020. args: {
  9021. titanId: upTitanArtifact.titanId,
  9022. slotId: upTitanArtifact.slotId
  9023. },
  9024. ident: `titanArtifactLevelUp`
  9025. }
  9026. ];
  9027. },
  9028. isWeCanDo: () => {
  9029. const upgradeTitanArtifact = this.getUpgradeTitanArtifact();
  9030. return upgradeTitanArtifact.titanId;
  9031. },
  9032. },
  9033. 10029: {
  9034. description: 'Открой сферу артефактов титанов', // ++++++++++++++++
  9035. doItCall: () => [{ name: "titanArtifactChestOpen", args: { amount: 1, free: true }, ident: "titanArtifactChestOpen" }],
  9036. isWeCanDo: () => {
  9037. return this.questInfo['inventoryGet']?.consumable[55] > 0
  9038. },
  9039. },
  9040. 10030: {
  9041. description: 'Улучши облик любого героя 1 раз', // Готово
  9042. doItCall: () => {
  9043. const upSkin = this.getUpgradeSkin();
  9044. return [
  9045. {
  9046. name: "heroSkinUpgrade",
  9047. args: {
  9048. heroId: upSkin.heroId,
  9049. skinId: upSkin.skinId
  9050. },
  9051. ident: `heroSkinUpgrade`
  9052. }
  9053. ];
  9054. },
  9055. isWeCanDo: () => {
  9056. const upgradeSkin = this.getUpgradeSkin();
  9057. return upgradeSkin.heroId;
  9058. },
  9059. },
  9060. 10031: {
  9061. description: 'Победи в 6 боях Турнира Стихий', // --------------
  9062. doItFunc: testTitanArena,
  9063. isWeCanDo: () => false,
  9064. },
  9065. 10043: {
  9066. description: 'Начни или присоеденись к Приключению', // --------------
  9067. isWeCanDo: () => false,
  9068. },
  9069. 10044: {
  9070. description: 'Воспользуйся призывом питомцев 1 раз', // ++++++++++++++++
  9071. doItCall: () => [{ name: "pet_chestOpen", args: { amount: 1, paid: false }, ident: "pet_chestOpen" }],
  9072. isWeCanDo: () => {
  9073. return this.questInfo['inventoryGet']?.consumable[90] > 0
  9074. },
  9075. },
  9076. 10046: {
  9077. /**
  9078. * TODO: Watch Adventure
  9079. * TODO: Смотреть приключение
  9080. */
  9081. description: 'Открой 3 сундука в Приключениях',
  9082. isWeCanDo: () => false,
  9083. },
  9084. 10047: {
  9085. description: 'Набери 150 очков активности в Гильдии', // Готово
  9086. doItCall: () => {
  9087. const enchantRune = this.getEnchantRune();
  9088. return [
  9089. {
  9090. name: "heroEnchantRune",
  9091. args: {
  9092. heroId: enchantRune.heroId,
  9093. tier: enchantRune.tier,
  9094. items: {
  9095. consumable: { [enchantRune.itemId]: 1 }
  9096. }
  9097. },
  9098. ident: `heroEnchantRune`
  9099. }
  9100. ];
  9101. },
  9102. isWeCanDo: () => {
  9103. const userInfo = this.questInfo['userGetInfo'];
  9104. const enchantRune = this.getEnchantRune();
  9105. return enchantRune.heroId && userInfo.gold > 1e3;
  9106. },
  9107. },
  9108. };
  9109.  
  9110. constructor(resolve, reject, questInfo) {
  9111. this.resolve = resolve;
  9112. this.reject = reject;
  9113. }
  9114.  
  9115. init(questInfo) {
  9116. this.questInfo = questInfo;
  9117. this.isAuto = false;
  9118. }
  9119.  
  9120. async autoInit(isAuto) {
  9121. this.isAuto = isAuto || false;
  9122. const quests = {};
  9123. const calls = this.callsList.map(name => ({
  9124. name, args: {}, ident: name
  9125. }))
  9126. const result = await Send(JSON.stringify({ calls })).then(e => e.results);
  9127. for (const call of result) {
  9128. quests[call.ident] = call.result.response;
  9129. }
  9130. this.questInfo = quests;
  9131. }
  9132.  
  9133. async start() {
  9134. const weCanDo = [];
  9135. const selectedActions = getSaveVal('selectedActions', {});
  9136. for (let quest of this.questInfo['questGetAll']) {
  9137. if (quest.id in this.dataQuests && quest.state == 1) {
  9138. if (!selectedActions[quest.id]) {
  9139. selectedActions[quest.id] = {
  9140. checked: false
  9141. }
  9142. }
  9143.  
  9144. const isWeCanDo = this.dataQuests[quest.id].isWeCanDo;
  9145. if (!isWeCanDo.call(this)) {
  9146. continue;
  9147. }
  9148.  
  9149. weCanDo.push({
  9150. name: quest.id,
  9151. label: I18N(`QUEST_${quest.id}`),
  9152. checked: selectedActions[quest.id].checked
  9153. });
  9154. }
  9155. }
  9156.  
  9157. if (!weCanDo.length) {
  9158. this.end(I18N('NOTHING_TO_DO'));
  9159. return;
  9160. }
  9161.  
  9162. console.log(weCanDo);
  9163. let taskList = [];
  9164. if (this.isAuto) {
  9165. taskList = weCanDo;
  9166. } else {
  9167. const answer = await popup.confirm(`${I18N('YOU_CAN_COMPLETE') }:`, [
  9168. { msg: I18N('BTN_DO_IT'), result: true },
  9169. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  9170. ], weCanDo);
  9171. if (!answer) {
  9172. this.end('');
  9173. return;
  9174. }
  9175. taskList = popup.getCheckBoxes();
  9176. taskList.forEach(e => {
  9177. selectedActions[e.name].checked = e.checked;
  9178. });
  9179. setSaveVal('selectedActions', selectedActions);
  9180. }
  9181.  
  9182. const calls = [];
  9183. let countChecked = 0;
  9184. for (const task of taskList) {
  9185. if (task.checked) {
  9186. countChecked++;
  9187. const quest = this.dataQuests[task.name]
  9188. console.log(quest.description);
  9189.  
  9190. if (quest.doItCall) {
  9191. const doItCall = quest.doItCall.call(this);
  9192. calls.push(...doItCall);
  9193. }
  9194. }
  9195. }
  9196.  
  9197. if (!countChecked) {
  9198. this.end(I18N('NOT_QUEST_COMPLETED'));
  9199. return;
  9200. }
  9201.  
  9202. const result = await Send(JSON.stringify({ calls }));
  9203. if (result.error) {
  9204. console.error(result.error, result.error.call)
  9205. }
  9206. this.end(`${I18N('COMPLETED_QUESTS')}: ${countChecked}`);
  9207. }
  9208.  
  9209. errorHandling(error) {
  9210. //console.error(error);
  9211. let errorInfo = error.toString() + '\n';
  9212. try {
  9213. const errorStack = error.stack.split('\n');
  9214. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testDoYourBest");
  9215. errorInfo += errorStack.slice(0, endStack).join('\n');
  9216. } catch (e) {
  9217. errorInfo += error.stack;
  9218. }
  9219. copyText(errorInfo);
  9220. }
  9221.  
  9222. skillCost(lvl) {
  9223. return 573 * lvl ** 0.9 + lvl ** 2.379;
  9224. }
  9225.  
  9226. getUpgradeSkills() {
  9227. const heroes = Object.values(this.questInfo['heroGetAll']);
  9228. const upgradeSkills = [
  9229. { heroId: 0, slotId: 0, value: 130 },
  9230. { heroId: 0, slotId: 0, value: 130 },
  9231. { heroId: 0, slotId: 0, value: 130 },
  9232. ];
  9233. const skillLib = lib.getData('skill');
  9234. /**
  9235. * color - 1 (белый) открывает 1 навык
  9236. * color - 2 (зеленый) открывает 2 навык
  9237. * color - 4 (синий) открывает 3 навык
  9238. * color - 7 (фиолетовый) открывает 4 навык
  9239. */
  9240. const colors = [1, 2, 4, 7];
  9241. for (const hero of heroes) {
  9242. const level = hero.level;
  9243. const color = hero.color;
  9244. for (let skillId in hero.skills) {
  9245. const tier = skillLib[skillId].tier;
  9246. const sVal = hero.skills[skillId];
  9247. if (color < colors[tier] || tier < 1 || tier > 4) {
  9248. continue;
  9249. }
  9250. for (let upSkill of upgradeSkills) {
  9251. if (sVal < upSkill.value && sVal < level) {
  9252. upSkill.value = sVal;
  9253. upSkill.heroId = hero.id;
  9254. upSkill.skill = tier;
  9255. break;
  9256. }
  9257. }
  9258. }
  9259. }
  9260. return upgradeSkills;
  9261. }
  9262.  
  9263. getUpgradeArtifact() {
  9264. const heroes = Object.values(this.questInfo['heroGetAll']);
  9265. const inventory = this.questInfo['inventoryGet'];
  9266. const upArt = { heroId: 0, slotId: 0, level: 100 };
  9267.  
  9268. const heroLib = lib.getData('hero');
  9269. const artifactLib = lib.getData('artifact');
  9270.  
  9271. for (const hero of heroes) {
  9272. const heroInfo = heroLib[hero.id];
  9273. const level = hero.level
  9274. if (level < 20) {
  9275. continue;
  9276. }
  9277.  
  9278. for (let slotId in hero.artifacts) {
  9279. const art = hero.artifacts[slotId];
  9280. /* Текущая звезданость арта */
  9281. const star = art.star;
  9282. if (!star) {
  9283. continue;
  9284. }
  9285. /* Текущий уровень арта */
  9286. const level = art.level;
  9287. if (level >= 100) {
  9288. continue;
  9289. }
  9290. /* Идентификатор арта в библиотеке */
  9291. const artifactId = heroInfo.artifacts[slotId];
  9292. const artInfo = artifactLib.id[artifactId];
  9293. const costNextLevel = artifactLib.type[artInfo.type].levels[level + 1].cost;
  9294.  
  9295. const costСurrency = Object.keys(costNextLevel).pop();
  9296. const costValues = Object.entries(costNextLevel[costСurrency]).pop();
  9297. const costId = costValues[0];
  9298. const costValue = +costValues[1];
  9299.  
  9300. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  9301. if (level < upArt.level && inventory[costСurrency][costId] >= costValue) {
  9302. upArt.level = level;
  9303. upArt.heroId = hero.id;
  9304. upArt.slotId = slotId;
  9305. upArt.costСurrency = costСurrency;
  9306. upArt.costId = costId;
  9307. upArt.costValue = costValue;
  9308. }
  9309. }
  9310. }
  9311. return upArt;
  9312. }
  9313.  
  9314. getUpgradeSkin() {
  9315. const heroes = Object.values(this.questInfo['heroGetAll']);
  9316. const inventory = this.questInfo['inventoryGet'];
  9317. const upSkin = { heroId: 0, skinId: 0, level: 60, cost: 1500 };
  9318.  
  9319. const skinLib = lib.getData('skin');
  9320.  
  9321. for (const hero of heroes) {
  9322. const level = hero.level
  9323. if (level < 20) {
  9324. continue;
  9325. }
  9326.  
  9327. for (let skinId in hero.skins) {
  9328. /* Текущий уровень скина */
  9329. const level = hero.skins[skinId];
  9330. if (level >= 60) {
  9331. continue;
  9332. }
  9333. /* Идентификатор скина в библиотеке */
  9334. const skinInfo = skinLib[skinId];
  9335. if (!skinInfo.statData.levels?.[level + 1]) {
  9336. continue;
  9337. }
  9338. const costNextLevel = skinInfo.statData.levels[level + 1].cost;
  9339.  
  9340. const costСurrency = Object.keys(costNextLevel).pop();
  9341. const costСurrencyId = Object.keys(costNextLevel[costСurrency]).pop();
  9342. const costValue = +costNextLevel[costСurrency][costСurrencyId];
  9343.  
  9344. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  9345. if (level < upSkin.level &&
  9346. costValue < upSkin.cost &&
  9347. inventory[costСurrency][costСurrencyId] >= costValue) {
  9348. upSkin.cost = costValue;
  9349. upSkin.level = level;
  9350. upSkin.heroId = hero.id;
  9351. upSkin.skinId = skinId;
  9352. upSkin.costСurrency = costСurrency;
  9353. upSkin.costСurrencyId = costСurrencyId;
  9354. }
  9355. }
  9356. }
  9357. return upSkin;
  9358. }
  9359.  
  9360. getUpgradeTitanArtifact() {
  9361. const titans = Object.values(this.questInfo['titanGetAll']);
  9362. const inventory = this.questInfo['inventoryGet'];
  9363. const userInfo = this.questInfo['userGetInfo'];
  9364. const upArt = { titanId: 0, slotId: 0, level: 120 };
  9365.  
  9366. const titanLib = lib.getData('titan');
  9367. const artTitanLib = lib.getData('titanArtifact');
  9368.  
  9369. for (const titan of titans) {
  9370. const titanInfo = titanLib[titan.id];
  9371. // const level = titan.level
  9372. // if (level < 20) {
  9373. // continue;
  9374. // }
  9375.  
  9376. for (let slotId in titan.artifacts) {
  9377. const art = titan.artifacts[slotId];
  9378. /* Текущая звезданость арта */
  9379. const star = art.star;
  9380. if (!star) {
  9381. continue;
  9382. }
  9383. /* Текущий уровень арта */
  9384. const level = art.level;
  9385. if (level >= 120) {
  9386. continue;
  9387. }
  9388. /* Идентификатор арта в библиотеке */
  9389. const artifactId = titanInfo.artifacts[slotId];
  9390. const artInfo = artTitanLib.id[artifactId];
  9391. const costNextLevel = artTitanLib.type[artInfo.type].levels[level + 1].cost;
  9392.  
  9393. const costСurrency = Object.keys(costNextLevel).pop();
  9394. let costValue = 0;
  9395. let currentValue = 0;
  9396. if (costСurrency == 'gold') {
  9397. costValue = costNextLevel[costСurrency];
  9398. currentValue = userInfo.gold;
  9399. } else {
  9400. const costValues = Object.entries(costNextLevel[costСurrency]).pop();
  9401. const costId = costValues[0];
  9402. costValue = +costValues[1];
  9403. currentValue = inventory[costСurrency][costId];
  9404. }
  9405.  
  9406. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  9407. if (level < upArt.level && currentValue >= costValue) {
  9408. upArt.level = level;
  9409. upArt.titanId = titan.id;
  9410. upArt.slotId = slotId;
  9411. break;
  9412. }
  9413. }
  9414. }
  9415. return upArt;
  9416. }
  9417.  
  9418. getEnchantRune() {
  9419. const heroes = Object.values(this.questInfo['heroGetAll']);
  9420. const inventory = this.questInfo['inventoryGet'];
  9421. const enchRune = { heroId: 0, tier: 0, exp: 43750, itemId: 0 };
  9422. for (let i = 1; i <= 4; i++) {
  9423. if (inventory.consumable[i] > 0) {
  9424. enchRune.itemId = i;
  9425. break;
  9426. }
  9427. return enchRune;
  9428. }
  9429.  
  9430. const runeLib = lib.getData('rune');
  9431. const runeLvls = Object.values(runeLib.level);
  9432. /**
  9433. * color - 4 (синий) открывает 1 и 2 символ
  9434. * color - 7 (фиолетовый) открывает 3 символ
  9435. * color - 8 (фиолетовый +1) открывает 4 символ
  9436. * color - 9 (фиолетовый +2) открывает 5 символ
  9437. */
  9438. // TODO: кажется надо учесть уровень команды
  9439. const colors = [4, 4, 7, 8, 9];
  9440. for (const hero of heroes) {
  9441. const color = hero.color;
  9442.  
  9443.  
  9444. for (let runeTier in hero.runes) {
  9445. /* Проверка на доступность руны */
  9446. if (color < colors[runeTier]) {
  9447. continue;
  9448. }
  9449. /* Текущий опыт руны */
  9450. const exp = hero.runes[runeTier];
  9451. if (exp >= 43750) {
  9452. continue;
  9453. }
  9454.  
  9455. let level = 0;
  9456. if (exp) {
  9457. for (let lvl of runeLvls) {
  9458. if (exp >= lvl.enchantValue) {
  9459. level = lvl.level;
  9460. } else {
  9461. break;
  9462. }
  9463. }
  9464. }
  9465. /** Уровень героя необходимый для уровня руны */
  9466. const heroLevel = runeLib.level[level].heroLevel;
  9467. if (hero.level < heroLevel) {
  9468. continue;
  9469. }
  9470.  
  9471. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  9472. if (exp < enchRune.exp) {
  9473. enchRune.exp = exp;
  9474. enchRune.heroId = hero.id;
  9475. enchRune.tier = runeTier;
  9476. break;
  9477. }
  9478. }
  9479. }
  9480. return enchRune;
  9481. }
  9482.  
  9483. getOutlandChest() {
  9484. const bosses = this.questInfo['bossGetAll'];
  9485.  
  9486. const calls = [];
  9487.  
  9488. for (let boss of bosses) {
  9489. if (boss.mayRaid) {
  9490. calls.push({
  9491. name: "bossRaid",
  9492. args: {
  9493. bossId: boss.id
  9494. },
  9495. ident: "bossRaid_" + boss.id
  9496. });
  9497. calls.push({
  9498. name: "bossOpenChest",
  9499. args: {
  9500. bossId: boss.id,
  9501. amount: 1,
  9502. starmoney: 0
  9503. },
  9504. ident: "bossOpenChest_" + boss.id
  9505. });
  9506. } else if (boss.chestId == 1) {
  9507. calls.push({
  9508. name: "bossOpenChest",
  9509. args: {
  9510. bossId: boss.id,
  9511. amount: 1,
  9512. starmoney: 0
  9513. },
  9514. ident: "bossOpenChest_" + boss.id
  9515. });
  9516. }
  9517. }
  9518.  
  9519. return calls;
  9520. }
  9521.  
  9522. getExpHero() {
  9523. const heroes = Object.values(this.questInfo['heroGetAll']);
  9524. const inventory = this.questInfo['inventoryGet'];
  9525. const expHero = { heroId: 0, exp: 3625195, libId: 0 };
  9526. /** зелья опыта (consumable 9, 10, 11, 12) */
  9527. for (let i = 9; i <= 12; i++) {
  9528. if (inventory.consumable[i]) {
  9529. expHero.libId = i;
  9530. break;
  9531. }
  9532. }
  9533.  
  9534. for (const hero of heroes) {
  9535. const exp = hero.xp;
  9536. if (exp < expHero.exp) {
  9537. expHero.heroId = hero.id;
  9538. }
  9539. }
  9540. return expHero;
  9541. }
  9542.  
  9543. getHeroIdTitanGift() {
  9544. const heroes = Object.values(this.questInfo['heroGetAll']);
  9545. const inventory = this.questInfo['inventoryGet'];
  9546. const user = this.questInfo['userGetInfo'];
  9547. const titanGiftLib = lib.getData('titanGift');
  9548. /** Искры */
  9549. const titanGift = inventory.consumable[24];
  9550. let heroId = 0;
  9551. let minLevel = 30;
  9552.  
  9553. if (titanGift < 250 || user.gold < 7000) {
  9554. return 0;
  9555. }
  9556.  
  9557. for (const hero of heroes) {
  9558. if (hero.titanGiftLevel >= 30) {
  9559. continue;
  9560. }
  9561.  
  9562. if (!hero.titanGiftLevel) {
  9563. return hero.id;
  9564. }
  9565.  
  9566. const cost = titanGiftLib[hero.titanGiftLevel].cost;
  9567. if (minLevel > hero.titanGiftLevel &&
  9568. titanGift >= cost.consumable[24] &&
  9569. user.gold >= cost.gold
  9570. ) {
  9571. minLevel = hero.titanGiftLevel;
  9572. heroId = hero.id;
  9573. }
  9574. }
  9575.  
  9576. return heroId;
  9577. }
  9578.  
  9579. end(status) {
  9580. setProgress(status, true);
  9581. this.resolve();
  9582. }
  9583. }
  9584.  
  9585. this.questRun = dailyQuests;
  9586.  
  9587. function testDoYourBest() {
  9588. return new Promise((resolve, reject) => {
  9589. const doIt = new doYourBest(resolve, reject);
  9590. doIt.start();
  9591. });
  9592. }
  9593.  
  9594. /**
  9595. * Do everything button
  9596. *
  9597. * Кнопка сделать все
  9598. */
  9599. class doYourBest {
  9600.  
  9601. funcList = [
  9602. {
  9603. name: 'getOutland',
  9604. label: I18N('ASSEMBLE_OUTLAND'),
  9605. checked: false
  9606. },
  9607. {
  9608. name: 'testTower',
  9609. label: I18N('PASS_THE_TOWER'),
  9610. checked: false
  9611. },
  9612. {
  9613. name: 'checkExpedition',
  9614. label: I18N('CHECK_EXPEDITIONS'),
  9615. checked: false
  9616. },
  9617. {
  9618. name: 'testTitanArena',
  9619. label: I18N('COMPLETE_TOE'),
  9620. checked: false
  9621. },
  9622. {
  9623. name: 'mailGetAll',
  9624. label: I18N('COLLECT_MAIL'),
  9625. checked: false
  9626. },
  9627. {
  9628. name: 'collectAllStuff',
  9629. label: I18N('COLLECT_MISC'),
  9630. title: I18N('COLLECT_MISC_TITLE'),
  9631. checked: false
  9632. },
  9633. {
  9634. name: 'getDailyBonus',
  9635. label: I18N('DAILY_BONUS'),
  9636. checked: false
  9637. },
  9638. {
  9639. name: 'dailyQuests',
  9640. label: I18N('DO_DAILY_QUESTS'),
  9641. checked: false
  9642. },
  9643. {
  9644. name: 'rollAscension',
  9645. label: I18N('SEER_TITLE'),
  9646. checked: false
  9647. },
  9648. {
  9649. name: 'questAllFarm',
  9650. label: I18N('COLLECT_QUEST_REWARDS'),
  9651. checked: false
  9652. },
  9653. {
  9654. name: 'testDungeon',
  9655. label: I18N('COMPLETE_DUNGEON'),
  9656. checked: false
  9657. },
  9658. {
  9659. name: 'synchronization',
  9660. label: I18N('MAKE_A_SYNC'),
  9661. checked: false
  9662. },
  9663. {
  9664. name: 'reloadGame',
  9665. label: I18N('RELOAD_GAME'),
  9666. checked: false
  9667. },
  9668. ];
  9669.  
  9670. functions = {
  9671. getOutland,
  9672. testTower,
  9673. checkExpedition,
  9674. testTitanArena,
  9675. mailGetAll,
  9676. collectAllStuff: async () => {
  9677. await offerFarmAllReward();
  9678. 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"}]}');
  9679. },
  9680. dailyQuests: async function () {
  9681. const quests = new dailyQuests(() => { }, () => { });
  9682. await quests.autoInit(true);
  9683. await quests.start();
  9684. },
  9685. rollAscension,
  9686. getDailyBonus,
  9687. questAllFarm,
  9688. testDungeon,
  9689. synchronization: async () => {
  9690. cheats.refreshGame();
  9691. },
  9692. reloadGame: async () => {
  9693. location.reload();
  9694. },
  9695. }
  9696.  
  9697. constructor(resolve, reject, questInfo) {
  9698. this.resolve = resolve;
  9699. this.reject = reject;
  9700. this.questInfo = questInfo
  9701. }
  9702.  
  9703. async start() {
  9704. const selectedDoIt = getSaveVal('selectedDoIt', {});
  9705.  
  9706. this.funcList.forEach(task => {
  9707. if (!selectedDoIt[task.name]) {
  9708. selectedDoIt[task.name] = {
  9709. checked: task.checked
  9710. }
  9711. } else {
  9712. task.checked = selectedDoIt[task.name].checked
  9713. }
  9714. });
  9715.  
  9716. const answer = await popup.confirm(I18N('RUN_FUNCTION'), [
  9717. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  9718. { msg: I18N('BTN_GO'), result: true },
  9719. ], this.funcList);
  9720.  
  9721. if (!answer) {
  9722. this.end('');
  9723. return;
  9724. }
  9725.  
  9726. const taskList = popup.getCheckBoxes();
  9727. taskList.forEach(task => {
  9728. selectedDoIt[task.name].checked = task.checked;
  9729. });
  9730. setSaveVal('selectedDoIt', selectedDoIt);
  9731. for (const task of popup.getCheckBoxes()) {
  9732. if (task.checked) {
  9733. try {
  9734. setProgress(`${task.label} <br>${I18N('PERFORMED')}!`);
  9735. await this.functions[task.name]();
  9736. setProgress(`${task.label} <br>${I18N('DONE')}!`);
  9737. } catch (error) {
  9738. if (await popup.confirm(`${I18N('ERRORS_OCCURRES')}:<br> ${task.label} <br>${I18N('COPY_ERROR')}?`, [
  9739. { msg: I18N('BTN_NO'), result: false },
  9740. { msg: I18N('BTN_YES'), result: true },
  9741. ])) {
  9742. this.errorHandling(error);
  9743. }
  9744. }
  9745. }
  9746. }
  9747. setTimeout((msg) => {
  9748. this.end(msg);
  9749. }, 2000, I18N('ALL_TASK_COMPLETED'));
  9750. return;
  9751. }
  9752.  
  9753. errorHandling(error) {
  9754. //console.error(error);
  9755. let errorInfo = error.toString() + '\n';
  9756. try {
  9757. const errorStack = error.stack.split('\n');
  9758. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testDoYourBest");
  9759. errorInfo += errorStack.slice(0, endStack).join('\n');
  9760. } catch (e) {
  9761. errorInfo += error.stack;
  9762. }
  9763. copyText(errorInfo);
  9764. }
  9765.  
  9766. end(status) {
  9767. setProgress(status, true);
  9768. this.resolve();
  9769. }
  9770. }
  9771.  
  9772. /**
  9773. * Passing the adventure along the specified route
  9774. *
  9775. * Прохождение приключения по указанному маршруту
  9776. */
  9777. function testAdventure(type) {
  9778. return new Promise((resolve, reject) => {
  9779. const bossBattle = new executeAdventure(resolve, reject);
  9780. bossBattle.start(type);
  9781. });
  9782. }
  9783.  
  9784. /**
  9785. * Passing the adventure along the specified route
  9786. *
  9787. * Прохождение приключения по указанному маршруту
  9788. */
  9789. class executeAdventure {
  9790.  
  9791. type = 'default';
  9792.  
  9793. actions = {
  9794. default: {
  9795. getInfo: "adventure_getInfo",
  9796. startBattle: 'adventure_turnStartBattle',
  9797. endBattle: 'adventure_endBattle',
  9798. collectBuff: 'adventure_turnCollectBuff'
  9799. },
  9800. solo: {
  9801. getInfo: "adventureSolo_getInfo",
  9802. startBattle: 'adventureSolo_turnStartBattle',
  9803. endBattle: 'adventureSolo_endBattle',
  9804. collectBuff: 'adventureSolo_turnCollectBuff'
  9805. }
  9806. }
  9807.  
  9808. terminatеReason = I18N('UNKNOWN');
  9809. callAdventureInfo = {
  9810. name: "adventure_getInfo",
  9811. args: {},
  9812. ident: "adventure_getInfo"
  9813. }
  9814. callTeamGetAll = {
  9815. name: "teamGetAll",
  9816. args: {},
  9817. ident: "teamGetAll"
  9818. }
  9819. callTeamGetFavor = {
  9820. name: "teamGetFavor",
  9821. args: {},
  9822. ident: "teamGetFavor"
  9823. }
  9824. callStartBattle = {
  9825. name: "adventure_turnStartBattle",
  9826. args: {},
  9827. ident: "body"
  9828. }
  9829. callEndBattle = {
  9830. name: "adventure_endBattle",
  9831. args: {
  9832. result: {},
  9833. progress: {},
  9834. },
  9835. ident: "body"
  9836. }
  9837. callCollectBuff = {
  9838. name: "adventure_turnCollectBuff",
  9839. args: {},
  9840. ident: "body"
  9841. }
  9842.  
  9843. constructor(resolve, reject) {
  9844. this.resolve = resolve;
  9845. this.reject = reject;
  9846. }
  9847.  
  9848. async start(type) {
  9849. this.type = type || this.type;
  9850. this.callAdventureInfo.name = this.actions[this.type].getInfo;
  9851. const data = await Send(JSON.stringify({
  9852. calls: [
  9853. this.callAdventureInfo,
  9854. this.callTeamGetAll,
  9855. this.callTeamGetFavor
  9856. ]
  9857. }));
  9858. return this.checkAdventureInfo(data.results);
  9859. }
  9860.  
  9861. async getPath() {
  9862. const oldVal = getSaveVal('adventurePath', '');
  9863. const keyPath = `adventurePath:${this.mapIdent}`;
  9864. const answer = await popup.confirm(I18N('ENTER_THE_PATH'), [
  9865. {
  9866. msg: I18N('START_ADVENTURE'),
  9867. placeholder: '1,2,3,4,5,6',
  9868. isInput: true,
  9869. default: getSaveVal(keyPath, oldVal)
  9870. },
  9871. {
  9872. msg: I18N('BTN_CANCEL'),
  9873. result: false,
  9874. isCancel: true
  9875. },
  9876. ]);
  9877. if (!answer) {
  9878. this.terminatеReason = I18N('BTN_CANCELED');
  9879. return false;
  9880. }
  9881.  
  9882. let path = answer.split(',');
  9883. if (path.length < 2) {
  9884. path = answer.split('-');
  9885. }
  9886. if (path.length < 2) {
  9887. this.terminatеReason = I18N('MUST_TWO_POINTS');
  9888. return false;
  9889. }
  9890.  
  9891. for (let p in path) {
  9892. path[p] = +path[p].trim()
  9893. if (Number.isNaN(path[p])) {
  9894. this.terminatеReason = I18N('MUST_ONLY_NUMBERS');
  9895. return false;
  9896. }
  9897. }
  9898.  
  9899. if (!this.checkPath(path)) {
  9900. return false;
  9901. }
  9902. setSaveVal(keyPath, answer);
  9903. return path;
  9904. }
  9905.  
  9906. checkPath(path) {
  9907. for (let i = 0; i < path.length - 1; i++) {
  9908. const currentPoint = path[i];
  9909. const nextPoint = path[i + 1];
  9910.  
  9911. const isValidPath = this.paths.some(p =>
  9912. (p.from_id === currentPoint && p.to_id === nextPoint) ||
  9913. (p.from_id === nextPoint && p.to_id === currentPoint)
  9914. );
  9915.  
  9916. if (!isValidPath) {
  9917. this.terminatеReason = I18N('INCORRECT_WAY', {
  9918. from: currentPoint,
  9919. to: nextPoint,
  9920. });
  9921. return false;
  9922. }
  9923. }
  9924.  
  9925. return true;
  9926. }
  9927.  
  9928. async checkAdventureInfo(data) {
  9929. this.advInfo = data[0].result.response;
  9930. if (!this.advInfo) {
  9931. this.terminatеReason = I18N('NOT_ON_AN_ADVENTURE') ;
  9932. return this.end();
  9933. }
  9934. const heroesTeam = data[1].result.response.adventure_hero;
  9935. const favor = data[2]?.result.response.adventure_hero;
  9936. const heroes = heroesTeam.slice(0, 5);
  9937. const pet = heroesTeam[5];
  9938. this.args = {
  9939. pet,
  9940. heroes,
  9941. favor,
  9942. path: [],
  9943. broadcast: false
  9944. }
  9945. const advUserInfo = this.advInfo.users[userInfo.id];
  9946. this.turnsLeft = advUserInfo.turnsLeft;
  9947. this.currentNode = advUserInfo.currentNode;
  9948. this.nodes = this.advInfo.nodes;
  9949. this.paths = this.advInfo.paths;
  9950. this.mapIdent = this.advInfo.mapIdent;
  9951.  
  9952. this.path = await this.getPath();
  9953. if (!this.path) {
  9954. return this.end();
  9955. }
  9956.  
  9957. if (this.currentNode == 1 && this.path[0] != 1) {
  9958. this.path.unshift(1);
  9959. }
  9960.  
  9961. return this.loop();
  9962. }
  9963.  
  9964. async loop() {
  9965. const position = this.path.indexOf(+this.currentNode);
  9966. if (!(~position)) {
  9967. this.terminatеReason = I18N('YOU_IN_NOT_ON_THE_WAY');
  9968. return this.end();
  9969. }
  9970. this.path = this.path.slice(position);
  9971. if ((this.path.length - 1) > this.turnsLeft &&
  9972. await popup.confirm(I18N('ATTEMPTS_NOT_ENOUGH'), [
  9973. { msg: I18N('YES_CONTINUE'), result: false },
  9974. { msg: I18N('BTN_NO'), result: true },
  9975. ])) {
  9976. this.terminatеReason = I18N('NOT_ENOUGH_AP');
  9977. return this.end();
  9978. }
  9979. const toPath = [];
  9980. for (const nodeId of this.path) {
  9981. if (!this.turnsLeft) {
  9982. this.terminatеReason = I18N('ATTEMPTS_ARE_OVER');
  9983. return this.end();
  9984. }
  9985. toPath.push(nodeId);
  9986. console.log(toPath);
  9987. if (toPath.length > 1) {
  9988. setProgress(toPath.join(' > ') + ` ${I18N('MOVES')}: ` + this.turnsLeft);
  9989. }
  9990. if (nodeId == this.currentNode) {
  9991. continue;
  9992. }
  9993.  
  9994. const nodeInfo = this.getNodeInfo(nodeId);
  9995. if (nodeInfo.type == 'TYPE_COMBAT') {
  9996. if (nodeInfo.state == 'empty') {
  9997. this.turnsLeft--;
  9998. continue;
  9999. }
  10000.  
  10001. /**
  10002. * Disable regular battle cancellation
  10003. *
  10004. * Отключаем штатную отменую боя
  10005. */
  10006. isCancalBattle = false;
  10007. if (await this.battle(toPath)) {
  10008. this.turnsLeft--;
  10009. toPath.splice(0, toPath.indexOf(nodeId));
  10010. nodeInfo.state = 'empty';
  10011. isCancalBattle = true;
  10012. continue;
  10013. }
  10014. isCancalBattle = true;
  10015. return this.end()
  10016. }
  10017.  
  10018. if (nodeInfo.type == 'TYPE_PLAYERBUFF') {
  10019. const buff = this.checkBuff(nodeInfo);
  10020. if (buff == null) {
  10021. continue;
  10022. }
  10023.  
  10024. if (await this.collectBuff(buff, toPath)) {
  10025. this.turnsLeft--;
  10026. toPath.splice(0, toPath.indexOf(nodeId));
  10027. continue;
  10028. }
  10029. this.terminatеReason = I18N('BUFF_GET_ERROR');
  10030. return this.end();
  10031. }
  10032. }
  10033. this.terminatеReason = I18N('SUCCESS');
  10034. return this.end();
  10035. }
  10036.  
  10037. /**
  10038. * Carrying out a fight
  10039. *
  10040. * Проведение боя
  10041. */
  10042. async battle(path, preCalc = true) {
  10043. const data = await this.startBattle(path);
  10044. try {
  10045. const battle = data.results[0].result.response.battle;
  10046. const result = await Calc(battle);
  10047. if (result.result.win) {
  10048. const info = await this.endBattle(result);
  10049. if (info.results[0].result.response?.error) {
  10050. this.terminatеReason = I18N('BATTLE_END_ERROR');
  10051. return false;
  10052. }
  10053. } else {
  10054. await this.cancelBattle(result);
  10055.  
  10056. if (preCalc && await this.preCalcBattle(battle)) {
  10057. path = path.slice(-2);
  10058. for (let i = 1; i <= getInput('countAutoBattle'); i++) {
  10059. setProgress(`${I18N('AUTOBOT')}: ${i}/${getInput('countAutoBattle')}`);
  10060. const result = await this.battle(path, false);
  10061. if (result) {
  10062. setProgress(I18N('VICTORY'));
  10063. return true;
  10064. }
  10065. }
  10066. this.terminatеReason = I18N('FAILED_TO_WIN_AUTO');
  10067. return false;
  10068. }
  10069. return false;
  10070. }
  10071. } catch (error) {
  10072. console.error(error);
  10073. if (await popup.confirm(I18N('ERROR_OF_THE_BATTLE_COPY'), [
  10074. { msg: I18N('BTN_NO'), result: false },
  10075. { msg: I18N('BTN_YES'), result: true },
  10076. ])) {
  10077. this.errorHandling(error, data);
  10078. }
  10079. this.terminatеReason = I18N('ERROR_DURING_THE_BATTLE');
  10080. return false;
  10081. }
  10082. return true;
  10083. }
  10084.  
  10085. /**
  10086. * Recalculate battles
  10087. *
  10088. * Прерасчтет битвы
  10089. */
  10090. async preCalcBattle(battle) {
  10091. const countTestBattle = getInput('countTestBattle');
  10092. for (let i = 0; i < countTestBattle; i++) {
  10093. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  10094. const result = await Calc(battle);
  10095. if (result.result.win) {
  10096. console.log(i, countTestBattle);
  10097. return true;
  10098. }
  10099. }
  10100. this.terminatеReason = I18N('NO_CHANCE_WIN') + countTestBattle;
  10101. return false;
  10102. }
  10103.  
  10104. /**
  10105. * Starts a fight
  10106. *
  10107. * Начинает бой
  10108. */
  10109. startBattle(path) {
  10110. this.args.path = path;
  10111. this.callStartBattle.name = this.actions[this.type].startBattle;
  10112. this.callStartBattle.args = this.args
  10113. const calls = [this.callStartBattle];
  10114. return Send(JSON.stringify({ calls }));
  10115. }
  10116.  
  10117. cancelBattle(battle) {
  10118. const fixBattle = function (heroes) {
  10119. for (const ids in heroes) {
  10120. const hero = heroes[ids];
  10121. hero.energy = random(1, 999);
  10122. if (hero.hp > 0) {
  10123. hero.hp = random(1, hero.hp);
  10124. }
  10125. }
  10126. }
  10127. fixBattle(battle.progress[0].attackers.heroes);
  10128. fixBattle(battle.progress[0].defenders.heroes);
  10129. return this.endBattle(battle);
  10130. }
  10131.  
  10132. /**
  10133. * Ends the fight
  10134. *
  10135. * Заканчивает бой
  10136. */
  10137. endBattle(battle) {
  10138. this.callEndBattle.name = this.actions[this.type].endBattle;
  10139. this.callEndBattle.args.result = battle.result
  10140. this.callEndBattle.args.progress = battle.progress
  10141. const calls = [this.callEndBattle];
  10142. return Send(JSON.stringify({ calls }));
  10143. }
  10144.  
  10145. /**
  10146. * Checks if you can get a buff
  10147. *
  10148. * Проверяет можно ли получить баф
  10149. */
  10150. checkBuff(nodeInfo) {
  10151. let id = null;
  10152. let value = 0;
  10153. for (const buffId in nodeInfo.buffs) {
  10154. const buff = nodeInfo.buffs[buffId];
  10155. if (buff.owner == null && buff.value > value) {
  10156. id = buffId;
  10157. value = buff.value;
  10158. }
  10159. }
  10160. nodeInfo.buffs[id].owner = 'Я';
  10161. return id;
  10162. }
  10163.  
  10164. /**
  10165. * Collects a buff
  10166. *
  10167. * Собирает баф
  10168. */
  10169. async collectBuff(buff, path) {
  10170. this.callCollectBuff.name = this.actions[this.type].collectBuff;
  10171. this.callCollectBuff.args = { buff, path };
  10172. const calls = [this.callCollectBuff];
  10173. return Send(JSON.stringify({ calls }));
  10174. }
  10175.  
  10176. getNodeInfo(nodeId) {
  10177. return this.nodes.find(node => node.id == nodeId);
  10178. }
  10179.  
  10180. errorHandling(error, data) {
  10181. //console.error(error);
  10182. let errorInfo = error.toString() + '\n';
  10183. try {
  10184. const errorStack = error.stack.split('\n');
  10185. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testAdventure");
  10186. errorInfo += errorStack.slice(0, endStack).join('\n');
  10187. } catch (e) {
  10188. errorInfo += error.stack;
  10189. }
  10190. if (data) {
  10191. errorInfo += '\nData: ' + JSON.stringify(data);
  10192. }
  10193. copyText(errorInfo);
  10194. }
  10195.  
  10196. end() {
  10197. isCancalBattle = true;
  10198. setProgress(this.terminatеReason, true);
  10199. console.log(this.terminatеReason);
  10200. this.resolve();
  10201. }
  10202. }
  10203.  
  10204. /**
  10205. * Passage of brawls
  10206. *
  10207. * Прохождение потасовок
  10208. */
  10209. function testBrawls() {
  10210. return new Promise((resolve, reject) => {
  10211. const brawls = new executeBrawls(resolve, reject);
  10212. brawls.start(brawlsPack);
  10213. });
  10214. }
  10215. /**
  10216. * Passage of brawls
  10217. *
  10218. * Прохождение потасовок
  10219. */
  10220. class executeBrawls {
  10221. callBrawlQuestGetInfo = {
  10222. name: "brawl_questGetInfo",
  10223. args: {},
  10224. ident: "brawl_questGetInfo"
  10225. }
  10226. callBrawlFindEnemies = {
  10227. name: "brawl_findEnemies",
  10228. args: {},
  10229. ident: "brawl_findEnemies"
  10230. }
  10231. callBrawlQuestFarm = {
  10232. name: "brawl_questFarm",
  10233. args: {},
  10234. ident: "brawl_questFarm"
  10235. }
  10236. callUserGetInfo = {
  10237. name: "userGetInfo",
  10238. args: {},
  10239. ident: "userGetInfo"
  10240. }
  10241. callTeamGetMaxUpgrade = {
  10242. name: "teamGetMaxUpgrade",
  10243. args: {},
  10244. ident: "teamGetMaxUpgrade"
  10245. }
  10246. callBrawlGetInfo = {
  10247. name: "brawl_getInfo",
  10248. args: {},
  10249. ident: "brawl_getInfo"
  10250. }
  10251.  
  10252. stats = {
  10253. win: 0,
  10254. loss: 0,
  10255. count: 0,
  10256. }
  10257.  
  10258. stage = {
  10259. '3': 1,
  10260. '7': 2,
  10261. '12': 3,
  10262. }
  10263.  
  10264. attempts = 0;
  10265.  
  10266. constructor(resolve, reject) {
  10267. this.resolve = resolve;
  10268. this.reject = reject;
  10269. }
  10270.  
  10271. async start(args) {
  10272. this.args = args;
  10273. isCancalBattle = false;
  10274. this.brawlInfo = await this.getBrawlInfo();
  10275. this.attempts = this.brawlInfo.attempts;
  10276.  
  10277. if (!this.attempts) {
  10278. this.end(I18N('DONT_HAVE_LIVES'))
  10279. return;
  10280. }
  10281.  
  10282. while (1) {
  10283. if (!isBrawlsAutoStart) {
  10284. this.end(I18N('BTN_CANCELED'))
  10285. return;
  10286. }
  10287.  
  10288. const maxStage = this.brawlInfo.questInfo.stage;
  10289. const stage = this.stage[maxStage];
  10290. const progress = this.brawlInfo.questInfo.progress;
  10291.  
  10292. 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 () {
  10293. isBrawlsAutoStart = false;
  10294. });
  10295.  
  10296. if (this.brawlInfo.questInfo.canFarm) {
  10297. const result = await this.questFarm();
  10298. console.log(result);
  10299. }
  10300.  
  10301. if (this.brawlInfo.questInfo.stage == 12 && this.brawlInfo.questInfo.progress == 12) {
  10302. this.end(I18N('SUCCESS'))
  10303. return;
  10304. }
  10305.  
  10306. if (!this.attempts) {
  10307. this.end(I18N('DONT_HAVE_LIVES'))
  10308. return;
  10309. }
  10310.  
  10311. const enemie = Object.values(this.brawlInfo.findEnemies).shift();
  10312.  
  10313. // Для потасовок брустара
  10314. this.args.heroes = await this.updatePack(enemie.heroes);
  10315.  
  10316. const result = await this.battle(enemie.userId);
  10317. this.brawlInfo = {
  10318. questInfo: result[1].result.response,
  10319. findEnemies: result[2].result.response,
  10320. }
  10321. }
  10322. }
  10323.  
  10324. async updatePack(enemieHeroes) {
  10325. const packs = [
  10326. // 4023 Эдем
  10327. [4020, 4022, 4023, 4042, 4043],
  10328. [4023, 4030, 4033, 4042, 4043],
  10329. [4023, 4040, 4041, 4042, 4043],
  10330. // Разное
  10331. [4003, 4010, 4011, 4012, 4013],
  10332. [4030, 4032, 4033, 4040, 4043],
  10333. [4033, 4040, 4041, 4042, 4043],
  10334. [4030, 4031, 4033, 4040, 4043],
  10335. [4030, 4033, 4040, 4042, 4043],
  10336. [4001, 4032, 4033, 4040, 4043],
  10337. [4010, 4012, 4013, 4040, 4043],
  10338. [4001, 4002, 4003, 4040, 4043],
  10339. // 4003 Гиперион
  10340. [4000, 4001, 4003, 4033, 4043],
  10341. [4000, 4001, 4003, 4023, 4030],
  10342. [4000, 4001, 4003, 4023, 4033],
  10343. [4000, 4001, 4003, 4013, 4033],
  10344. [4003, 4010, 4012, 4013, 4043],
  10345. [4003, 4010, 4012, 4013, 4033],
  10346. [4003, 4030, 4032, 4042, 4043],
  10347. [4003, 4030, 4031, 4032, 4033],
  10348. [4003, 4040, 4041, 4042, 4043],
  10349. [4003, 4030, 4033, 4040, 4043],
  10350. // 4013 Араджи
  10351. [4010, 4011, 4012, 4013, 4033],
  10352. [4010, 4011, 4012, 4013, 4043],
  10353. [4010, 4011, 4013, 4042, 4043],
  10354. [4010, 4011, 4013, 4033, 4043],
  10355. [4001, 4010, 4011, 4013, 4033],
  10356. [4010, 4011, 4013, 4030, 4033],
  10357. [4010, 4011, 4013, 4040, 4043],
  10358. [4013, 4030, 4033, 4040, 4043],
  10359. [4013, 4030, 4033, 4042, 4043],
  10360. [4013, 4020, 4022, 4023, 4033],
  10361. ].filter(p => p.includes(this.mandatoryId))
  10362.  
  10363. const bestPack = {
  10364. pack: packs[0],
  10365. countWin: 0,
  10366. }
  10367.  
  10368. for (const pack of packs) {
  10369. const attackers = this.maxUpgrade
  10370. .filter(e => pack.includes(e.id))
  10371. .reduce((obj, e) => ({ ...obj, [e.id]: e }), {});
  10372. const battle = {
  10373. attackers,
  10374. defenders: [enemieHeroes],
  10375. type: "brawl_titan",
  10376. }
  10377.  
  10378. let countWinBattles = 0;
  10379. let countTestBattle = 10;
  10380. for (let i = 0; i < countTestBattle; i++) {
  10381. battle.seed = Math.floor(Date.now() / 1000) + Math.random() * 1000;
  10382. const result = await Calc(battle);
  10383. if (result.result.win) {
  10384. countWinBattles++;
  10385. }
  10386. if (countWinBattles > 7) {
  10387. console.log(pack)
  10388. return pack;
  10389. }
  10390. }
  10391. if (countWinBattles > bestPack.countWin) {
  10392. bestPack.countWin = countWinBattles;
  10393. bestPack.pack = pack;
  10394. }
  10395. }
  10396.  
  10397. console.log(bestPack);
  10398. return bestPack.pack;
  10399. }
  10400.  
  10401. async questFarm() {
  10402. const calls = [this.callBrawlQuestFarm];
  10403. const result = await Send(JSON.stringify({ calls }));
  10404. return result.results[0].result.response;
  10405. }
  10406.  
  10407. async getBrawlInfo() {
  10408. const data = await Send(JSON.stringify({
  10409. calls: [
  10410. this.callUserGetInfo,
  10411. this.callBrawlQuestGetInfo,
  10412. this.callBrawlFindEnemies,
  10413. this.callTeamGetMaxUpgrade,
  10414. this.callBrawlGetInfo,
  10415. ]
  10416. }));
  10417.  
  10418. let attempts = data.results[0].result.response.refillable.find(n => n.id == 48);
  10419. this.maxUpgrade = Object.values(data.results[3].result.response.titan);
  10420. this.info = data.results[4].result.response;
  10421. this.mandatoryId = lib.data.brawl.promoHero[this.info.id].promoHero;
  10422. return {
  10423. attempts: attempts.amount,
  10424. questInfo: data.results[1].result.response,
  10425. findEnemies: data.results[2].result.response,
  10426. }
  10427. }
  10428.  
  10429. /**
  10430. * Carrying out a fight
  10431. *
  10432. * Проведение боя
  10433. */
  10434. async battle(userId) {
  10435. this.stats.count++;
  10436. const battle = await this.startBattle(userId, this.args);
  10437. const result = await Calc(battle);
  10438. console.log(result.result);
  10439. if (result.result.win) {
  10440. this.stats.win++;
  10441. } else {
  10442. this.stats.loss++;
  10443. this.attempts--;
  10444. }
  10445. return await this.endBattle(result);
  10446. // return await this.cancelBattle(result);
  10447. }
  10448.  
  10449. /**
  10450. * Starts a fight
  10451. *
  10452. * Начинает бой
  10453. */
  10454. async startBattle(userId, args) {
  10455. const call = {
  10456. name: "brawl_startBattle",
  10457. args,
  10458. ident: "brawl_startBattle"
  10459. }
  10460. call.args.userId = userId;
  10461. const calls = [call];
  10462. const result = await Send(JSON.stringify({ calls }));
  10463. return result.results[0].result.response;
  10464. }
  10465.  
  10466. cancelBattle(battle) {
  10467. const fixBattle = function (heroes) {
  10468. for (const ids in heroes) {
  10469. const hero = heroes[ids];
  10470. hero.energy = random(1, 999);
  10471. if (hero.hp > 0) {
  10472. hero.hp = random(1, hero.hp);
  10473. }
  10474. }
  10475. }
  10476. fixBattle(battle.progress[0].attackers.heroes);
  10477. fixBattle(battle.progress[0].defenders.heroes);
  10478. return this.endBattle(battle);
  10479. }
  10480.  
  10481. /**
  10482. * Ends the fight
  10483. *
  10484. * Заканчивает бой
  10485. */
  10486. async endBattle(battle) {
  10487. battle.progress[0].attackers.input = ['auto', 0, 0, 'auto', 0, 0];
  10488. const calls = [{
  10489. name: "brawl_endBattle",
  10490. args: {
  10491. result: battle.result,
  10492. progress: battle.progress
  10493. },
  10494. ident: "brawl_endBattle"
  10495. },
  10496. this.callBrawlQuestGetInfo,
  10497. this.callBrawlFindEnemies,
  10498. ];
  10499. const result = await Send(JSON.stringify({ calls }));
  10500. return result.results;
  10501. }
  10502.  
  10503. end(endReason) {
  10504. isCancalBattle = true;
  10505. isBrawlsAutoStart = false;
  10506. setProgress(endReason, true);
  10507. console.log(endReason);
  10508. this.resolve();
  10509. }
  10510. }
  10511.  
  10512. })();
  10513.  
  10514. /**
  10515. * TODO:
  10516. * Получение всех уровней при сборе всех наград (квест на титанит и на энку) +-
  10517. * Добивание на арене титанов
  10518. * Закрытие окошек по Esc +-
  10519. * Починить работу скрипта на уровне команды ниже 10 +-
  10520. * Написать номальную синхронизацию
  10521. * Добавить дополнительные настройки автопокупки в "Тайном богатстве"
  10522. */