HeroWarsDungeon

Automation of actions for the game Hero Wars

目前为 2023-10-24 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name HeroWarsDungeon
  3. // @name:en HeroWarsDungeon
  4. // @name:ru HeroWarsDungeon
  5. // @namespace HeroWarsDungeon
  6. // @version 2.153.5
  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, ApuoH, Gudwin
  11. // @license Copyright ZingerY
  12. // @homepage http://ilovemycomp.narod.ru/HeroWarsHelper.user.js
  13. // @icon http://ilovemycomp.narod.ru/VaultBoyIco16.ico
  14. // @icon64 http://ilovemycomp.narod.ru/VaultBoyIco64.png
  15. // @encoding utf-8
  16. // @include https://*.nextersglobal.com/*
  17. // @include https://*.hero-wars*.com/*
  18. // @match https://www.solfors.com/
  19. // @match https://t.me/s/hw_ru
  20. // @run-at document-start
  21. // ==/UserScript==
  22.  
  23. (function() {
  24. /**
  25. * Start script
  26. *
  27. * Стартуем скрипт
  28. */
  29. console.log('Start ' + GM_info.script.name + ', v' + GM_info.script.version);
  30. /**
  31. * Script info
  32. *
  33. * Информация о скрипте
  34. */
  35. const scriptInfo = (({name, version, author, homepage, lastModified}, updateUrl, source) =>
  36. ({name, version, author, homepage, lastModified, updateUrl, source}))
  37. (GM_info.script, GM_info.scriptUpdateURL, arguments.callee.toString());
  38. /**
  39. * If we are on the gifts page, then we collect and send them to the server
  40. *
  41. * Если находимся на странице подарков, то собираем и отправляем их на сервер
  42. */
  43. if (['www.solfors.com', 't.me'].includes(location.host)) {
  44. setTimeout(sendCodes, 2000);
  45. return;
  46. }
  47. /**
  48. * Information for completing daily quests
  49. *
  50. * Информация для выполнения ежендевных квестов
  51. */
  52. const questsInfo = {};
  53. /**
  54. * Is the game data loaded
  55. *
  56. * Загружены ли данные игры
  57. */
  58. let isLoadGame = false;
  59. /**
  60. * Headers of the last request
  61. *
  62. * Заголовки последнего запроса
  63. */
  64. let lastHeaders = {};
  65. /**
  66. * Information about sent gifts
  67. *
  68. * Информация об отправленных подарках
  69. */
  70. let freebieCheckInfo = null;
  71. /** Пачки для тестов в чате*/ //тест сохранка
  72. let repleyBattle = {
  73. defenders: {},
  74. attackers: {},
  75. effects: {},
  76. state: {},
  77. seed: undefined
  78. }
  79. /**
  80. * User data
  81. *
  82. * Данные пользователя
  83. */
  84. let userInfo;
  85. /**
  86. * Original methods for working with AJAX
  87. *
  88. * Оригинальные методы для работы с AJAX
  89. */
  90. const original = {
  91. open: XMLHttpRequest.prototype.open,
  92. send: XMLHttpRequest.prototype.send,
  93. setRequestHeader: XMLHttpRequest.prototype.setRequestHeader,
  94. };
  95. /**
  96. * Decoder for converting byte data to JSON string
  97. *
  98. * Декодер для перобразования байтовых данных в JSON строку
  99. */
  100. const decoder = new TextDecoder("utf-8");
  101. /**
  102. * Stores a history of requests
  103. *
  104. * Хранит историю запросов
  105. */
  106. let requestHistory = {};
  107. /**
  108. * URL for API requests
  109. *
  110. * URL для запросов к API
  111. */
  112. let apiUrl = '';
  113.  
  114. /**
  115. * Connecting to the game code
  116. *
  117. * Подключение к коду игры
  118. */
  119. this.cheats = new hackGame();
  120. /**
  121. * The function of calculating the results of the battle
  122. *
  123. * Функция расчета результатов боя
  124. */
  125. this.BattleCalc = cheats.BattleCalc;
  126. /**
  127. * Sending a request available through the console
  128. *
  129. * Отправка запроса доступная через консоль
  130. */
  131. this.SendRequest = send;
  132. /**
  133. * Simple combat calculation available through the console
  134. *
  135. * Простой расчет боя доступный через консоль
  136. */
  137. this.Calc = function (data) {
  138. const type = getBattleType(data?.type);
  139. return new Promise((resolve, reject) => {
  140. try {
  141. BattleCalc(data, type, resolve);
  142. } catch (e) {
  143. reject(e);
  144. }
  145. })
  146. }
  147. //тест остановка подземки
  148. let stopDung = false;
  149. /**
  150. * Short asynchronous request
  151. * Usage example (returns information about a character):
  152. * const userInfo = await Send('{"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}')
  153. *
  154. * Короткий асинхронный запрос
  155. * Пример использования (возвращает информацию о персонаже):
  156. * const userInfo = await Send('{"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}')
  157. */
  158. this.Send = function (json, pr) {
  159. return new Promise((resolve, reject) => {
  160. try {
  161. send(json, resolve, pr);
  162. } catch (e) {
  163. reject(e);
  164. }
  165. })
  166. }
  167.  
  168. const i18nLangData = {
  169. /* English translation by BaBa */
  170. en: {
  171. /* Checkboxes */
  172. SKIP_FIGHTS: 'Skip battle',
  173. SKIP_FIGHTS_TITLE: 'Skip battle in Outland and the arena of the titans, auto-pass in the tower and campaign',
  174. ENDLESS_CARDS: 'Infinite cards',
  175. ENDLESS_CARDS_TITLE: 'Disable Divination Cards wasting',
  176. AUTO_EXPEDITION: 'Auto Expedition',
  177. AUTO_EXPEDITION_TITLE: 'Auto-sending expeditions',
  178. CANCEL_FIGHT: 'Cancel battle',
  179. CANCEL_FIGHT_TITLE: 'The possibility of canceling the battle on VG',
  180. GIFTS: 'Gifts',
  181. GIFTS_TITLE: 'Collect gifts automatically',
  182. BATTLE_RECALCULATION: 'Battle recalculation',
  183. BATTLE_RECALCULATION_TITLE: 'Preliminary calculation of the battle',
  184. BATTLE_FISHING: 'Finishing',
  185. BATTLE_FISHING_TITLE: 'Finishing off the team from the last replay in the chat',
  186. BATTLE_TRENING: 'Workout',
  187. BATTLE_TRENING_TITLE: 'A training battle in the chat against the team from the last replay',
  188. QUANTITY_CONTROL: 'Quantity control',
  189. QUANTITY_CONTROL_TITLE: 'Ability to specify the number of opened "lootboxes"',
  190. REPEAT_CAMPAIGN: 'Repeat missions',
  191. REPEAT_CAMPAIGN_TITLE: 'Auto-repeat battles in the campaign',
  192. DISABLE_DONAT: 'Disable donation',
  193. DISABLE_DONAT_TITLE: 'Removes all donation offers',
  194. DAILY_QUESTS: 'Quests',
  195. DAILY_QUESTS_TITLE: 'Complete daily quests',
  196. AUTO_QUIZ: 'AutoQuiz',
  197. AUTO_QUIZ_TITLE: 'Automatically receive correct answers to quiz questions',
  198. SECRET_WEALTH_CHECKBOX: 'Automatic purchase in the store "Secret Wealth" when entering the game',
  199. /* Input fields */
  200. HOW_MUCH_TITANITE: 'How much titanite to farm',
  201. COMBAT_SPEED: 'Combat Speed Multiplier',
  202. HOW_REPEAT_CAMPAIGN: 'how many mission replays', //тест добавил
  203. NUMBER_OF_TEST: 'Number of test fights',
  204. NUMBER_OF_AUTO_BATTLE: 'Number of auto-battle attempts',
  205. /* Buttons */
  206. RUN_SCRIPT: 'Run the',
  207. STOP_SCRIPT: 'Stop the',
  208. TO_DO_EVERYTHING: 'Do All',
  209. TO_DO_EVERYTHING_TITLE: 'Perform multiple actions of your choice',
  210. OUTLAND: 'Outland',
  211. OUTLAND_TITLE: 'Collect Outland',
  212. TITAN_ARENA: 'ToE',
  213. TITAN_ARENA_TITLE: 'Complete the titan arena',
  214. DUNGEON: 'Dungeon',
  215. DUNGEON_TITLE: 'Go through the dungeon',
  216. DUNGEON2: 'Dungeon full',
  217. DUNGEON_FULL_TITLE: 'Dungeon for Full Titans',
  218. STOP_DUNGEON: 'Stop Dungeon',
  219. STOP_DUNGEON_TITLE: 'Stop digging the dungeon',
  220. TOWER: 'Tower',
  221. TOWER_TITLE: 'Pass the tower',
  222. EXPEDITIONS: 'Expeditions',
  223. EXPEDITIONS_TITLE: 'Sending and collecting expeditions',
  224. SYNC: 'Sync',
  225. SYNC_TITLE: 'Partial synchronization of game data without reloading the page',
  226. ARCHDEMON: 'Archdemon',
  227. ARCHDEMON_TITLE: 'Hitting kills and collecting rewards',
  228. ESTER_EGGS: 'Easter eggs',
  229. ESTER_EGGS_TITLE: 'Collect all Easter eggs or rewards',
  230. REWARDS: 'Rewards',
  231. REWARDS_TITLE: 'Collect all quest rewards',
  232. MAIL: 'Mail',
  233. MAIL_TITLE: 'Collect all mail, except letters with energy and charges of the portal',
  234. MINIONS: 'Minions',
  235. MINIONS_TITLE: 'Attack minions with saved packs',
  236. ADVENTURE: 'Adventure',
  237. ADVENTURE_TITLE: 'Passes the adventure along the specified route',
  238. STORM: 'Storm',
  239. STORM_TITLE: 'Passes the Storm along the specified route',
  240. SANCTUARY: 'Sanctuary',
  241. SANCTUARY_TITLE: 'Fast travel to Sanctuary',
  242. GUILD_WAR: 'Guild War',
  243. GUILD_WAR_TITLE: 'Fast travel to Guild War',
  244. SECRET_WEALTH: 'Secret Wealth',
  245. SECRET_WEALTH_TITLE: 'Buy something in the store "Secret Wealth"',
  246. /* Misc */
  247. BOTTOM_URLS: '<a href="https://t.me/+0oMwICyV1aQ1MDAy" target="_blank" title="Telegram"><svg style="margin: 2px;" width="20" height="20" viewBox="0 0 1000 1000" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><defs><linearGradient x1="50%" y1="0%" x2="50%" y2="99.2583404%" id="linearGradient-1"><stop stop-color="#2AABEE" offset="0%"></stop><stop stop-color="#229ED9" offset="100%"></stop></linearGradient></defs><g id="Artboard" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"><circle id="Oval" fill="url(#linearGradient-1)" cx="500" cy="500" r="500"></circle><path d="M226.328419,494.722069 C372.088573,431.216685 469.284839,389.350049 517.917216,369.122161 C656.772535,311.36743 685.625481,301.334815 704.431427,301.003532 C708.567621,300.93067 717.815839,301.955743 723.806446,306.816707 C728.864797,310.92121 730.256552,316.46581 730.922551,320.357329 C731.588551,324.248848 732.417879,333.113828 731.758626,340.040666 C724.234007,419.102486 691.675104,610.964674 675.110982,699.515267 C668.10208,736.984342 654.301336,749.547532 640.940618,750.777006 C611.904684,753.448938 589.856115,731.588035 561.733393,713.153237 C517.726886,684.306416 492.866009,666.349181 450.150074,638.200013 C400.78442,605.66878 432.786119,587.789048 460.919462,558.568563 C468.282091,550.921423 596.21508,434.556479 598.691227,424.000355 C599.00091,422.680135 599.288312,417.758981 596.36474,415.160431 C593.441168,412.561881 589.126229,413.450484 586.012448,414.157198 C581.598758,415.158943 511.297793,461.625274 375.109553,553.556189 C355.154858,567.258623 337.080515,573.934908 320.886524,573.585046 C303.033948,573.199351 268.692754,563.490928 243.163606,555.192408 C211.851067,545.013936 186.964484,539.632504 189.131547,522.346309 C190.260287,513.342589 202.659244,504.134509 226.328419,494.722069 Z" id="Path-3" fill="#FFFFFF"></path></g></svg></a>',
  248. GIFTS_SENT: 'Gifts sent!',
  249. DO_YOU_WANT: "Do you really want to do this?",
  250. BTN_RUN: 'Run',
  251. BTN_CANCEL: 'Cancel',
  252. BTN_OK: 'OK',
  253. MSG_HAVE_BEEN_DEFEATED: 'You have been defeated!',
  254. BTN_AUTO: 'Auto',
  255. MSG_YOU_APPLIED: 'You applied',
  256. MSG_DAMAGE: 'damage',
  257. MSG_CANCEL_AND_STAT: 'Auto (F5) and show statistic',
  258. MSG_REPEAT_MISSION: 'Repeat the mission?',
  259. BTN_REPEAT: 'Repeat',
  260. BTN_NO: 'No',
  261. MSG_SPECIFY_QUANT: 'Specify Quantity:',
  262. BTN_OPEN: 'Open',
  263. QUESTION_COPY: 'Question copied to clipboard',
  264. ANSWER_KNOWN: 'The answer is known',
  265. ANSWER_NOT_KNOWN: 'ATTENTION THE ANSWER IS NOT KNOWN',
  266. BEING_RECALC: 'The battle is being recalculated',
  267. THIS_TIME: 'This time',
  268. VICTORY: 'VICTORY',
  269. DEFEAT: 'DEFEAT',
  270. CHANCE_TO_WIN: "Chance to win",
  271. OPEN_DOLLS: 'nesting dolls recursively',
  272. SENT_QUESTION: 'Question sent',
  273. SETTINGS: 'Settings',
  274. MSG_BAN_ATTENTION: '<p style="color:red;">Using this feature may result in a ban.</p> Continue?',
  275. BTN_YES_I_AGREE: 'Yes, I understand the risks!',
  276. BTN_NO_I_AM_AGAINST: 'No, I refuse it!',
  277. VALUES: 'Values',
  278. SAVING: 'Saving',
  279. EXPEDITIONS_SENT: 'Expeditions sent',
  280. TITANIT: 'Titanit',
  281. COMPLETED: 'completed',
  282. FLOOR: 'Floor',
  283. LEVEL: 'Level',
  284. BATTLES: 'battles',
  285. EVENT: 'Event',
  286. NOT_AVAILABLE: 'not available',
  287. NO_HEROES: 'No heroes',
  288. DAMAGE_AMOUNT: 'Damage amount',
  289. NOTHING_TO_COLLECT: 'Nothing to collect',
  290. COLLECTED: 'Collected',
  291. REWARD: 'rewards',
  292. REMAINING_ATTEMPTS: 'Remaining attempts',
  293. BATTLES_CANCELED: 'Battles canceled',
  294. MINION_RAID: 'Minion Raid',
  295. STOPPED: 'Stopped',
  296. REPETITIONS: 'Repetitions',
  297. MISSIONS_PASSED: 'Missions passed',
  298. STOP: 'stop',
  299. TOTAL_OPEN: 'Total open',
  300. OPEN: 'Open',
  301. ROUND_STAT: 'Damage statistics for ',
  302. BATTLE: 'battles',
  303. MINIMUM: 'Minimum',
  304. MAXIMUM: 'Maximum',
  305. AVERAGE: 'Average',
  306. NOT_THIS_TIME: 'Not this time',
  307. RETRY_LIMIT_EXCEEDED: 'Retry limit exceeded',
  308. SUCCESS: 'Success',
  309. RECEIVED: 'Received',
  310. LETTERS: 'letters',
  311. PORTALS: 'portals',
  312. ATTEMPTS: 'attempts',
  313. /* Quests */
  314. QUEST_10001: 'Upgrade the skills of heroes 3 times',
  315. QUEST_10002: 'Complete 10 missions',
  316. QUEST_10003: 'Complete 3 heroic missions',
  317. QUEST_10004: 'Fight 3 times in the Arena or Grand Arena',
  318. QUEST_10006: 'Use the exchange of emeralds 1 time',
  319. QUEST_10007: 'Perform 1 summon in the Solu Atrium',
  320. QUEST_10016: 'Send gifts to guildmates',
  321. QUEST_10018: 'Use an experience potion',
  322. QUEST_10019: 'Open 1 chest in the Tower',
  323. QUEST_10020: 'Open 3 chests in Outland',
  324. QUEST_10021: 'Collect 75 Titanite in the Guild Dungeon',
  325. QUEST_10021: 'Collect 150 Titanite in the Guild Dungeon',
  326. QUEST_10023: 'Upgrade Gift of the Elements by 1 level',
  327. QUEST_10024: 'Level up any artifact once',
  328. QUEST_10025: 'Start Expedition 1',
  329. QUEST_10026: 'Start 4 Expeditions',
  330. QUEST_10027: 'Win 1 battle of the Tournament of Elements',
  331. QUEST_10028: 'Level up any titan artifact',
  332. QUEST_10029: 'Unlock the Orb of Titan Artifacts',
  333. QUEST_10030: 'Upgrade any Skin of any hero 1 time',
  334. QUEST_10031: 'Win 6 battles of the Tournament of Elements',
  335. QUEST_10043: 'Start or Join an Adventure',
  336. QUEST_10044: 'Use Summon Pets 1 time',
  337. QUEST_10046: 'Open 3 chests in Adventure',
  338. QUEST_10047: 'Get 150 Guild Activity Points',
  339. NOTHING_TO_DO: 'Nothing to do',
  340. YOU_CAN_COMPLETE: 'You can complete quests',
  341. BTN_DO_IT: 'Do it',
  342. NOT_QUEST_COMPLETED: 'Not a single quest completed',
  343. COMPLETED_QUESTS: 'Completed quests',
  344. /* everything button */
  345. ASSEMBLE_OUTLAND: 'Assemble Outland',
  346. PASS_THE_TOWER: 'Pass the tower',
  347. CHECK_EXPEDITIONS: 'Check Expeditions',
  348. COMPLETE_TOE: 'Complete ToE',
  349. COMPLETE_DUNGEON: 'Complete the dungeon',
  350. COLLECT_MAIL: 'Collect mail',
  351. COLLECT_MISC: 'Collect some bullshit',
  352. COLLECT_MISC_TITLE: 'Collect Easter Eggs, Skin Gems, Keys, Arena Coins and Soul Crystal',
  353. COLLECT_QUEST_REWARDS: 'Collect quest rewards',
  354. MAKE_A_SYNC: 'Make a sync',
  355.  
  356. RUN_FUNCTION: 'Run the following functions?',
  357. BTN_GO: 'Go!',
  358. PERFORMED: 'Performed',
  359. DONE: 'Done',
  360. ERRORS_OCCURRES: 'Errors occurred while executing',
  361. COPY_ERROR: 'Copy error information to clipboard',
  362. BTN_YES: 'Yes',
  363. ALL_TASK_COMPLETED: 'All tasks completed',
  364.  
  365. UNKNOWN: 'unknown',
  366. ENTER_THE_PATH: 'Enter the path of adventure using commas or dashes',
  367. START_ADVENTURE: 'Start your adventure along this path!',
  368. BTN_CANCELED: 'Canceled',
  369. MUST_TWO_POINTS: 'The path must contain at least 2 points.',
  370. MUST_ONLY_NUMBERS: 'The path must contain only numbers and commas',
  371. NOT_ON_AN_ADVENTURE: 'You are not on an adventure',
  372. YOU_IN_NOT_ON_THE_WAY: 'Your location is not on the way',
  373. ATTEMPTS_NOT_ENOUGH: 'Your attempts are not enough to complete the path, continue?',
  374. YES_CONTINUE: 'Yes, continue!',
  375. NOT_ENOUGH_AP: 'Not enough action points',
  376. ATTEMPTS_ARE_OVER: 'The attempts are over',
  377. MOVES: 'Moves',
  378. BUFF_GET_ERROR: 'Buff getting error',
  379. BATTLE_END_ERROR: 'Battle end error',
  380. AUTOBOT: 'Autobot',
  381. FAILED_TO_WIN_AUTO: 'Failed to win the auto battle',
  382. ERROR_OF_THE_BATTLE_COPY: 'An error occurred during the passage of the battle<br>Copy the error to the clipboard?',
  383. ERROR_DURING_THE_BATTLE: 'Error during the battle',
  384. NO_CHANCE_WIN: 'No chance of winning this fight: 0/',
  385. LOST_HEROES: 'You have won, but you have lost one or several heroes',
  386. VICTORY_IMPOSSIBLE: 'Is victory impossible, should we focus on the result?',
  387. FIND_COEFF: 'Find the coefficient greater than',
  388. BTN_PASS: 'PASS',
  389. BRAWLS: 'Brawls',
  390. BRAWLS_TITLE: 'Activates the ability to auto-brawl',
  391. START_AUTO_BRAWLS: 'Start Auto Brawls?',
  392. LOSSES: 'Losses',
  393. WINS: 'Wins',
  394. FIGHTS: 'Fights',
  395. STAGE: 'Stage',
  396. DONT_HAVE_LIVES: 'You don\'t have lives',
  397. LIVES: 'Lives',
  398. SECRET_WEALTH_ALREADY: 'Secret Wealth: Item for Pet Potions already purchased',
  399. SECRET_WEALTH_NOT_ENOUGH: 'Secret Wealth: Not Enough Pet Potion, You Have {available}, Need {need}',
  400. SECRET_WEALTH_UPGRADE_NEW_PET: 'Secret Wealth: After purchasing the Pet Potion, it will not be enough to upgrade a new pet',
  401. SECRET_WEALTH_PURCHASED: 'Secret wealth: Purchased {count} {name}',
  402. SECRET_WEALTH_CANCELED: 'Secret Wealth: Purchase Canceled',
  403. SECRET_WEALTH_BUY: 'You have {available} Pet Potion.<br>Do you want to buy {countBuy} {name} for {price} Pet Potion?',
  404. DAILY_BONUS: 'Daily bonus',
  405. DO_DAILY_QUESTS: 'Do daily quests',
  406. ACTIONS: 'Actions',
  407. ACTIONS_TITLE: 'Dialog box with various actions',
  408. OTHERS: 'Others',
  409. OTHERS_TITLE: 'Others',
  410. CHOOSE_ACTION: 'Choose an action',
  411. OPEN_LOOTBOX: 'You have {lootBox} boxes, should we open them?',
  412. STAMINA: 'Energy',
  413. BOXES_OVER: 'The boxes are over',
  414. NO_BOXES: 'No boxes',
  415. NO_MORE_ACTIVITY: 'No more activity for items today',
  416. EXCHANGE_ITEMS: 'Exchange items for activity points (max {maxActive})?',
  417. GET_ACTIVITY: 'Get Activity',
  418. NOT_ENOUGH_ITEMS: 'Not enough items',
  419. ACTIVITY_RECEIVED: 'Activity received',
  420. NO_PURCHASABLE_HERO_SOULS: 'No purchasable Hero Souls',
  421. PURCHASED_HERO_SOULS: 'Purchased {countHeroSouls} Hero Souls',
  422. NOT_ENOUGH_EMERALDS_540: 'Not enough emeralds, you need 540 you have {currentStarMoney}',
  423. CHESTS_NOT_AVAILABLE: 'Chests not available',
  424. OUTLAND_CHESTS_RECEIVED: 'Outland chests received',
  425. RAID_NOT_AVAILABLE: 'The raid is not available or there are no spheres',
  426. RAID_ADVENTURE: 'Raid {adventureId} adventure!',
  427. SOMETHING_WENT_WRONG: 'Something went wrong',
  428. ADVENTURE_COMPLETED: 'Adventure {adventureId} completed {times} times',
  429. CLAN_STAT_COPY: 'Clan statistics copied to clipboard',
  430. GET_ENERGY: 'Get Energy',
  431. GET_ENERGY_TITLE: 'Opens platinum boxes one at a time until you get 250 energy',
  432. ITEM_EXCHANGE: 'Item Exchange',
  433. ITEM_EXCHANGE_TITLE: 'Exchanges items for the specified amount of activity',
  434. BUY_SOULS: 'Buy souls',
  435. BUY_SOULS_TITLE: 'Buy hero souls from all available shops',
  436. BUY_OUTLAND: 'Buy Outland',
  437. BUY_OUTLAND_TITLE: 'Buy 9 chests in Outland for 540 emeralds',
  438. AUTO_RAID_ADVENTURE: 'Raid adventure',
  439. AUTO_RAID_ADVENTURE_TITLE: 'Raid adventure set number of times',
  440. CLAN_STAT: 'Clan statistics',
  441. CLAN_STAT_TITLE: 'Copies clan statistics to the clipboard',
  442. BTN_AUTO_F5: 'Auto (F5)',
  443. BOSS_DAMAGE: 'Boss Damage: ',
  444. NOTHING_BUY: 'Nothing to buy',
  445. LOTS_BOUGHT: '{countBuy} lots bought for gold',
  446. BUY_FOR_GOLD: 'Buy for gold',
  447. BUY_FOR_GOLD_TITLE: 'Buy items for gold in the Town Shop and in the Pet Soul Stone Shop',
  448. REWARDS_AND_MAIL: 'Rewars and Mail',
  449. REWARDS_AND_MAIL_TITLE: 'Collects rewards and mail',
  450. COLLECT_REWARDS_AND_MAIL: 'Collected {countQuests} rewards and {countMail} letters',
  451. TIMER_ALREADY: 'Timer already started',
  452. NO_ATTEMPTS_TIMER_START: 'No attempts, timer started',
  453. EPIC_BRAWL_RESULT: 'Wins: {wins}/{attempts}, Coins: {coins}, Streak: {progress}/{nextStage} [Close]{end}',
  454. ATTEMPT_ENDED: '<br>Attempts ended, timer started',
  455. EPIC_BRAWL: 'Cosmic Battle',
  456. EPIC_BRAWL_TITLE: 'Spends attempts in the Cosmic Battle',
  457. RELOAD_GAME: 'Reload game',
  458. TIMER: 'Timer:',
  459. SHOW_ERRORS: 'Show errors',
  460. SHOW_ERRORS_TITLE: 'Show server request errors',
  461. ERROR_MSG: 'Error: {name}<br>{description}',
  462. },
  463. ru: {
  464. /* Чекбоксы */
  465. SKIP_FIGHTS: 'Пропуск боев',
  466. SKIP_FIGHTS_TITLE: 'Пропуск боев в запределье и арене титанов, автопропуск в башне и кампании',
  467. ENDLESS_CARDS: 'Бесконечные карты',
  468. ENDLESS_CARDS_TITLE: 'Отключить трату карт предсказаний',
  469. AUTO_EXPEDITION: 'АвтоЭкспедиции',
  470. AUTO_EXPEDITION_TITLE: 'Автоотправка экспедиций',
  471. CANCEL_FIGHT: 'Отмена боя',
  472. CANCEL_FIGHT_TITLE: 'Возможность отмены боя на ВГ, СМ и в Асгарде',
  473. GIFTS: 'Подарки',
  474. GIFTS_TITLE: 'Собирать подарки автоматически',
  475. BATTLE_RECALCULATION: 'Прерасчет боя',
  476. BATTLE_RECALCULATION_TITLE: 'Предварительный расчет боя',
  477. BATTLE_FISHING: 'Добивание',
  478. BATTLE_FISHING_TITLE: 'Добивание в чате команды из последнего реплея',
  479. BATTLE_TRENING: 'Тренировка',
  480. BATTLE_TRENING_TITLE: 'Тренировочный бой в чате против команды из последнего реплея',
  481. QUANTITY_CONTROL: 'Контроль кол-ва',
  482. QUANTITY_CONTROL_TITLE: 'Возможность указывать количество открываемых "лутбоксов"',
  483. REPEAT_CAMPAIGN: 'Повтор в компании',
  484. REPEAT_CAMPAIGN_TITLE: 'Автоповтор боев в кампании',
  485. DISABLE_DONAT: 'Отключить донат',
  486. DISABLE_DONAT_TITLE: 'Убирает все предложения доната',
  487. DAILY_QUESTS: 'Квесты',
  488. DAILY_QUESTS_TITLE: 'Выполнять ежедневные квесты',
  489. AUTO_QUIZ: 'АвтоВикторина',
  490. AUTO_QUIZ_TITLE: 'Автоматическое получение правильных ответов на вопросы викторины',
  491. SECRET_WEALTH_CHECKBOX: 'Автоматическая покупка в магазине "Тайное Богатство" при заходе в игру',
  492. /* Поля ввода */
  493. HOW_MUCH_TITANITE: 'Сколько фармим титанита',
  494. COMBAT_SPEED: 'Множитель ускорения боя',
  495. HOW_REPEAT_CAMPAIGN: 'Сколько повторов миссий', //тест добавил
  496. NUMBER_OF_TEST: 'Количество тестовых боев',
  497. NUMBER_OF_AUTO_BATTLE: 'Количество попыток автобоев',
  498. /* Кнопки */
  499. RUN_SCRIPT: 'Запустить скрипт',
  500. STOP_SCRIPT: 'Остановить скрипт',
  501. TO_DO_EVERYTHING: 'Сделать все',
  502. TO_DO_EVERYTHING_TITLE: 'Выполнить несколько действий',
  503. OUTLAND: 'Запределье',
  504. OUTLAND_TITLE: 'Собрать Запределье',
  505. TITAN_ARENA: 'Турнир Стихий',
  506. TITAN_ARENA_TITLE: 'Автопрохождение Турнира Стихий',
  507. DUNGEON: 'Подземелье',
  508. DUNGEON_TITLE: 'Автопрохождение подземелья',
  509. DUNGEON2: 'Подземелье фулл',
  510. DUNGEON_FULL_TITLE: 'Подземелье для фуловых титанов',
  511. STOP_DUNGEON: 'Стоп подземка',
  512. STOP_DUNGEON_TITLE: 'Остановить копание подземелья',
  513. TOWER: 'Башня',
  514. TOWER_TITLE: 'Автопрохождение башни',
  515. EXPEDITIONS: 'Экспедиции',
  516. EXPEDITIONS_TITLE: 'Отправка и сбор экспедиций',
  517. SYNC: 'Синхронизация',
  518. SYNC_TITLE: 'Частичная синхронизация данных игры без перезагрузки страницы',
  519. ARCHDEMON: 'Архидемон',
  520. ARCHDEMON_TITLE: 'Набивает килы и собирает награду',
  521. ESTER_EGGS: 'Пасхалки',
  522. ESTER_EGGS_TITLE: 'Собрать все пасхалки или награды',
  523. REWARDS: 'Награды',
  524. REWARDS_TITLE: 'Собрать все награды за задания',
  525. MAIL: 'Почта',
  526. MAIL_TITLE: 'Собрать всю почту, кроме писем с энергией и зарядами портала',
  527. MINIONS: 'Прислужники',
  528. MINIONS_TITLE: 'Атакует прислужников сохраннеными пачками',
  529. ADVENTURE: 'Приключение',
  530. ADVENTURE_TITLE: 'Проходит приключение по указанному маршруту',
  531. STORM: 'Буря',
  532. STORM_TITLE: 'Проходит бурю по указанному маршруту',
  533. SANCTUARY: 'Святилище',
  534. SANCTUARY_TITLE: 'Быстрый переход к Святилищу',
  535. GUILD_WAR: 'Война гильдий',
  536. GUILD_WAR_TITLE: 'Быстрый переход к Войне гильдий',
  537. SECRET_WEALTH: 'Тайное богатство',
  538. SECRET_WEALTH_TITLE: 'Купить что-то в магазине "Тайное богатство"',
  539. /* Разное */
  540. BOTTOM_URLS: '<a href="https://t.me/+q6gAGCRpwyFkNTYy" target="_blank" title="Telegram"><svg style="margin: 2px;" width="20" height="20" viewBox="0 0 1000 1000" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><defs><linearGradient x1="50%" y1="0%" x2="50%" y2="99.2583404%" id="linearGradient-1"><stop stop-color="#2AABEE" offset="0%"></stop><stop stop-color="#229ED9" offset="100%"></stop></linearGradient></defs><g id="Artboard" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"><circle id="Oval" fill="url(#linearGradient-1)" cx="500" cy="500" r="500"></circle><path d="M226.328419,494.722069 C372.088573,431.216685 469.284839,389.350049 517.917216,369.122161 C656.772535,311.36743 685.625481,301.334815 704.431427,301.003532 C708.567621,300.93067 717.815839,301.955743 723.806446,306.816707 C728.864797,310.92121 730.256552,316.46581 730.922551,320.357329 C731.588551,324.248848 732.417879,333.113828 731.758626,340.040666 C724.234007,419.102486 691.675104,610.964674 675.110982,699.515267 C668.10208,736.984342 654.301336,749.547532 640.940618,750.777006 C611.904684,753.448938 589.856115,731.588035 561.733393,713.153237 C517.726886,684.306416 492.866009,666.349181 450.150074,638.200013 C400.78442,605.66878 432.786119,587.789048 460.919462,558.568563 C468.282091,550.921423 596.21508,434.556479 598.691227,424.000355 C599.00091,422.680135 599.288312,417.758981 596.36474,415.160431 C593.441168,412.561881 589.126229,413.450484 586.012448,414.157198 C581.598758,415.158943 511.297793,461.625274 375.109553,553.556189 C355.154858,567.258623 337.080515,573.934908 320.886524,573.585046 C303.033948,573.199351 268.692754,563.490928 243.163606,555.192408 C211.851067,545.013936 186.964484,539.632504 189.131547,522.346309 C190.260287,513.342589 202.659244,504.134509 226.328419,494.722069 Z" id="Path-3" fill="#FFFFFF"></path></g></svg></a><a href="https://vk.com/invite/YNPxKGX" target="_blank" title="Вконтакте"><svg style="margin: 2px;" width="20" height="20" viewBox="0 0 101 100" fill="none" xmlns="http://www.w3.org/2000/svg"><g clip-path="url(#clip0_2_40)"><path d="M0.5 48C0.5 25.3726 0.5 14.0589 7.52944 7.02944C14.5589 0 25.8726 0 48.5 0H52.5C75.1274 0 86.4411 0 93.4706 7.02944C100.5 14.0589 100.5 25.3726 100.5 48V52C100.5 74.6274 100.5 85.9411 93.4706 92.9706C86.4411 100 75.1274 100 52.5 100H48.5C25.8726 100 14.5589 100 7.52944 92.9706C0.5 85.9411 0.5 74.6274 0.5 52V48Z" fill="#0077FF"/><path d="M53.7085 72.042C30.9168 72.042 17.9169 56.417 17.3752 30.417H28.7919C29.1669 49.5003 37.5834 57.5836 44.25 59.2503V30.417H55.0004V46.8752C61.5837 46.1669 68.4995 38.667 70.8329 30.417H81.5832C79.7915 40.5837 72.2915 48.0836 66.9582 51.1669C72.2915 53.6669 80.8336 60.2086 84.0836 72.042H72.2499C69.7082 64.1253 63.3754 58.0003 55.0004 57.1669V72.042H53.7085Z" fill="white"/></g><defs><clipPath id="clip0_2_40"><rect width="100" height="100" fill="white" transform="translate(0.5)"/></clipPath></defs></svg></a>',
  541. GIFTS_SENT: 'Подарки отправлены!',
  542. DO_YOU_WANT: "Вы действительно хотите это сделать?",
  543. BTN_RUN: 'Запускай',
  544. BTN_CANCEL: 'Отмена',
  545. BTN_OK: 'Ок',
  546. MSG_HAVE_BEEN_DEFEATED: 'Вы потерпели поражение!',
  547. BTN_AUTO: 'Авто',
  548. MSG_YOU_APPLIED: 'Вы нанесли',
  549. MSG_DAMAGE: 'урона',
  550. MSG_CANCEL_AND_STAT: 'Авто (F5) и показать Статистику',
  551. MSG_REPEAT_MISSION: 'Повторить миссию?',
  552. BTN_REPEAT: 'Повторить',
  553. BTN_NO: 'Нет',
  554. MSG_SPECIFY_QUANT: 'Указать количество:',
  555. BTN_OPEN: 'Открыть',
  556. QUESTION_COPY: 'Вопрос скопирован в буфер обмена',
  557. ANSWER_KNOWN: 'Ответ известен',
  558. ANSWER_NOT_KNOWN: 'ВНИМАНИЕ ОТВЕТ НЕ ИЗВЕСТЕН',
  559. BEING_RECALC: 'Идет прерасчет боя',
  560. THIS_TIME: 'На этот раз',
  561. VICTORY: 'ПОБЕДА',
  562. DEFEAT: 'ПОРАЖЕНИЕ',
  563. CHANCE_TO_WIN: 'Шансы на победу',
  564. OPEN_DOLLS: 'матрешек рекурсивно',
  565. SENT_QUESTION: 'Вопрос отправлен',
  566. SETTINGS: 'Настройки',
  567. MSG_BAN_ATTENTION: '<p style="color:red;">Использование этой функции может привести к бану.</p> Продолжить?',
  568. BTN_YES_I_AGREE: 'Да, я беру на себя все риски!',
  569. BTN_NO_I_AM_AGAINST: 'Нет, я отказываюсь от этого!',
  570. VALUES: 'Значения',
  571. SAVING: 'Сохранка',
  572. EXPEDITIONS_SENT: 'Экспедиции отправлены',
  573. TITANIT: 'Титанит',
  574. COMPLETED: 'завершено',
  575. FLOOR: 'Этаж',
  576. LEVEL: 'Уровень',
  577. BATTLES: 'бои',
  578. EVENT: 'Эвент',
  579. NOT_AVAILABLE: 'недоступен',
  580. NO_HEROES: 'Нет героев',
  581. DAMAGE_AMOUNT: 'Количество урона',
  582. NOTHING_TO_COLLECT: 'Нечего собирать',
  583. COLLECTED: 'Собрано',
  584. REWARD: 'наград',
  585. REMAINING_ATTEMPTS: 'Осталось попыток',
  586. BATTLES_CANCELED: 'Битв отменено',
  587. MINION_RAID: 'Рейд прислужников',
  588. STOPPED: 'Остановлено',
  589. REPETITIONS: 'Повторений',
  590. MISSIONS_PASSED: 'Миссий пройдено',
  591. STOP: 'остановить',
  592. TOTAL_OPEN: 'Всего открыто',
  593. OPEN: 'Открыто',
  594. ROUND_STAT: 'Статистика урона за',
  595. BATTLE: 'боев',
  596. MINIMUM: 'Минимальный',
  597. MAXIMUM: 'Максимальный',
  598. AVERAGE: 'Средний',
  599. NOT_THIS_TIME: 'Не в этот раз',
  600. RETRY_LIMIT_EXCEEDED: 'Превышен лимит попыток',
  601. SUCCESS: 'Успех',
  602. RECEIVED: 'Получено',
  603. LETTERS: 'писем',
  604. PORTALS: 'порталов',
  605. ATTEMPTS: 'попыток',
  606. QUEST_10001: 'Улучши умения героев 3 раза',
  607. QUEST_10002: 'Пройди 10 миссий',
  608. QUEST_10003: 'Пройди 3 героические миссии',
  609. QUEST_10004: 'Сразись 3 раза на Арене или Гранд Арене',
  610. QUEST_10006: 'Используй обмен изумрудов 1 раз',
  611. QUEST_10007: 'Соверши 1 призыв в Атриуме Душ',
  612. QUEST_10016: 'Отправь подарки согильдийцам',
  613. QUEST_10018: 'Используй зелье опыта',
  614. QUEST_10019: 'Открой 1 сундук в Башне',
  615. QUEST_10020: 'Открой 3 сундука в Запределье',
  616. QUEST_10021: 'Собери 75 Титанита в Подземелье Гильдии',
  617. QUEST_10021: 'Собери 150 Титанита в Подземелье Гильдии',
  618. QUEST_10023: 'Прокачай Дар Стихий на 1 уровень',
  619. QUEST_10024: 'Повысь уровень любого артефакта один раз',
  620. QUEST_10025: 'Начни 1 Экспедицию',
  621. QUEST_10026: 'Начни 4 Экспедиции',
  622. QUEST_10027: 'Победи в 1 бою Турнира Стихий',
  623. QUEST_10028: 'Повысь уровень любого артефакта титанов',
  624. QUEST_10029: 'Открой сферу артефактов титанов',
  625. QUEST_10030: 'Улучши облик любого героя 1 раз',
  626. QUEST_10031: 'Победи в 6 боях Турнира Стихий',
  627. QUEST_10043: 'Начни или присоединись к Приключению',
  628. QUEST_10044: 'Воспользуйся призывом питомцев 1 раз',
  629. QUEST_10046: 'Открой 3 сундука в Приключениях',
  630. QUEST_10047: 'Набери 150 очков активности в Гильдии',
  631. NOTHING_TO_DO: 'Нечего выполнять',
  632. YOU_CAN_COMPLETE: 'Можно выполнить квесты',
  633. BTN_DO_IT: 'Выполняй',
  634. NOT_QUEST_COMPLETED: 'Ни одного квеста не выполнено',
  635. COMPLETED_QUESTS: 'Выполнено квестов',
  636. /* everything button */
  637. ASSEMBLE_OUTLAND: 'Собрать Запределье',
  638. PASS_THE_TOWER: 'Пройти башню',
  639. CHECK_EXPEDITIONS: 'Проверить экспедиции',
  640. COMPLETE_TOE: 'Пройти Турнир Стихий',
  641. COMPLETE_DUNGEON: 'Пройти подземелье',
  642. COLLECT_MAIL: 'Собрать почту',
  643. COLLECT_MISC: 'Собрать всякую херню',
  644. COLLECT_MISC_TITLE: 'Собрать пасхалки, камни облика, ключи, монеты арены и Хрусталь души',
  645. COLLECT_QUEST_REWARDS: 'Собрать награды за квесты',
  646. MAKE_A_SYNC: 'Сделать синхронизацию',
  647.  
  648. RUN_FUNCTION: 'Выполнить следующие функции?',
  649. BTN_GO: 'Погнали!',
  650. PERFORMED: 'Выполняется',
  651. DONE: 'Выполнено',
  652. ERRORS_OCCURRES: 'Призошли ошибки при выполнении',
  653. COPY_ERROR: 'Скопировать в буфер информацию об ошибке',
  654. BTN_YES: 'Да',
  655. ALL_TASK_COMPLETED: 'Все задачи выполнены',
  656.  
  657. UNKNOWN: 'Неизвестно',
  658. ENTER_THE_PATH: 'Введите путь приключения через запятые или дефисы',
  659. START_ADVENTURE: 'Начать приключение по этому пути!',
  660. BTN_CANCELED: 'Отменено',
  661. MUST_TWO_POINTS: 'Путь должен состоять минимум из 2х точек',
  662. MUST_ONLY_NUMBERS: 'Путь должен содержать только цифры и запятые',
  663. NOT_ON_AN_ADVENTURE: 'Вы не в приключении',
  664. YOU_IN_NOT_ON_THE_WAY: 'Указанный путь должен включать точку вашего положения',
  665. ATTEMPTS_NOT_ENOUGH: 'Ваших попыток не достаточно для завершения пути, продолжить?',
  666. YES_CONTINUE: 'Да, продолжай!',
  667. NOT_ENOUGH_AP: 'Попыток не достаточно',
  668. ATTEMPTS_ARE_OVER: 'Попытки закончились',
  669. MOVES: 'Ходы',
  670. BUFF_GET_ERROR: 'Ошибка при получении бафа',
  671. BATTLE_END_ERROR: 'Ошибка завершения боя',
  672. AUTOBOT: 'АвтоБой',
  673. FAILED_TO_WIN_AUTO: 'Не удалось победить в автобою',
  674. ERROR_OF_THE_BATTLE_COPY: 'Призошли ошибка в процессе прохождения боя<br>Скопировать ошибку в буфер обмена?',
  675. ERROR_DURING_THE_BATTLE: 'Ошибка в процессе прохождения боя',
  676. NO_CHANCE_WIN: 'Нет шансов победить в этом бою: 0/',
  677. LOST_HEROES: 'Вы победили, но потеряли одного или несколько героев!',
  678. VICTORY_IMPOSSIBLE: 'Победа не возможна, бъем на результат?',
  679. FIND_COEFF: 'Поиск коэффициента больше чем',
  680. BTN_PASS: 'ПРОПУСК',
  681. BRAWLS: 'Потасовки',
  682. BRAWLS_TITLE: 'Включает возможность автопотасовок',
  683. START_AUTO_BRAWLS: 'Запустить Автопотасовки?',
  684. LOSSES: 'Поражений',
  685. WINS: 'Побед',
  686. FIGHTS: 'Боев',
  687. STAGE: 'Стадия',
  688. DONT_HAVE_LIVES: 'У Вас нет жизней',
  689. LIVES: 'Жизни',
  690. SECRET_WEALTH_ALREADY: 'Тайное богатство: товар за Зелья питомцев уже куплен',
  691. SECRET_WEALTH_NOT_ENOUGH: 'Тайное богатство: Не достаточно Зелье Питомца, у Вас {available}, нужно {need}',
  692. SECRET_WEALTH_UPGRADE_NEW_PET: 'Тайное богатство: После покупки Зелье Питомца будет не достаточно для прокачки нового питомца',
  693. SECRET_WEALTH_PURCHASED: 'Тайное богатство: Куплено {count} {name}',
  694. SECRET_WEALTH_CANCELED: 'Тайное богатство: покупка отменена',
  695. SECRET_WEALTH_BUY: 'У вас {available} Зелье Питомца.<br>Вы хотите купить {countBuy} {name} за {price} Зелье Питомца?',
  696. DAILY_BONUS: 'Ежедневная награда',
  697. DO_DAILY_QUESTS: 'Сделать ежедневные квесты',
  698. ACTIONS: 'Действия',
  699. ACTIONS_TITLE: 'Диалоговое окно с различными действиями',
  700. OTHERS: 'Разное',
  701. OTHERS_TITLE: 'Диалоговое окно с дополнительными различными действиями',
  702. CHOOSE_ACTION: 'Выберите действие',
  703. OPEN_LOOTBOX: 'У Вас {lootBox} ящиков, открываем?',
  704. STAMINA: 'Энергия',
  705. BOXES_OVER: 'Ящики закончились',
  706. NO_BOXES: 'Нет ящиков',
  707. NO_MORE_ACTIVITY: 'Больше активности за предметы сегодня не получить',
  708. EXCHANGE_ITEMS: 'Обменять предметы на очки активности (не более {maxActive})?',
  709. GET_ACTIVITY: 'Получить активность',
  710. NOT_ENOUGH_ITEMS: 'Предметов недостаточно',
  711. ACTIVITY_RECEIVED: 'Получено активности',
  712. NO_PURCHASABLE_HERO_SOULS: 'Нет доступных для покупки душ героев',
  713. PURCHASED_HERO_SOULS: 'Куплено {countHeroSouls} душ героев',
  714. NOT_ENOUGH_EMERALDS_540: 'Недостаточно изюма, нужно 540 у Вас {currentStarMoney}',
  715. CHESTS_NOT_AVAILABLE: 'Сундуки не доступны',
  716. OUTLAND_CHESTS_RECEIVED: 'Получено сундуков Запределья',
  717. RAID_NOT_AVAILABLE: 'Рейд не доступен или сфер нет',
  718. RAID_ADVENTURE: 'Рейд {adventureId} приключения!',
  719. SOMETHING_WENT_WRONG: 'Что-то пошло не так',
  720. ADVENTURE_COMPLETED: 'Приключение {adventureId} пройдено {times} раз',
  721. CLAN_STAT_COPY: 'Клановая статистика скопирована в буфер обмена',
  722. GET_ENERGY: 'Получить энергию',
  723. GET_ENERGY_TITLE: 'Открывает платиновые шкатулки по одной до получения 250 энергии',
  724. ITEM_EXCHANGE: 'Обмен предметов',
  725. ITEM_EXCHANGE_TITLE: 'Обменивает предметы на указанное количество активности',
  726. BUY_SOULS: 'Купить души',
  727. BUY_SOULS_TITLE: 'Купить души героев из всех доступных магазинов',
  728. BUY_OUTLAND: 'Купить Запределье',
  729. BUY_OUTLAND_TITLE: 'Купить 9 сундуков в Запределье за 540 изумрудов',
  730. AUTO_RAID_ADVENTURE: 'Рейд приключения',
  731. AUTO_RAID_ADVENTURE_TITLE: 'Рейд приключения заданное количество раз',
  732. CLAN_STAT: 'Клановая статистика',
  733. CLAN_STAT_TITLE: 'Копирует клановую статистику в буфер обмена',
  734. BTN_AUTO_F5: 'Авто (F5)',
  735. BOSS_DAMAGE: 'Урон по боссу: ',
  736. NOTHING_BUY: 'Нечего покупать',
  737. LOTS_BOUGHT: 'За золото куплено {countBuy} лотов',
  738. BUY_FOR_GOLD: 'Скупить за золото',
  739. BUY_FOR_GOLD_TITLE: 'Скупить предметы за золото в Городской лавке и в магазине Камней Душ Питомцев',
  740. REWARDS_AND_MAIL: 'Награды и почта',
  741. REWARDS_AND_MAIL_TITLE: 'Собирает награды и почту',
  742. COLLECT_REWARDS_AND_MAIL: 'Собрано {countQuests} наград и {countMail} писем',
  743. TIMER_ALREADY: 'Таймер уже запущен',
  744. NO_ATTEMPTS_TIMER_START: 'Попыток нет, запущен таймер',
  745. EPIC_BRAWL_RESULT: '{i} Победы: {wins}/{attempts}, Монеты: {coins}, Серия: {progress}/{nextStage} [Закрыть]{end}',
  746. ATTEMPT_ENDED: '<br>Попытки закончились, запущен таймер',
  747. EPIC_BRAWL: 'Вселенская битва',
  748. EPIC_BRAWL_TITLE: 'Тратит попытки во Вселенской битве',
  749. RELOAD_GAME: 'Перезагрузить игру',
  750. TIMER: 'Таймер:',
  751. SHOW_ERRORS: 'Отображать ошибки',
  752. SHOW_ERRORS_TITLE: 'Отображать ошибки запросов к серверу',
  753. ERROR_MSG: 'Ошибка: {name}<br>{description}',
  754. }
  755. }
  756.  
  757. function getLang() {
  758. let lang = '';
  759. if (typeof NXFlashVars !== 'undefined') {
  760. lang = NXFlashVars.interface_lang
  761. }
  762. if (!lang) {
  763. lang = (navigator.language || navigator.userLanguage).substr(0, 2);
  764. }
  765. if (lang == 'ru') {
  766. return lang;
  767. }
  768. return 'en';
  769. }
  770.  
  771. this.I18N = function (constant, replace) {
  772. const selectLang = getLang();
  773. if (constant && constant in i18nLangData[selectLang]) {
  774. const result = i18nLangData[selectLang][constant];
  775. if (replace) {
  776. return result.sprintf(replace);
  777. }
  778. return result;
  779. }
  780. return `% ${constant} %`;
  781. };
  782.  
  783. String.prototype.sprintf = String.prototype.sprintf ||
  784. function () {
  785. "use strict";
  786. var str = this.toString();
  787. if (arguments.length) {
  788. var t = typeof arguments[0];
  789. var key;
  790. var args = ("string" === t || "number" === t) ?
  791. Array.prototype.slice.call(arguments)
  792. : arguments[0];
  793.  
  794. for (key in args) {
  795. str = str.replace(new RegExp("\\{" + key + "\\}", "gi"), args[key]);
  796. }
  797. }
  798.  
  799. return str;
  800. };
  801.  
  802. /**
  803. * Checkboxes
  804. *
  805. * Чекбоксы
  806. */
  807. const checkboxes = {
  808. passBattle: {
  809. label: I18N('SKIP_FIGHTS'),
  810. cbox: null,
  811. title: I18N('SKIP_FIGHTS_TITLE'),
  812. default: false
  813. },
  814. /*endlessCards: {
  815. label: I18N('ENDLESS_CARDS'),
  816. cbox: null,
  817. title: I18N('ENDLESS_CARDS_TITLE'),
  818. default: true
  819. },*/
  820. /*sendExpedition: {
  821. label: I18N('AUTO_EXPEDITION'),
  822. cbox: null,
  823. title: I18N('AUTO_EXPEDITION_TITLE'),
  824. default: true
  825. },*/
  826. cancelBattle: {
  827. label: I18N('CANCEL_FIGHT'),
  828. cbox: null,
  829. title: I18N('CANCEL_FIGHT_TITLE'),
  830. default: false,
  831. },
  832. preCalcBattle: {
  833. label: I18N('BATTLE_RECALCULATION'),
  834. cbox: null,
  835. title: I18N('BATTLE_RECALCULATION_TITLE'),
  836. default: false
  837. },
  838. finishingBattle: {
  839. label: I18N('BATTLE_FISHING'),
  840. cbox: null,
  841. title: I18N('BATTLE_FISHING_TITLE'),
  842. default: false
  843. },
  844. treningBattle: {
  845. label: I18N('BATTLE_TRENING'),
  846. cbox: null,
  847. title: I18N('BATTLE_TRENING_TITLE'),
  848. default: false
  849. },
  850. countControl: {
  851. label: I18N('QUANTITY_CONTROL'),
  852. cbox: null,
  853. title: I18N('QUANTITY_CONTROL_TITLE'),
  854. default: true
  855. },
  856. isRepeatMission: {
  857. label: I18N('REPEAT_CAMPAIGN'),
  858. cbox: null,
  859. title: I18N('REPEAT_CAMPAIGN_TITLE'),
  860. default: false
  861. },
  862. noOfferDonat: {
  863. label: I18N('DISABLE_DONAT'),
  864. cbox: null,
  865. title: I18N('DISABLE_DONAT_TITLE'),
  866. /**
  867. * A crutch to get the field before getting the character id
  868. *
  869. * Костыль чтоб получать поле до получения id персонажа
  870. */
  871. default: (() => {
  872. $result = false;
  873. try {
  874. $result = JSON.parse(localStorage[GM_info.script.name + ':noOfferDonat'])
  875. } catch(e) {
  876. $result = false;
  877. }
  878. return $result || false;
  879. })(),
  880. },
  881. dailyQuests: {
  882. label: I18N('DAILY_QUESTS'),
  883. cbox: null,
  884. title: I18N('DAILY_QUESTS_TITLE'),
  885. default: false
  886. },
  887. secretWealth: {
  888. label: I18N('SECRET_WEALTH'),
  889. cbox: null,
  890. title: I18N('SECRET_WEALTH_CHECKBOX'),
  891. default: false
  892. },
  893. /*
  894. autoBrawls: {
  895. label: I18N('BRAWLS'),
  896. cbox: null,
  897. title: I18N('BRAWLS_TITLE'),
  898. default: (() => {
  899. $result = false;
  900. try {
  901. $result = JSON.parse(localStorage[GM_info.script.name + ':autoBrawls'])
  902. } catch (e) {
  903. $result = false;
  904. }
  905. return $result || false;
  906. })(),
  907. },*/
  908. /*
  909. getAnswer: {
  910. label: I18N('AUTO_QUIZ'),
  911. cbox: null,
  912. title: I18N('AUTO_QUIZ_TITLE'),
  913. default: false
  914. },
  915. */
  916. /*showErrors: {
  917. label: I18N('SHOW_ERRORS'),
  918. cbox: null,
  919. title: I18N('SHOW_ERRORS_TITLE'),
  920. default: true
  921. },*/
  922. buyForGold: {
  923. label: I18N('BUY_FOR_GOLD'),
  924. cbox: null,
  925. title: I18N('BUY_FOR_GOLD_TITLE'),
  926. default: false
  927. },
  928. };
  929. /**
  930. * Get checkbox state
  931. *
  932. * Получить состояние чекбокса
  933. */
  934. function isChecked(checkBox) {
  935. if (!(checkBox in checkboxes)) {
  936. return false;
  937. }
  938. return checkboxes[checkBox].cbox?.checked;
  939. }
  940. /**
  941. * Input fields
  942. *
  943. * Поля ввода
  944. */
  945. const inputs = {
  946. countTitanit: {
  947. input: null,
  948. title: I18N('HOW_MUCH_TITANITE'),
  949. default: 150,
  950. },
  951. speedBattle: {
  952. input: null,
  953. title: I18N('COMBAT_SPEED'),
  954. default: 5,
  955. },
  956. //тест
  957. countRaid: {
  958. input: null,
  959. title: I18N('HOW_REPEAT_CAMPAIGN'),
  960. default: 5,
  961. },
  962. countTestBattle: {
  963. input: null,
  964. title: I18N('NUMBER_OF_TEST'),
  965. default: 10,
  966. },
  967. countAutoBattle: {
  968. input: null,
  969. title: I18N('NUMBER_OF_AUTO_BATTLE'),
  970. default: 10,
  971. }
  972. }
  973. //сохранка тест
  974. const inputs2 = {
  975. countBattle: {
  976. input: null,
  977. title: '-1 сохраняет защиту, -2 атаку противника с Replay',
  978. default: 1,
  979. },
  980. needResource: {
  981. input: null,
  982. title: 'Мощь противника мин.(тыс.)/урона(млн.)',
  983. default: 300,
  984. },
  985. needResource2: {
  986. input: null,
  987. title: 'Мощь противника макс./тип бафа',
  988. default: 1500,
  989. },
  990. }
  991. /**
  992. * Checks the checkbox
  993. *
  994. * Получить данные поля ввода
  995. */
  996. /*function getInput(inputName) {
  997. return inputs[inputName].input.value;
  998. }*/
  999. function getInput(inputName) {
  1000. if(inputs[inputName]) {return inputs[inputName].input.value;}
  1001. else if(inputs2[inputName]) {return inputs2[inputName].input.value;}
  1002. else return null
  1003. }
  1004. //тест рейд
  1005. /** Автоповтор миссии */
  1006. let isRepeatMission = false;
  1007. /** Вкл/Выкл автоповтор миссии */
  1008. this.switchRepeatMission = function() {
  1009. isRepeatMission = !isRepeatMission;
  1010. console.log(isRepeatMission);
  1011. }
  1012. //тест стоп
  1013. /**
  1014. * Button List
  1015. *
  1016. * Список кнопочек
  1017. */
  1018. const buttons = {
  1019. getOutland: {
  1020. name: I18N('TO_DO_EVERYTHING'),
  1021. title: I18N('TO_DO_EVERYTHING_TITLE'),
  1022. func: testDoYourBest,
  1023. },
  1024. /*
  1025. doActions: {
  1026. name: I18N('ACTIONS'),
  1027. title: I18N('ACTIONS_TITLE'),
  1028. func: async function () {
  1029. const popupButtons = [
  1030. {
  1031. msg: I18N('OUTLAND'),
  1032. result: function () {
  1033. confShow(`${I18N('RUN_SCRIPT')} ${I18N('OUTLAND')}?`, getOutland);
  1034. },
  1035. title: I18N('OUTLAND_TITLE'),
  1036. },
  1037. {
  1038. msg: I18N('TOWER'),
  1039. result: function () {
  1040. confShow(`${I18N('RUN_SCRIPT')} ${I18N('TOWER')}?`, testTower);
  1041. },
  1042. title: I18N('TOWER_TITLE'),
  1043. },
  1044. {
  1045. msg: I18N('EXPEDITIONS'),
  1046. result: function () {
  1047. confShow(`${I18N('RUN_SCRIPT')} ${I18N('EXPEDITIONS')}?`, checkExpedition);
  1048. },
  1049. title: I18N('EXPEDITIONS_TITLE'),
  1050. },
  1051. {
  1052. msg: I18N('MINIONS'),
  1053. result: function () {
  1054. confShow(`${I18N('RUN_SCRIPT')} ${I18N('MINIONS')}?`, testRaidNodes);
  1055. },
  1056. title: I18N('MINIONS_TITLE'),
  1057. },
  1058. {
  1059. msg: I18N('ESTER_EGGS'),
  1060. result: function () {
  1061. confShow(`${I18N('RUN_SCRIPT')} ${I18N('ESTER_EGGS')}?`, offerFarmAllReward);
  1062. },
  1063. title: I18N('ESTER_EGGS_TITLE'),
  1064. },
  1065. {
  1066. msg: I18N('STORM'),
  1067. result: function () {
  1068. testAdventure('solo');
  1069. },
  1070. title: I18N('STORM_TITLE'),
  1071. },
  1072. {
  1073. msg: I18N('REWARDS'),
  1074. result: function () {
  1075. confShow(`${I18N('RUN_SCRIPT')} ${I18N('REWARDS')}?`, questAllFarm);
  1076. },
  1077. title: I18N('REWARDS_TITLE'),
  1078. },
  1079. {
  1080. msg: I18N('MAIL'),
  1081. result: function () {
  1082. confShow(`${I18N('RUN_SCRIPT')} ${I18N('MAIL')}?`, mailGetAll);
  1083. },
  1084. title: I18N('MAIL_TITLE'),
  1085. },
  1086. ];
  1087. popupButtons.push({ result: false, isClose: true })
  1088. const answer = await popup.confirm(`${I18N('CHOOSE_ACTION')}:`, popupButtons);
  1089. if (typeof answer === 'function') {
  1090. answer();
  1091. }
  1092. }
  1093. },
  1094. doOthers: {
  1095. name: I18N('OTHERS'),
  1096. title: I18N('OTHERS_TITLE'),
  1097. func: async function () {
  1098. const popupButtons = [
  1099. {
  1100. msg: I18N('GET_ENERGY'),
  1101. result: farmStamina,
  1102. title: I18N('GET_ENERGY_TITLE'),
  1103. },
  1104. {
  1105. msg: I18N('ITEM_EXCHANGE'),
  1106. result: fillActive,
  1107. title: I18N('ITEM_EXCHANGE_TITLE'),
  1108. },
  1109. {
  1110. msg: I18N('BUY_SOULS'),
  1111. result: function () {
  1112. confShow(`${I18N('RUN_SCRIPT')} ${I18N('BUY_SOULS')}?`, buyHeroFragments);
  1113. },
  1114. title: I18N('BUY_SOULS_TITLE'),
  1115. },
  1116. {
  1117. msg: I18N('BUY_FOR_GOLD'),
  1118. result: function () {
  1119. confShow(`${I18N('RUN_SCRIPT')} ${I18N('BUY_FOR_GOLD')}?`, buyInStoreForGold);
  1120. },
  1121. title: I18N('BUY_FOR_GOLD_TITLE'),
  1122. },
  1123. {
  1124. msg: I18N('BUY_OUTLAND'),
  1125. result: function () {
  1126. confShow(I18N('BUY_OUTLAND_TITLE') + '?', bossOpenChestPay);
  1127. },
  1128. title: I18N('BUY_OUTLAND_TITLE'),
  1129. },
  1130. {
  1131. msg: I18N('AUTO_RAID_ADVENTURE'),
  1132. result: autoRaidAdventure,
  1133. title: I18N('AUTO_RAID_ADVENTURE_TITLE'),
  1134. },
  1135. {
  1136. msg: I18N('CLAN_STAT'),
  1137. result: clanStatistic,
  1138. title: I18N('CLAN_STAT_TITLE'),
  1139. },
  1140. {
  1141. msg: I18N('SECRET_WEALTH'),
  1142. result: buyWithPetExperience,
  1143. title: I18N('SECRET_WEALTH_TITLE'),
  1144. },
  1145. {
  1146. msg: I18N('EPIC_BRAWL'),
  1147. result: async function () {
  1148. confShow(`${I18N('RUN_SCRIPT')} ${I18N('EPIC_BRAWL')}?`, () => {
  1149. const brawl = new epicBrawl;
  1150. brawl.start();
  1151. });
  1152. },
  1153. title: I18N('EPIC_BRAWL_TITLE'),
  1154. },
  1155. ];
  1156. popupButtons.push({ result: false, isClose: true })
  1157. const answer = await popup.confirm(`${I18N('CHOOSE_ACTION')}:`, popupButtons);
  1158. if (typeof answer === 'function') {
  1159. answer();
  1160. }
  1161. }
  1162. },*/
  1163. testTitanArena: {
  1164. name: I18N('TITAN_ARENA'),
  1165. title: I18N('TITAN_ARENA_TITLE'),
  1166. func: function () {
  1167. confShow(`${I18N('RUN_SCRIPT')} ${I18N('TITAN_ARENA')}?`, testTitanArena);
  1168. },
  1169. },
  1170. testDungeon: {
  1171. name: I18N('DUNGEON'),
  1172. title: I18N('DUNGEON_TITLE'),
  1173. func: function () {
  1174. confShow(`${I18N('RUN_SCRIPT')} ${I18N('DUNGEON')}?`, testDungeon);
  1175. },
  1176. },
  1177. //тест подземка 2
  1178. DungeonFull: {
  1179. name: I18N('DUNGEON2'),
  1180. title: I18N('DUNGEON_FULL_TITLE'),
  1181. func: function () {
  1182. confShow(`${I18N('RUN_SCRIPT')} ${I18N('DUNGEON_FULL_TITLE')}?`, DungeonFull);
  1183. },
  1184. },
  1185. //остановить подземелье
  1186. stopDungeon: {
  1187. name: I18N('STOP_DUNGEON'),
  1188. title: I18N('STOP_DUNGEON_TITLE'),
  1189. func: function () {
  1190. confShow(`${I18N('STOP_SCRIPT')} ${I18N('STOP_DUNGEON_TITLE')}?`, stopDungeon);
  1191. },
  1192. },
  1193. // Башня
  1194. testTower: {
  1195. name: I18N('TOWER'),
  1196. title: I18N('TOWER_TITLE'),
  1197. func: function () {
  1198. confShow(`${I18N('RUN_SCRIPT')} ${I18N('TOWER')}?`, testTower);
  1199. },
  1200. },
  1201. /*
  1202. bossRatingEvent: {
  1203. name: I18N('ARCHDEMON'),
  1204. title: I18N('ARCHDEMON_TITLE'),
  1205. func: function () {
  1206. confShow(`${I18N('RUN_SCRIPT')} ${I18N('ARCHDEMON')}?`, bossRatingEvent);
  1207. },
  1208. },
  1209. */
  1210. rewardsAndMailFarm: {
  1211. name: I18N('REWARDS_AND_MAIL'),
  1212. title: I18N('REWARDS_AND_MAIL_TITLE'),
  1213. func: function () {
  1214. confShow(`${I18N('RUN_SCRIPT')} ${I18N('REWARDS_AND_MAIL')}?`, rewardsAndMailFarm);
  1215. },
  1216. },
  1217. //прислужники
  1218. testRaidNodes: {
  1219. name: I18N('MINIONS'),
  1220. title: I18N('MINIONS_TITLE'),
  1221. func: function () {
  1222. confShow(`${I18N('RUN_SCRIPT')} ${I18N('MINIONS')}?`, testRaidNodes);
  1223. },
  1224. },
  1225. //приключения
  1226. testAdventure: {
  1227. name: I18N('ADVENTURE'),
  1228. title: I18N('ADVENTURE_TITLE'),
  1229. func: () => {
  1230. testAdventure();
  1231. },
  1232. },
  1233. goToSanctuary: {
  1234. name: I18N('SANCTUARY'),
  1235. title: I18N('SANCTUARY_TITLE'),
  1236. func: cheats.goSanctuary,
  1237. },
  1238. goToClanWar: {
  1239. name: I18N('GUILD_WAR'),
  1240. title: I18N('GUILD_WAR_TITLE'),
  1241. func: cheats.goClanWar,
  1242. },
  1243. dailyQuests: {
  1244. name: I18N('DAILY_QUESTS'),
  1245. title: I18N('DAILY_QUESTS_TITLE'),
  1246. func: async function () {
  1247. const quests = new dailyQuests(() => { }, () => { });
  1248. await quests.autoInit();
  1249. quests.start();
  1250. },
  1251. },
  1252. newDay: {
  1253. name: I18N('SYNC'),
  1254. title: I18N('SYNC_TITLE'),
  1255. func: function () {
  1256. confShow(`${I18N('RUN_SCRIPT')} ${I18N('SYNC')}?`, cheats.refreshGame);
  1257. },
  1258. },
  1259. }
  1260. /**
  1261. * Display buttons
  1262. *
  1263. * Вывести кнопочки
  1264. */
  1265. function addControlButtons() {
  1266. for (let name in buttons) {
  1267. button = buttons[name];
  1268. button['button'] = scriptMenu.addButton(button.name, button.func, button.title);
  1269. }
  1270. }
  1271. /**
  1272. * Adds links
  1273. *
  1274. * Добавляет ссылки
  1275. */
  1276. function addBottomUrls() {
  1277. scriptMenu.addHeader(I18N('BOTTOM_URLS'));
  1278. }
  1279. /**
  1280. * Stop repetition of the mission
  1281. *
  1282. * Остановить повтор миссии
  1283. */
  1284. let isStopSendMission = false;
  1285. /**
  1286. * There is a repetition of the mission
  1287. *
  1288. * Идет повтор миссии
  1289. */
  1290. let isSendsMission = false;
  1291. /**
  1292. * Data on the past mission
  1293. *
  1294. * Данные о прошедшей мисии
  1295. */
  1296. let lastMissionStart = {}
  1297.  
  1298. /**
  1299. * Data on the past attack on the boss
  1300. *
  1301. * Данные о прошедшей атаке на босса
  1302. */
  1303. let lastBossBattle = {}
  1304. /**
  1305. * Data for calculating the last battle with the boss
  1306. *
  1307. * Данные для расчете последнего боя с боссом
  1308. */
  1309. let lastBossBattleInfo = null;
  1310. /**
  1311. * Ability to cancel the battle in Asgard
  1312. *
  1313. * Возможность отменить бой в Астгарде
  1314. */
  1315. let isCancalBossBattle = true;
  1316. /**
  1317. * Information about the last battle
  1318. *
  1319. * Данные о прошедшей битве
  1320. */
  1321. let lastBattleArg = {}
  1322. /**
  1323. * The name of the function of the beginning of the battle
  1324. *
  1325. * Имя функции начала боя
  1326. */
  1327. let nameFuncStartBattle = '';
  1328. /**
  1329. * The name of the function of the end of the battle
  1330. *
  1331. * Имя функции конца боя
  1332. */
  1333. let nameFuncEndBattle = '';
  1334. /**
  1335. * Data for calculating the last battle
  1336. *
  1337. * Данные для расчета последнего боя
  1338. */
  1339. let lastBattleInfo = null;
  1340. /**
  1341. * The ability to cancel the battle
  1342. *
  1343. * Возможность отменить бой
  1344. */
  1345. let isCancalBattle = true;
  1346.  
  1347. /**
  1348. * Certificator of the last open nesting doll
  1349. *
  1350. * Идетификатор последней открытой матрешки
  1351. */
  1352. let lastRussianDollId = null;
  1353. /**
  1354. * Cancel the training guide
  1355. *
  1356. * Отменить обучающее руководство
  1357. */
  1358. this.isCanceledTutorial = false;
  1359.  
  1360. /**
  1361. * Data from the last question of the quiz
  1362. *
  1363. * Данные последнего вопроса викторины
  1364. */
  1365. let lastQuestion = null;
  1366. /**
  1367. * Answer to the last question of the quiz
  1368. *
  1369. * Ответ на последний вопрос викторины
  1370. */
  1371. let lastAnswer = null;
  1372. /**
  1373. * Flag for opening keys or titan artifact spheres
  1374. *
  1375. * Флаг открытия ключей или сфер артефактов титанов
  1376. */
  1377. let artifactChestOpen = false;
  1378. /**
  1379. * The name of the function to open keys or orbs of titan artifacts
  1380. *
  1381. * Имя функции открытия ключей или сфер артефактов титанов
  1382. */
  1383. let artifactChestOpenCallName = '';
  1384. /**
  1385. * Data for the last battle in the dungeon
  1386. * (Fix endless cards)
  1387. *
  1388. * Данные для последнего боя в подземке
  1389. * (Исправление бесконечных карт)
  1390. */
  1391. let lastDungeonBattleData = null;
  1392. /**
  1393. * Start time of the last battle in the dungeon
  1394. *
  1395. * Время начала последнего боя в подземелье
  1396. */
  1397. let lastDungeonBattleStart = 0;
  1398. /**
  1399. * Subscription end time
  1400. *
  1401. * Время окончания подписки
  1402. */
  1403. let subEndTime = 0;
  1404. /**
  1405. * Number of prediction cards
  1406. *
  1407. * Количество карт предсказаний
  1408. */
  1409. let countPredictionCard = 0;
  1410.  
  1411. /**
  1412. * Brawl pack
  1413. *
  1414. * Пачка для потасовок
  1415. */
  1416. let brawlsPack = null;
  1417. /**
  1418. * Autobrawl started
  1419. *
  1420. * Автопотасовка запущена
  1421. */
  1422. let isBrawlsAutoStart = false;
  1423. /**
  1424. * Timer divider
  1425. *
  1426. * Делитель таймера
  1427. */
  1428. this.timerDiv = 1.5; //подземка динамический таймер
  1429. /**
  1430. * Copies the text to the clipboard
  1431. *
  1432. * Копирует тест в буфер обмена
  1433. * @param {*} text copied text // копируемый текст
  1434. */
  1435. function copyText(text) {
  1436. let copyTextarea = document.createElement("textarea");
  1437. copyTextarea.style.opacity = "0";
  1438. copyTextarea.textContent = text;
  1439. document.body.appendChild(copyTextarea);
  1440. copyTextarea.select();
  1441. document.execCommand("copy");
  1442. document.body.removeChild(copyTextarea);
  1443. delete copyTextarea;
  1444. }
  1445. /**
  1446. * Returns the history of requests
  1447. *
  1448. * Возвращает историю запросов
  1449. */
  1450. this.getRequestHistory = function() {
  1451. return requestHistory;
  1452. }
  1453. /**
  1454. * Generates a random integer from min to max
  1455. *
  1456. * Гененирует случайное целое число от min до max
  1457. */
  1458. const random = function (min, max) {
  1459. return Math.floor(Math.random() * (max - min + 1) + min);
  1460. }
  1461. //тест подземка гудвин
  1462. Number.prototype.round = function(places) {
  1463. return +(Math.round(this + "e+" + places) + "e-" + places);
  1464. }
  1465. String.prototype.fixed = function(length) {
  1466. return this.length < length ? this + ' '.repeat(2 * (length - this.length)): this ;
  1467. }
  1468. /**
  1469. * Clearing the request history
  1470. *
  1471. * Очистка истоии запросов
  1472. */
  1473. setInterval(function () {
  1474. let now = Date.now();
  1475. for (let i in requestHistory) {
  1476. if (now - i > 300000) {
  1477. delete requestHistory[i];
  1478. }
  1479. }
  1480. }, 300000);
  1481. /**
  1482. * DOM Loading Event page
  1483. *
  1484. * Событие загрузки DOM дерева страницы
  1485. */
  1486. document.addEventListener("DOMContentLoaded", () => {
  1487. /**
  1488. * Create the script interface
  1489. *
  1490. * Создание интерфеса скрипта
  1491. */
  1492. createInterface();
  1493. });
  1494. /**
  1495. * Gift codes collecting and sending codes
  1496. *
  1497. * Сбор и отправка кодов подарков
  1498. */
  1499. function sendCodes() {
  1500. let codes = [], count = 0;
  1501. if (!localStorage['giftSendIds']) {
  1502. localStorage['giftSendIds'] = '';
  1503. }
  1504. document.querySelectorAll('a[target="_blank"]').forEach(e => {
  1505. let url = e?.href;
  1506. if (!url) return;
  1507. url = new URL(url);
  1508. let giftId = url.searchParams.get('gift_id');
  1509. if (!giftId || localStorage['giftSendIds'].includes(giftId)) return;
  1510. localStorage['giftSendIds'] += ';' + giftId;
  1511. codes.push(giftId);
  1512. count++;
  1513. });
  1514.  
  1515. if (codes.length) {
  1516. localStorage['giftSendIds'] = localStorage['giftSendIds'].split(';').splice(-50).join(';');
  1517. sendGiftsCodes(codes);
  1518. }
  1519.  
  1520. if (!count) {
  1521. setTimeout(sendCodes, 2000);
  1522. }
  1523. }
  1524. /**
  1525. * Checking sent codes
  1526. *
  1527. * Проверка отправленных кодов
  1528. */
  1529. function checkSendGifts() {
  1530. if (!freebieCheckInfo) {
  1531. return;
  1532. }
  1533.  
  1534. let giftId = freebieCheckInfo.args.giftId;
  1535. let valName = 'giftSendIds_' + userInfo.id;
  1536. localStorage[valName] = localStorage[valName] ?? '';
  1537. if (!localStorage[valName].includes(giftId)) {
  1538. localStorage[valName] += ';' + giftId;
  1539. sendGiftsCodes([giftId]);
  1540. }
  1541. }
  1542. /**
  1543. * Sending codes
  1544. *
  1545. * Отправка кодов
  1546. */
  1547. function sendGiftsCodes(codes) {
  1548. fetch('https://zingery.ru/heroes/setGifts.php', {
  1549. method: 'POST',
  1550. body: JSON.stringify(codes)
  1551. }).then(
  1552. response => response.json()
  1553. ).then(
  1554. data => {
  1555. if (data.result) {
  1556. console.log(I18N('GIFTS_SENT'));
  1557. }
  1558. }
  1559. )
  1560. }
  1561. /** тест убрано Возвращает объект если переданный парамет строка */
  1562. //тест гудвин хз надо ли
  1563. /** Возвращает объект если переданный парамет строка */
  1564. function getJson(result) {
  1565. if (typeof result == 'string') {
  1566. result = JSON.parse(result);
  1567. }
  1568. if (result?.error) {
  1569. console.warn(result.error);
  1570. return false;
  1571. }
  1572. return result;
  1573. }
  1574. //Гудвин
  1575. /**
  1576. * Displays the dialog box
  1577. *
  1578. * Отображает диалоговое окно
  1579. */
  1580. function confShow(message, yesCallback, noCallback) {
  1581. let buts = [];
  1582. message = message || I18N('DO_YOU_WANT');
  1583. noCallback = noCallback || (() => {});
  1584. if (yesCallback) {
  1585. buts = [
  1586. { msg: I18N('BTN_RUN'), result: true},
  1587. { msg: I18N('BTN_CANCEL'), result: false},
  1588. ]
  1589. } else {
  1590. yesCallback = () => {};
  1591. buts = [
  1592. { msg: I18N('BTN_OK'), result: true},
  1593. ];
  1594. }
  1595. popup.confirm(message, buts).then((e) => {
  1596. if (e) {
  1597. yesCallback();
  1598. } else {
  1599. noCallback();
  1600. }
  1601. });
  1602. }
  1603. /**
  1604. * Overriding/Proxying the Ajax Request Creation Method
  1605. *
  1606. * Переопределяем/проксируем метод создания Ajax запроса
  1607. */
  1608. XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
  1609. this.uniqid = Date.now();
  1610. this.errorRequest = false;
  1611. if (method == 'POST' && url.includes('.nextersglobal.com/api/') && /api\/$/.test(url)) {
  1612. if (!apiUrl) {
  1613. apiUrl = url;
  1614. socialInfo = /heroes-(.+?)\./.exec(apiUrl);
  1615. sNetwork = socialInfo ? socialInfo[1] : 'vk';
  1616. }
  1617. requestHistory[this.uniqid] = {
  1618. method,
  1619. url,
  1620. error: [],
  1621. headers: {},
  1622. request: null,
  1623. response: null,
  1624. signature: [],
  1625. calls: {},
  1626. };
  1627. } else if (method == 'POST' && url.includes('error.nextersglobal.com/client/')) {
  1628. this.errorRequest = true;
  1629. }
  1630. return original.open.call(this, method, url, async, user, password);
  1631. };
  1632. /**
  1633. * Overriding/Proxying the header setting method for the AJAX request
  1634. *
  1635. * Переопределяем/проксируем метод установки заголовков для AJAX запроса
  1636. */
  1637. XMLHttpRequest.prototype.setRequestHeader = function (name, value, check) {
  1638. if (this.uniqid in requestHistory) {
  1639. requestHistory[this.uniqid].headers[name] = value;
  1640. } else {
  1641. check = true;
  1642. }
  1643.  
  1644. if (name == 'X-Auth-Signature') {
  1645. requestHistory[this.uniqid].signature.push(value);
  1646. if (!check) {
  1647. return;
  1648. }
  1649. }
  1650.  
  1651. return original.setRequestHeader.call(this, name, value);
  1652. };
  1653. /**
  1654. * Overriding/Proxying the AJAX Request Sending Method
  1655. *
  1656. * Переопределяем/проксируем метод отправки AJAX запроса
  1657. */
  1658. XMLHttpRequest.prototype.send = async function (sourceData) {
  1659. if (this.uniqid in requestHistory) {
  1660. let tempData = null;
  1661. if (getClass(sourceData) == "ArrayBuffer") {
  1662. tempData = decoder.decode(sourceData);
  1663. } else {
  1664. tempData = sourceData;
  1665. }
  1666. requestHistory[this.uniqid].request = tempData;
  1667. let headers = requestHistory[this.uniqid].headers;
  1668. lastHeaders = Object.assign({}, headers);
  1669. /**
  1670. * Game loading event
  1671. *
  1672. * Событие загрузки игры
  1673. */
  1674. if (headers["X-Request-Id"] > 2 && !isLoadGame) {
  1675. isLoadGame = true;
  1676. await openOrMigrateDatabase(userInfo.id);
  1677. await lib.load(cheats.libGame);
  1678. addControls();
  1679. addControlButtons();
  1680. addBottomUrls();
  1681. //if (isChecked('sendExpedition')) {
  1682. checkExpedition(); //экспедиции на авто
  1683. //}
  1684.  
  1685. checkSendGifts();
  1686. getAutoGifts();
  1687.  
  1688. cheats.activateHacks();
  1689.  
  1690. justInfo();
  1691. if (isChecked('dailyQuests')) {
  1692. testDailyQuests();
  1693. }
  1694.  
  1695. if (isChecked('secretWealth')) {
  1696. buyWithPetExperienceAuto();
  1697. }
  1698.  
  1699. if (isChecked('buyForGold')) {
  1700. buyInStoreForGold();
  1701. }
  1702. }
  1703. /**
  1704. * Outgoing request data processing
  1705. *
  1706. * Обработка данных исходящего запроса
  1707. */
  1708. sourceData = await checkChangeSend.call(this, sourceData, tempData);
  1709. /**
  1710. * Handling incoming request data
  1711. *
  1712. * Обработка данных входящего запроса
  1713. */
  1714. const oldReady = this.onreadystatechange;
  1715. this.onreadystatechange = async function (e) {
  1716. if(this.readyState == 4 && this.status == 200) {
  1717. isTextResponse = this.responseType === "text" || this.responseType === "";
  1718. let response = isTextResponse ? this.responseText : this.response;
  1719. requestHistory[this.uniqid].response = response;
  1720. /**
  1721. * Replacing incoming request data
  1722. *
  1723. * Замена данных входящего запроса
  1724. */
  1725. if (isTextResponse) {
  1726. await checkChangeResponse.call(this, response);
  1727. }
  1728. /**
  1729. * A function to run after the request is executed
  1730. *
  1731. * Функция запускаемая после выполения запроса
  1732. */
  1733. if (typeof this.onReadySuccess == 'function') {
  1734. setTimeout(this.onReadySuccess, 500);
  1735. }
  1736. }
  1737. if (oldReady) {
  1738. return oldReady.apply(this, arguments);
  1739. }
  1740. }
  1741. }
  1742. if (this.errorRequest) {
  1743. const oldReady = this.onreadystatechange;
  1744. this.onreadystatechange = function () {
  1745. Object.defineProperty(this, 'status', {
  1746. writable: true
  1747. });
  1748. this.status = 200;
  1749. Object.defineProperty(this, 'readyState', {
  1750. writable: true
  1751. });
  1752. this.readyState = 4;
  1753. Object.defineProperty(this, 'responseText', {
  1754. writable: true
  1755. });
  1756. this.responseText = JSON.stringify({
  1757. "result": true
  1758. });
  1759. return oldReady.apply(this, arguments);
  1760. }
  1761. this.onreadystatechange();
  1762. } else {
  1763. return original.send.call(this, sourceData);
  1764. }
  1765. };
  1766. /**
  1767. * Processing and substitution of outgoing data
  1768. *
  1769. * Обработка и подмена исходящих данных
  1770. */
  1771. async function checkChangeSend(sourceData, tempData) {
  1772. try {
  1773. /**
  1774. * A function that replaces battle data with incorrect ones to cancel combatя
  1775. *
  1776. * Функция заменяющая данные боя на неверные для отмены боя
  1777. */
  1778. const fixBattle = function (heroes) {
  1779. for (const ids in heroes) {
  1780. hero = heroes[ids];
  1781. hero.energy = random(1, 999);
  1782. if (hero.hp > 0) {
  1783. hero.hp = random(1, hero.hp);
  1784. }
  1785. }
  1786. }
  1787. /**
  1788. * Dialog window 2
  1789. *
  1790. * Диалоговое окно 2
  1791. */
  1792. const showMsg = async function (msg, ansF, ansS) {
  1793. if (typeof popup == 'object') {
  1794. return await popup.confirm(msg, [
  1795. {msg: ansF, result: false},
  1796. {msg: ansS, result: true},
  1797. ]);
  1798. } else {
  1799. return !confirm(`${msg}\n ${ansF} (${I18N('BTN_OK')})\n ${ansS} (${I18N('BTN_CANCEL')})`);
  1800. }
  1801. }
  1802. /**
  1803. * Dialog window 3
  1804. *
  1805. * Диалоговое окно 3
  1806. */
  1807. const showMsgs = async function (msg, ansF, ansS, ansT) {
  1808. return await popup.confirm(msg, [
  1809. {msg: ansF, result: 0},
  1810. {msg: ansS, result: 1},
  1811. {msg: ansT, result: 2},
  1812. ]);
  1813. }
  1814.  
  1815. let changeRequest = false;
  1816. testData = JSON.parse(tempData);
  1817. for (const call of testData.calls) {
  1818. if (!artifactChestOpen) {
  1819. requestHistory[this.uniqid].calls[call.name] = call.ident;
  1820. }
  1821. /**
  1822. * Cancellation of the battle in adventures, on VG and with minions of Asgard
  1823. * Отмена боя в приключениях, на ВГ и с прислужниками Асгарда
  1824. */
  1825. if ((call.name == 'adventure_endBattle' ||
  1826. call.name == 'adventureSolo_endBattle' ||
  1827. call.name == 'clanWarEndBattle' &&
  1828. isChecked('cancelBattle') ||
  1829. call.name == 'crossClanWar_endBattle' &&
  1830. isChecked('cancelBattle') ||
  1831. call.name == 'brawl_endBattle' ||
  1832. call.name == 'towerEndBattle' ||
  1833. call.name == 'clanRaid_endNodeBattle') &&
  1834. isCancalBattle) {
  1835. nameFuncEndBattle = call.name;
  1836. if (!call.args.result.win) {
  1837. let resultPopup = false;
  1838. if (call.name == 'adventure_endBattle' ||
  1839. call.name == 'adventureSolo_endBattle') {
  1840. resultPopup = await showMsgs(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_CANCEL'), I18N('BTN_AUTO'));
  1841. } else if (call.name == 'clanWarEndBattle' ||
  1842. call.name == 'crossClanWar_endBattle') {
  1843. resultPopup = await showMsg(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_AUTO_F5'));
  1844. } else {
  1845. resultPopup = await showMsg(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_CANCEL'));
  1846. }
  1847. if (resultPopup) {
  1848. fixBattle(call.args.progress[0].attackers.heroes);
  1849. fixBattle(call.args.progress[0].defenders.heroes);
  1850. changeRequest = true;
  1851. if (resultPopup > 1) {
  1852. this.onReadySuccess = testAutoBattle;
  1853. // setTimeout(bossBattle, 1000);
  1854. }
  1855. }
  1856. } else if (call.args.result.stars < 3 && call.name == 'towerEndBattle') {
  1857. resultPopup = await showMsg(I18N('LOST_HEROES'), I18N('BTN_OK'), I18N('BTN_CANCEL'));
  1858. if (resultPopup) {
  1859. fixBattle(call.args.progress[0].attackers.heroes);
  1860. fixBattle(call.args.progress[0].defenders.heroes);
  1861. changeRequest = true;
  1862. }
  1863. }
  1864. if (isChecked('autoBrawls') && !isBrawlsAutoStart && call.name == 'brawl_endBattle') {
  1865. if (await popup.confirm(I18N('START_AUTO_BRAWLS'), [
  1866. { msg: I18N('BTN_NO'), result: false },
  1867. { msg: I18N('BTN_YES'), result: true },
  1868. ])) {
  1869. this.onReadySuccess = testBrawls;
  1870. isBrawlsAutoStart = true;
  1871. }
  1872. }
  1873. }
  1874. /**
  1875. * Save pack for Brawls
  1876. *
  1877. * Сохраняем пачку для потасовок
  1878. */
  1879. if (call.name == 'brawl_startBattle') {
  1880. console.log(JSON.stringify(call.args));
  1881. brawlsPack = call.args;
  1882. }
  1883. /**
  1884. * Canceled fight in Asgard
  1885. * Отмена боя в Асгарде
  1886. */
  1887. if (call.name == 'clanRaid_endBossBattle' &&
  1888. isCancalBossBattle &&
  1889. isChecked('cancelBattle')) {
  1890. bossDamage = call.args.progress[0].defenders.heroes[1].extra;
  1891. sumDamage = bossDamage.damageTaken + bossDamage.damageTakenNextLevel;
  1892. let resultPopup = await showMsgs(
  1893. `${I18N('MSG_YOU_APPLIED')} ${sumDamage.toLocaleString()} ${I18N('MSG_DAMAGE')}.`,
  1894. I18N('BTN_OK'), I18N('BTN_AUTO_F5'), I18N('MSG_CANCEL_AND_STAT'))
  1895. if (resultPopup) {
  1896. fixBattle(call.args.progress[0].attackers.heroes);
  1897. fixBattle(call.args.progress[0].defenders.heroes);
  1898. changeRequest = true;
  1899. if (resultPopup > 1) {
  1900. this.onReadySuccess = testBossBattle;
  1901. // setTimeout(bossBattle, 1000);
  1902. }
  1903. }
  1904. }
  1905. /**
  1906. * Save the Asgard Boss Attack Pack
  1907. * Сохраняем пачку для атаки босса Асгарда
  1908. */
  1909. if (call.name == 'clanRaid_startBossBattle') {
  1910. lastBossBattle = call.args;
  1911. }
  1912. /**
  1913. * Saving the request to start the last battle
  1914. * Сохранение запроса начала последнего боя
  1915. */
  1916. if (call.name == 'clanWarAttack' ||
  1917. call.name == 'crossClanWar_startBattle' ||
  1918. call.name == 'adventure_turnStartBattle') {
  1919. nameFuncStartBattle = call.name;
  1920. lastBattleArg = call.args;
  1921. }
  1922. /**
  1923. * Disable spending divination cards
  1924. * Отключить трату карт предсказаний
  1925. */
  1926. if (call.name == 'dungeonEndBattle') {
  1927. if (call.args.isRaid) {
  1928. if (countPredictionCard <= 0) {
  1929. delete call.args.isRaid;
  1930. changeRequest = true;
  1931. } else if (countPredictionCard > 0) {
  1932. countPredictionCard--;
  1933. }
  1934. }
  1935. console.log(`Cards: ${countPredictionCard}`);
  1936. /**
  1937. * Fix endless cards
  1938. * Исправление бесконечных карт
  1939. */
  1940. const lastBattle = lastDungeonBattleData;
  1941. if (lastBattle && !call.args.isRaid) {
  1942. if (changeRequest) {
  1943. lastBattle.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  1944. } else {
  1945. lastBattle.progress = call.args.progress;
  1946. }
  1947. const result = await Calc(lastBattle);
  1948. if (changeRequest) {
  1949. call.args.progress = result.progress;
  1950. call.args.result = result.result;
  1951. }
  1952.  
  1953. let timer = getTimer(result.battleTime);
  1954. const period = Math.ceil((Date.now() - lastDungeonBattleStart) / 1000);
  1955. console.log(timer, period);
  1956. if (period < timer) {
  1957. timer = timer - period;
  1958. await countdownTimer(timer);
  1959. }
  1960.  
  1961. }
  1962. }
  1963. /**
  1964. * Quiz Answer
  1965. * Ответ на викторину
  1966. */
  1967. if (call.name == 'quizAnswer') {
  1968. /**
  1969. * Automatically changes the answer to the correct one if there is one.
  1970. * Автоматически меняет ответ на правильный если он есть
  1971. */
  1972. if (lastAnswer && isChecked('getAnswer')) {
  1973. call.args.answerId = lastAnswer;
  1974. lastAnswer = null;
  1975. changeRequest = true;
  1976. }
  1977. }
  1978. /**
  1979. * Present
  1980. * Подарки
  1981. */
  1982. if (call.name == 'freebieCheck') {
  1983. freebieCheckInfo = call;
  1984. }
  1985. /**
  1986. * Getting mission data for auto-repeat
  1987. * Получение данных миссии для автоповтора
  1988. */
  1989. if ((isRepeatMission || isChecked('isRepeatMission')) &&
  1990. call.name == 'missionEnd') {
  1991. let missionInfo = {
  1992. id: call.args.id,
  1993. result: call.args.result,
  1994. heroes: call.args.progress[0].attackers.heroes,
  1995. count: 0,
  1996. }
  1997. setTimeout(async () => {
  1998. if (!isSendsMission && await popup.confirm(I18N('MSG_REPEAT_MISSION'), [
  1999. { msg: I18N('BTN_REPEAT'), result: true},
  2000. { msg: I18N('BTN_NO'), result: false},
  2001. ])) {
  2002. isStopSendMission = false;
  2003. isSendsMission = true;
  2004. sendsMission(missionInfo);
  2005. }
  2006. }, 0);
  2007. }
  2008. /**
  2009. * Getting mission data
  2010. * Получение данных миссии
  2011. */
  2012. if (call.name == 'missionStart') {
  2013. lastMissionStart = call.args;
  2014. }
  2015. /**
  2016. * Specify the quantity for Titan Orbs and Pet Eggs
  2017. * Указать количество для сфер титанов и яиц петов
  2018. */
  2019. if (isChecked('countControl') &&
  2020. (call.name == 'pet_chestOpen' ||
  2021. call.name == 'titanUseSummonCircle') &&
  2022. call.args.amount > 1) {
  2023. call.args.amount = 1;
  2024. const result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2025. { msg: I18N('BTN_OPEN'), isInput: true, default: call.args.amount},
  2026. ]);
  2027. if (result) {
  2028. call.args.amount = result;
  2029. changeRequest = true;
  2030. }
  2031. }
  2032. /**
  2033. * Specify the amount for keys and spheres of titan artifacts
  2034. * Указать колличество для ключей и сфер артефактов титанов
  2035. */
  2036. if (isChecked('countControl') &&
  2037. (call.name == 'artifactChestOpen' ||
  2038. call.name == 'titanArtifactChestOpen') &&
  2039. call.args.amount > 1 &&
  2040. call.args.free &&
  2041. !changeRequest) {
  2042. artifactChestOpenCallName = call.name;
  2043. let result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2044. { msg: I18N('BTN_OPEN'), isInput: true, default: call.args.amount },
  2045. ]);
  2046. if (result) {
  2047. let sphere = result < 10 ? 1 : 10;
  2048.  
  2049. call.args.amount = sphere;
  2050. result -= sphere;
  2051.  
  2052. for (let count = result; count > 0; count -= sphere) {
  2053. if (count < 10) sphere = 1;
  2054. const ident = artifactChestOpenCallName + "_" + count;
  2055. testData.calls.push({
  2056. name: artifactChestOpenCallName,
  2057. args: {
  2058. amount: sphere,
  2059. free: true,
  2060. },
  2061. ident: ident
  2062. });
  2063. if (!Array.isArray(requestHistory[this.uniqid].calls[call.name])) {
  2064. requestHistory[this.uniqid].calls[call.name] = [requestHistory[this.uniqid].calls[call.name]];
  2065. }
  2066. requestHistory[this.uniqid].calls[call.name].push(ident);
  2067. }
  2068.  
  2069. artifactChestOpen = true;
  2070. changeRequest = true;
  2071. }
  2072. }
  2073. if (call.name == 'consumableUseLootBox') {
  2074. lastRussianDollId = call.args.libId;
  2075. /**
  2076. * Specify quantity for gold caskets
  2077. * Указать количество для золотых шкатулок
  2078. */
  2079. if (isChecked('countControl') &&
  2080. call.args.libId == 148 &&
  2081. call.args.amount > 1) {
  2082. const result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2083. { msg: I18N('BTN_OPEN'), isInput: true, default: call.args.amount},
  2084. ]);
  2085. call.args.amount = result;
  2086. changeRequest = true;
  2087. }
  2088. }
  2089. /**
  2090. * Adding a request to receive 26 store
  2091. * Добавление запроса на получение 26 магазина
  2092. */
  2093. if (call.name == 'registration') {
  2094. /*
  2095. testData.calls.push({
  2096. name: "shopGet",
  2097. args: {
  2098. shopId: "26"
  2099. },
  2100. ident: "shopGet"
  2101. });
  2102. changeRequest = true;
  2103. */
  2104. }
  2105. /**
  2106. * Changing the maximum number of raids in the campaign
  2107. * Изменение максимального количества рейдов в кампании
  2108. */
  2109. // if (call.name == 'missionRaid') {
  2110. // if (isChecked('countControl') && call.args.times > 1) {
  2111. // const result = +(await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2112. // { msg: I18N('BTN_RUN'), isInput: true, default: call.args.times },
  2113. // ]));
  2114. // call.args.times = result > call.args.times ? call.args.times : result;
  2115. // changeRequest = true;
  2116. // }
  2117. // }
  2118. }
  2119.  
  2120. let headers = requestHistory[this.uniqid].headers;
  2121. if (changeRequest) {
  2122. sourceData = JSON.stringify(testData);
  2123. headers['X-Auth-Signature'] = getSignature(headers, sourceData);
  2124. }
  2125.  
  2126. let signature = headers['X-Auth-Signature'];
  2127. if (signature) {
  2128. original.setRequestHeader.call(this, 'X-Auth-Signature', signature);
  2129. }
  2130. } catch (err) {
  2131. console.log("Request(send, " + this.uniqid + "):\n", sourceData, "Error:\n", err);
  2132. }
  2133. return sourceData;
  2134. }
  2135. /**
  2136. * Processing and substitution of incoming data
  2137. *
  2138. * Обработка и подмена входящих данных
  2139. */
  2140. async function checkChangeResponse(response) {
  2141. try {
  2142. isChange = false;
  2143. let nowTime = Math.round(Date.now() / 1000);
  2144. callsIdent = requestHistory[this.uniqid].calls;
  2145. respond = JSON.parse(response);
  2146. /**
  2147. * If the request returned an error removes the error (removes synchronization errors)
  2148. * Если запрос вернул ошибку удаляет ошибку (убирает ошибки синхронизации)
  2149. */
  2150. if (respond.error) {
  2151. isChange = true;
  2152. console.error(respond.error);
  2153. if (isChecked('showErrors')) {
  2154. popup.confirm(I18N('ERROR_MSG', {
  2155. name: respond.error.name,
  2156. description: respond.error.description,
  2157. }));
  2158. }
  2159. delete respond.error;
  2160. respond.results = [];
  2161. }
  2162. let mainReward = null;
  2163. const allReward = {};
  2164. let readQuestInfo = false;
  2165. for (const call of respond.results) {
  2166. /**
  2167. * Obtaining initial data for completing quests
  2168. * Получение исходных данных для выполнения квестов
  2169. */
  2170. if (readQuestInfo) {
  2171. questsInfo[call.ident] = call.result.response;
  2172. }
  2173. /**
  2174. * Getting a user ID
  2175. * Получение идетификатора пользователя
  2176. */
  2177. if (call.ident == callsIdent['registration']) {
  2178. userId = call.result.response.userId;
  2179. readQuestInfo = true;
  2180. }
  2181. /**
  2182. * Endless lives in brawls
  2183. * Бесконечные жизни в потасовках
  2184. */
  2185. /*
  2186. if (getSaveVal('autoBrawls') && call.ident == callsIdent['brawl_getInfo']) {
  2187. brawl = call.result.response;
  2188. if (brawl) {
  2189. brawl.boughtEndlessLivesToday = 1;
  2190. isChange = true;
  2191. }
  2192. }
  2193. */
  2194. /**
  2195. * Hiding donation offers 1
  2196. * Скрываем предложения доната 1
  2197. */
  2198. if (call.ident == callsIdent['billingGetAll'] && getSaveVal('noOfferDonat')) {
  2199. const billings = call.result.response?.billings;
  2200. const bundle = call.result.response?.bundle;
  2201. if (billings && bundle) {
  2202. call.result.response.billings = [];
  2203. call.result.response.bundle = [];
  2204. isChange = true;
  2205. }
  2206. }
  2207. /**
  2208. * Hiding donation offers 2
  2209. * Скрываем предложения доната 2
  2210. */
  2211. if (getSaveVal('noOfferDonat') &&
  2212. (call.ident == callsIdent['offerGetAll'] ||
  2213. call.ident == callsIdent['specialOffer_getAll'])) {
  2214. let offers = call.result.response;
  2215. if (offers) {
  2216. call.result.response = offers.filter(e => !['addBilling', 'bundleCarousel'].includes(e.type));
  2217. isChange = true;
  2218. }
  2219. }
  2220. /**
  2221. * Hiding donation offers 3
  2222. * Скрываем предложения доната 3
  2223. */
  2224. if (getSaveVal('noOfferDonat') && call.result?.bundleUpdate) {
  2225. delete call.result.bundleUpdate;
  2226. isChange = true;
  2227. }
  2228. /**
  2229. * Copies a quiz question to the clipboard
  2230. * Копирует вопрос викторины в буфер обмена и получает на него ответ если есть
  2231. */
  2232. if (call.ident == callsIdent['quizGetNewQuestion']) {
  2233. let quest = call.result.response;
  2234. console.log(quest.question);
  2235. copyText(quest.question);
  2236. setProgress(I18N('QUESTION_COPY'), true);
  2237. quest.lang = null;
  2238. if (typeof NXFlashVars !== 'undefined') {
  2239. quest.lang = NXFlashVars.interface_lang;
  2240. }
  2241. lastQuestion = quest;
  2242. if (isChecked('getAnswer')) {
  2243. const answer = await getAnswer(lastQuestion);
  2244. if (answer) {
  2245. lastAnswer = answer;
  2246. console.log(answer);
  2247. setProgress(`${I18N('ANSWER_KNOWN')}: ${answer}`, true);
  2248. } else {
  2249. setProgress(I18N('ANSWER_NOT_KNOWN'), true);
  2250. }
  2251. }
  2252. }
  2253. /**
  2254. * Submits a question with an answer to the database
  2255. * Отправляет вопрос с ответом в базу данных
  2256. */
  2257. if (call.ident == callsIdent['quizAnswer']) {
  2258. const answer = call.result.response;
  2259. if (lastQuestion) {
  2260. const answerInfo = {
  2261. answer,
  2262. question: lastQuestion,
  2263. lang: null,
  2264. }
  2265. if (typeof NXFlashVars !== 'undefined') {
  2266. answerInfo.lang = NXFlashVars.interface_lang;
  2267. }
  2268. lastQuestion = null;
  2269. setTimeout(sendAnswerInfo, 0, answerInfo);
  2270. }
  2271. }
  2272. /**
  2273. * Get user data
  2274. * Получить даныне пользователя
  2275. */
  2276. if (call.ident == callsIdent['userGetInfo']) {
  2277. let user = call.result.response;
  2278. userInfo = Object.assign({}, user);
  2279. delete userInfo.refillable;
  2280. if (!questsInfo['userGetInfo']) {
  2281. questsInfo['userGetInfo'] = user;
  2282. }
  2283. }
  2284. /**
  2285. * Start of the battle for recalculation
  2286. * Начало боя для прерасчета
  2287. */
  2288. if ((call.ident == callsIdent['clanWarAttack'] ||
  2289. call.ident == callsIdent['crossClanWar_startBattle'] ||
  2290. call.ident == callsIdent['battleGetReplay'] ||
  2291. call.ident == callsIdent['brawl_startBattle'] ||
  2292. call.ident == callsIdent['adventureSolo_turnStartBattle'] ||
  2293. call.ident == callsIdent['adventure_turnStartBattle']) &&
  2294. isChecked('preCalcBattle')) {
  2295. setProgress('Идет прерасчет боя');
  2296. let battle = call.result.response.battle || call.result.response.replay;
  2297. if (call.ident == callsIdent['brawl_startBattle']) {
  2298. battle = call.result.response;
  2299. }
  2300. lastBattleInfo = battle;
  2301. console.log(battle.type);
  2302. function getBattleInfo(battle, isRandSeed) {
  2303. return new Promise(function (resolve) {
  2304. if (isRandSeed) {
  2305. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  2306. }
  2307. BattleCalc(battle, getBattleType(battle.type), e => resolve(e));
  2308. });
  2309. }
  2310. let actions = [getBattleInfo(battle, false)]
  2311. const countTestBattle = getInput('countTestBattle');
  2312. if (call.ident == callsIdent['battleGetReplay']) {
  2313. battle.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  2314. }
  2315. for (let i = 0; i < countTestBattle; i++) {
  2316. actions.push(getBattleInfo(battle, true));
  2317. }
  2318. Promise.all(actions)
  2319. .then(e => {
  2320. e = e.map(n => ({win: n.result.win, time: n.battleTime}));
  2321. let firstBattle = e.shift();
  2322. const timer = Math.floor(120 - firstBattle.time);
  2323. const min = ('00' + Math.floor(timer / 60)).slice(-2);
  2324. const sec = ('00' + Math.floor(timer - min * 60)).slice(-2);
  2325. const countWin = e.reduce((w, s) => w + s.win, 0);
  2326. 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)
  2327. });
  2328. }
  2329. //тест сохранки
  2330. /** Запоминаем команды в реплее*/
  2331. if (call.ident == callsIdent['battleGetReplay']) {
  2332. let battle = call.result.response.replay;
  2333. repleyBattle.attackers = battle.attackers;
  2334. repleyBattle.defenders = battle.defenders[0];
  2335. repleyBattle.effects = battle.effects.defenders;
  2336. repleyBattle.state = battle.progress[0].defenders.heroes;
  2337. repleyBattle.seed = battle.seed;
  2338. }
  2339. /** Нападение в турнире*/
  2340. if (call.ident == callsIdent['titanArenaStartBattle']) {
  2341. let bestBattle = getInput('countBattle');
  2342. let unrandom = getInput('needResource');
  2343. let maxPower = getInput('needResource2');
  2344. if (bestBattle * unrandom * maxPower == 0) {
  2345. let battle = call.result.response.battle;
  2346. if (bestBattle == 0) {
  2347. battle.progress = bestLordBattle[battle.typeId]?.progress;
  2348. }
  2349. if (unrandom == 0 && !!repleyBattle.seed) {
  2350. battle.seed = repleyBattle.seed;
  2351. }
  2352. if (maxPower == 0) {
  2353. battle.attackers = getTitansPack(Object.keys(battle.attackers));
  2354. }
  2355. isChange = true;
  2356. }
  2357. }
  2358. /** Тест боев с усилениями команд защиты*/
  2359. if (call.ident == callsIdent['chatAcceptChallenge']) {
  2360. let battle = call.result.response.battle;
  2361. addBuff(battle);
  2362. let testType = getInput('countBattle');
  2363. if (testType.slice(0, 1) == "-") {
  2364. testType = parseInt(testType.slice(1), 10);
  2365. switch (testType) {
  2366. case 1:
  2367. battle.defenders[0] = repleyBattle.defenders;
  2368. break; //наша атака против защиты из реплея
  2369. case 2:
  2370. battle.defenders[0] = repleyBattle.attackers;
  2371. break; //наша атака против атаки из реплея
  2372. case 3:
  2373. battle.attackers = repleyBattle.attackers;
  2374. break; //атака из реплея против защиты в чате
  2375. case 4:
  2376. battle.attackers = repleyBattle.defenders;
  2377. break; //защита из реплея против защиты в чате
  2378. case 5:
  2379. battle.attackers = repleyBattle.attackers;
  2380. battle.defenders[0] = repleyBattle.defenders;
  2381. break; //атака из реплея против защиты из реплея
  2382. case 6:
  2383. battle.attackers = repleyBattle.defenders;
  2384. battle.defenders[0] = repleyBattle.attackers;
  2385. break; //защита из реплея против атаки из реплея
  2386. case 7:
  2387. battle.attackers = repleyBattle.attackers;
  2388. battle.defenders[0] = repleyBattle.attackers;
  2389. break; //атака из реплея против атаки из реплея
  2390. case 8:
  2391. battle.attackers = repleyBattle.defenders;
  2392. battle.defenders[0] = repleyBattle.defenders;
  2393. break; //защита из реплея против защиты из реплея
  2394. }
  2395. }
  2396.  
  2397. isChange = true;
  2398. }
  2399. /** Тест боев с усилениями команд защиты тренировках*/
  2400. if (call.ident == callsIdent['demoBattles_startBattle']) {
  2401. let battle = call.result.response.battle;
  2402. addBuff(battle);
  2403. let testType = getInput('countBattle');
  2404. if (testType.slice(0, 1) == "-") {
  2405. testType = parseInt(testType.slice(1), 10);
  2406. switch (testType) {
  2407. case 1:
  2408. battle.defenders[0] = repleyBattle.defenders;
  2409. break; //наша атака против защиты из реплея
  2410. case 2:
  2411. battle.defenders[0] = repleyBattle.attackers;
  2412. break; //наша атака против атаки из реплея
  2413. case 3:
  2414. battle.attackers = repleyBattle.attackers;
  2415. break; //атака из реплея против защиты в чате
  2416. case 4:
  2417. battle.attackers = repleyBattle.defenders;
  2418. break; //защита из реплея против защиты в чате
  2419. case 5:
  2420. battle.attackers = repleyBattle.attackers;
  2421. battle.defenders[0] = repleyBattle.defenders;
  2422. break; //атака из реплея против защиты из реплея
  2423. case 6:
  2424. battle.attackers = repleyBattle.defenders;
  2425. battle.defenders[0] = repleyBattle.attackers;
  2426. break; //защита из реплея против атаки из реплея
  2427. case 7:
  2428. battle.attackers = repleyBattle.attackers;
  2429. battle.defenders[0] = repleyBattle.attackers;
  2430. break; //атака из реплея против атаки из реплея
  2431. case 8:
  2432. battle.attackers = repleyBattle.defenders;
  2433. battle.defenders[0] = repleyBattle.defenders;
  2434. break; //защита из реплея против защиты из реплея
  2435. }
  2436. }
  2437.  
  2438. isChange = true;
  2439. }
  2440. //тест сохранки
  2441. /**
  2442. * Start of the Asgard boss fight
  2443. * Начало боя с боссом Асгарда
  2444. */
  2445. if (call.ident == callsIdent['clanRaid_startBossBattle']) {
  2446. lastBossBattleInfo = call.result.response.battle;
  2447. if (isChecked('preCalcBattle')) {
  2448. const result = await Calc(lastBossBattleInfo).then(e => e.progress[0].defenders.heroes[1].extra);
  2449. const bossDamage = result.damageTaken + result.damageTakenNextLevel;
  2450. setProgress(I18N('BOSS_DAMAGE') + bossDamage.toLocaleString(), false, hideProgress);
  2451. }
  2452. }
  2453. /**
  2454. * Cancel tutorial
  2455. * Отмена туториала
  2456. */
  2457. if (isCanceledTutorial && call.ident == callsIdent['tutorialGetInfo']) {
  2458. let chains = call.result.response.chains;
  2459. for (let n in chains) {
  2460. chains[n] = 9999;
  2461. }
  2462. isChange = true;
  2463. }
  2464. /**
  2465. * Opening keys and spheres of titan artifacts
  2466. * Открытие ключей и сфер артефактов титанов
  2467. */
  2468. if (artifactChestOpen &&
  2469. (call.ident == callsIdent[artifactChestOpenCallName] ||
  2470. (callsIdent[artifactChestOpenCallName] && callsIdent[artifactChestOpenCallName].includes(call.ident)))) {
  2471. let reward = call.result.response[artifactChestOpenCallName == 'artifactChestOpen' ? 'chestReward' : 'reward'];
  2472.  
  2473. reward.forEach(e => {
  2474. for (let f in e) {
  2475. if (!allReward[f]) {
  2476. allReward[f] = {};
  2477. }
  2478. for (let o in e[f]) {
  2479. if (!allReward[f][o]) {
  2480. allReward[f][o] = e[f][o];
  2481. } else {
  2482. allReward[f][o] += e[f][o];
  2483. }
  2484. }
  2485. }
  2486. });
  2487.  
  2488. if (!call.ident.includes(artifactChestOpenCallName)) {
  2489. mainReward = call.result.response;
  2490. }
  2491. }
  2492.  
  2493. /**
  2494. * Sum the result of opening Pet Eggs
  2495. * Суммирование результата открытия яиц питомцев
  2496. */
  2497. if (isChecked('countControl') && call.ident == callsIdent['pet_chestOpen']) {
  2498. const rewards = call.result.response.rewards;
  2499. rewards.forEach(e => {
  2500. for (let f in e) {
  2501. if (!allReward[f]) {
  2502. allReward[f] = {};
  2503. }
  2504. for (let o in e[f]) {
  2505. if (!allReward[f][o]) {
  2506. allReward[f][o] = e[f][o];
  2507. } else {
  2508. allReward[f][o] += e[f][o];
  2509. }
  2510. }
  2511. }
  2512. });
  2513. call.result.response.rewards = [allReward];
  2514. isChange = true;
  2515. }
  2516. /**
  2517. * Auto-repeat opening matryoshkas
  2518. * АвтоПовтор открытия матрешек
  2519. */
  2520. if (isChecked('countControl') && call.ident == callsIdent['consumableUseLootBox']) {
  2521. let lootBox = call.result.response;
  2522. let newCount = 0;
  2523. for (let n of lootBox) {
  2524. if (n?.consumable && n.consumable[lastRussianDollId]) {
  2525. newCount += n.consumable[lastRussianDollId]
  2526. }
  2527. }
  2528. if (newCount && await popup.confirm(`${I18N('BTN_OPEN')} ${newCount} ${I18N('OPEN_DOLLS')}?`, [
  2529. { msg: I18N('BTN_OPEN'), result: true},
  2530. { msg: I18N('BTN_NO'), result: false},
  2531. ])) {
  2532. const recursionResult = await openRussianDolls(lastRussianDollId, newCount);
  2533. lootBox = [...lootBox, ...recursionResult];
  2534. }
  2535. /** Объединение результата лутбоксов */
  2536. const allLootBox = {};
  2537. lootBox.forEach(e => {
  2538. for (let f in e) {
  2539. if (!allLootBox[f]) {
  2540. if (typeof e[f] == 'object') {
  2541. allLootBox[f] = {};
  2542. } else {
  2543. allLootBox[f] = 0;
  2544. }
  2545. }
  2546. if (typeof e[f] == 'object') {
  2547. for (let o in e[f]) {
  2548. if (newCount && o == lastRussianDollId) {
  2549. continue;
  2550. }
  2551. if (!allLootBox[f][o]) {
  2552. allLootBox[f][o] = e[f][o];
  2553. } else {
  2554. allLootBox[f][o] += e[f][o];
  2555. }
  2556. }
  2557. } else {
  2558. allLootBox[f] += e[f];
  2559. }
  2560. }
  2561. });
  2562. /** Разбитие результата */
  2563. const output = [];
  2564. const maxCount = 5;
  2565. let currentObj = {};
  2566. let count = 0;
  2567. for (let f in allLootBox) {
  2568. if (!currentObj[f]) {
  2569. if (typeof allLootBox[f] == 'object') {
  2570. for (let o in allLootBox[f]) {
  2571. currentObj[f] ||= {}
  2572. if (!currentObj[f][o]) {
  2573. currentObj[f][o] = allLootBox[f][o];
  2574. count++;
  2575. if (count === maxCount) {
  2576. output.push(currentObj);
  2577. currentObj = {};
  2578. count = 0;
  2579. }
  2580. }
  2581. }
  2582. } else {
  2583. currentObj[f] = allLootBox[f];
  2584. count++;
  2585. if (count === maxCount) {
  2586. output.push(currentObj);
  2587. currentObj = {};
  2588. count = 0;
  2589. }
  2590. }
  2591. }
  2592. }
  2593. if (count > 0) {
  2594. output.push(currentObj);
  2595. }
  2596. console.log(output);
  2597. call.result.response = output;
  2598. isChange = true;
  2599. }
  2600. /**
  2601. * Dungeon recalculation (fix endless cards)
  2602. * Прерасчет подземки (исправление бесконечных карт)
  2603. */
  2604. if (call.ident == callsIdent['dungeonStartBattle']) {
  2605. lastDungeonBattleData = call.result.response;
  2606. lastDungeonBattleStart = Date.now();
  2607. }
  2608. /**
  2609. * Getting the number of prediction cards
  2610. * Получение количества карт предсказаний
  2611. */
  2612. if (call.ident == callsIdent['inventoryGet']) {
  2613. countPredictionCard = call.result.response.consumable[81] || 0;
  2614. }
  2615. /**
  2616. * Adding 26 store to other stores
  2617. * Добавление 26 магазина к остальным магазинам
  2618. */
  2619. if (call.ident == callsIdent['shopGetAll']) {
  2620. if (userInfo.level >= 10) {
  2621. call.result.response[26] = await Send({ calls: [{ name: "shopGet", args: { shopId: "26" }, ident: "shopGet" }] }).then(e => e.results[0].result.response);
  2622. console.log(call.result.response);;
  2623. isChange = true;
  2624. }
  2625. }
  2626. /**
  2627. * Getting subscription status
  2628. * Получение состояния подписки
  2629. */
  2630. if (call.ident == callsIdent['subscriptionGetInfo']) {
  2631. const subscription = call.result.response.subscription;
  2632. if (subscription) {
  2633. subEndTime = subscription.endTime * 1000;
  2634. }
  2635. }
  2636. /**
  2637. * Getting prediction cards
  2638. * Получение карт предсказаний
  2639. */
  2640. if (call.ident == callsIdent['questFarm']) {
  2641. const consumable = call.result.response?.consumable;
  2642. if (consumable && consumable[81]) {
  2643. countPredictionCard += consumable[81];
  2644. console.log(`Cards: ${countPredictionCard}`);
  2645. }
  2646. }
  2647. }
  2648.  
  2649. if (mainReward && artifactChestOpen) {
  2650. console.log(allReward);
  2651. mainReward[artifactChestOpenCallName == 'artifactChestOpen' ? 'chestReward' : 'reward'] = [allReward];
  2652. artifactChestOpen = false;
  2653. artifactChestOpenCallName = '';
  2654. isChange = true;
  2655. }
  2656. } catch(err) {
  2657. console.log("Request(response, " + this.uniqid + "):\n", "Error:\n", response, err);
  2658. }
  2659.  
  2660. if (isChange) {
  2661. Object.defineProperty(this, 'responseText', {
  2662. writable: true
  2663. });
  2664. this.responseText = JSON.stringify(respond);
  2665. }
  2666. }
  2667.  
  2668. /** Добавляет в бой эффекты усиления*/
  2669. function addBuff(battle) {
  2670. let effects = battle.effects;
  2671. let buffType = getInput('needResource2');
  2672. if (-1 < buffType && buffType < 7) {
  2673. let percentBuff = getInput('needResource');
  2674. effects.defenders = {};
  2675. effects.defenders[buffs[buffType]] = percentBuff;
  2676. } else if (buffType.slice(0, 1) == "-" || isChecked('treningBattle')) {
  2677. buffType = parseInt(buffType.slice(1), 10);
  2678. effects.defenders = repleyBattle.effects;
  2679. battle.defenders[0] = repleyBattle.defenders;
  2680. let def = battle.defenders[0];
  2681. if (buffType == 1) {
  2682. for (let i in def) {
  2683. let state = def[i].state;
  2684. state.hp = state.maxHp;
  2685. state.energy = 0;
  2686. state.isDead = false;
  2687. }
  2688. } else if (buffType == 2 || isChecked('finishingBattle')) {
  2689. for (let i in def) {
  2690. let state = def[i].state;
  2691. let rState = repleyBattle.state[i];
  2692. if (!!rState) {
  2693. state.hp = rState.hp;
  2694. state.energy = rState.energy;
  2695. state.isDead = rState.isDead;
  2696. } else {
  2697. state.hp = 0;
  2698. state.energy = 0;
  2699. state.isDead = true;
  2700. }
  2701. }
  2702. }
  2703. }
  2704. }
  2705. const buffs = ['percentBuffAll_allAttacks', 'percentBuffAll_armor', 'percentBuffAll_magicResist', 'percentBuffAll_physicalAttack', 'percentBuffAll_magicPower', 'percentDamageBuff_dot', 'percentBuffAll_healing', 'percentBuffAllForFallenAllies', 'percentBuffAll_energyIncrease', 'percentIncomeDamageReduce_any', 'percentIncomeDamageReduce_physical', 'percentIncomeDamageReduce_magic', 'percentIncomeDamageReduce_dot', 'percentBuffHp', 'percentBuffByPerk_energyIncrease_8', 'percentBuffByPerk_energyIncrease_5', 'percentBuffByPerk_energyIncrease_4', 'percentBuffByPerk_allAttacks_5', 'percentBuffByPerk_allAttacks_4', 'percentBuffByPerk_allAttacks_9', 'percentBuffByPerk_castSpeed_7', 'percentBuffByPerk_castSpeed_6', 'percentBuffByPerk_castSpeed_10', 'percentBuffByPerk_armorPenetration_6', 'percentBuffByPerk_physicalAttack_6', 'percentBuffByPerk_armorPenetration_10', 'percentBuffByPerk_physicalAttack_10', 'percentBuffByPerk_magicPower_7', 'percentDamageBuff_any','percentDamageBuff_physical','percentDamageBuff_magic','corruptedBoss_25_80_1_100_10','tutorialPetUlt_1.2','tutorialBossPercentDamage_1','corruptedBoss_50_80_1_100_10','corruptedBoss_75_80_1_100_10','corruptedBoss_80_80_1_100_10','percentBuffByPerk_castSpeed_4','percentBuffByPerk_energyIncrease_7','percentBuffByPerk_castSpeed_9','percentBuffByPerk_castSpeed_8','bossStageBuff_1000000_20000','bossStageBuff_1500000_30000','bossStageBuff_2000000_40000','bossStageBuff_3000000_50000','bossStageBuff_4000000_60000','bossStageBuff_5000000_70000','bossStageBuff_7500000_80000','bossStageBuff_11000000_90000','bossStageBuff_15000000_100000','bossStageBuff_20000000_120000','bossStageBuff_30000000_150000','bossStageBuff_40000000_200000','bossStageBuff_50000000_250000','percentBuffPet_strength','percentBuffPet_castSpeed','percentBuffPet_petEnergyIncrease','stormPowerBuff_100_1000','stormPowerBuff_100','changeStarSphereIncomingDamage_any','changeBlackHoleDamage','buffSpeedWhenStarfall','changeTeamStartEnergy','decreaseStarSphereDamage','avoidAllBlackholeDamageOnce','groveKeeperAvoidBlackholeDamageChance_3','undeadPreventsNightmares_3','engeneerIncreaseStarMachineIncomingDamage_3','overloadHealDamageStarSphere','nightmareDeathGiveLifesteal_100','starfallIncreaseAllyHeal_9_100','decreaseStarSphereDamage_4','increaseNightmaresIncomingDamageByCount','debuffNightmareOnSpawnFrom_7_hp','damageNightmareGiveEnergy','ultEnergyCompensationOnPlanetParade_6','bestDamagerBeforeParadeGetsImprovedBuff_any','starSphereDeathGiveEnergy','bestDamagerOnParadeBecomesImmortal_any','preventNightmare','buffStatWithHealing_physicalAttack_magic_100','buffStatWithHealing_magicPower_physical_100','buffStatWithHealing_hp_dot_100','replaceHealingWithDamage_magic','critWithRetaliation_10_dot','posessionWithBuffStat_25_20_5_10','energyBurnDamageWithEffect_magic_Silence_5_5','percentBuffHp','percentBuffAll_energyIncrease','percentBuffAll_magicResist','percentBuffAll_armor','percentIncomeDamageReduce_any','percentBuffAll_healing','percentIncomeDamageReduce_any','percentBuffHp','percentBuffAll_energyIncrease','percentIncomeDamageReduce_any','percentBuffHp','percentBuffByPerk_castSpeed_All','percentBuffAll_castSpeed'];
  2706.  
  2707. /**
  2708. * Request an answer to a question
  2709. *
  2710. * Запрос ответа на вопрос
  2711. */
  2712. async function getAnswer(question) {
  2713. return new Promise((resolve, reject) => {
  2714. fetch('https://zingery.ru/heroes/getAnswer.php', {
  2715. method: 'POST',
  2716. body: JSON.stringify(question)
  2717. }).then(
  2718. response => response.json()
  2719. ).then(
  2720. data => {
  2721. if (data.result) {
  2722. resolve(data.result);
  2723. } else {
  2724. resolve(false);
  2725. }
  2726. }
  2727. ).catch((error) => {
  2728. console.error(error);
  2729. resolve(false);
  2730. });
  2731. })
  2732. }
  2733.  
  2734. /**
  2735. * Submitting a question and answer to a database
  2736. *
  2737. * Отправка вопроса и ответа в базу данных
  2738. */
  2739. function sendAnswerInfo(answerInfo) {
  2740. fetch('https://zingery.ru/heroes/setAnswer.php', {
  2741. method: 'POST',
  2742. body: JSON.stringify(answerInfo)
  2743. }).then(
  2744. response => response.json()
  2745. ).then(
  2746. data => {
  2747. if (data.result) {
  2748. console.log(I18N('SENT_QUESTION'));
  2749. }
  2750. }
  2751. )
  2752. }
  2753.  
  2754. /**
  2755. * Returns the battle type by preset type
  2756. *
  2757. * Возвращает тип боя по типу пресета
  2758. */
  2759. function getBattleType(strBattleType) {
  2760. switch (strBattleType) {
  2761. case "invasion":
  2762. return "get_invasion";
  2763. case "titan_pvp_manual":
  2764. return "get_titanPvpManual";
  2765. case "titan_pvp":
  2766. return "get_titanPvp";
  2767. case "titan_clan_pvp":
  2768. case "clan_pvp_titan":
  2769. case "clan_global_pvp_titan":
  2770. case "brawl_titan":
  2771. case "challenge_titan":
  2772. return "get_titanClanPvp";
  2773. case "clan_raid": // Asgard Boss // Босс асгарда
  2774. case "adventure": // Adventures // Приключения
  2775. case "clan_global_pvp":
  2776. case "clan_pvp":
  2777. case "challenge":
  2778. return "get_clanPvp";
  2779. case "dungeon_titan":
  2780. case "titan_tower":
  2781. return "get_titan";
  2782. case "tower":
  2783. case "clan_dungeon":
  2784. return "get_tower";
  2785. case "pve":
  2786. return "get_pve";
  2787. case "pvp_manual":
  2788. return "get_pvpManual";
  2789. case "grand":
  2790. case "arena":
  2791. case "pvp":
  2792. return "get_pvp";
  2793. case "core":
  2794. return "get_core";
  2795. case "boss_10":
  2796. case "boss_11":
  2797. case "boss_12":
  2798. return "get_boss";
  2799. default:
  2800. return "get_clanPvp";
  2801. }
  2802. }
  2803. /**
  2804. * Returns the class name of the passed object
  2805. *
  2806. * Возвращает название класса переданного объекта
  2807. */
  2808. function getClass(obj) {
  2809. return {}.toString.call(obj).slice(8, -1);
  2810. }
  2811. /**
  2812. * Calculates the request signature
  2813. *
  2814. * Расчитывает сигнатуру запроса
  2815. */
  2816. this.getSignature = function(headers, data) {
  2817. const sign = {
  2818. signature: '',
  2819. length: 0,
  2820. add: function (text) {
  2821. this.signature += text;
  2822. if (this.length < this.signature.length) {
  2823. this.length = 3 * (this.signature.length + 1) >> 1;
  2824. }
  2825. },
  2826. }
  2827. sign.add(headers["X-Request-Id"]);
  2828. sign.add(':');
  2829. sign.add(headers["X-Auth-Token"]);
  2830. sign.add(':');
  2831. sign.add(headers["X-Auth-Session-Id"]);
  2832. sign.add(':');
  2833. sign.add(data);
  2834. sign.add(':');
  2835. sign.add('LIBRARY-VERSION=1');
  2836. sign.add('UNIQUE-SESSION-ID=' + headers["X-Env-Unique-Session-Id"]);
  2837.  
  2838. return md5(sign.signature);
  2839. }
  2840. /**
  2841. * Creates an interface
  2842. *
  2843. * Создает интерфейс
  2844. */
  2845. function createInterface() {
  2846. scriptMenu.init({
  2847. showMenu: true
  2848. });
  2849. scriptMenu.addHeader(GM_info.script.name, justInfo);
  2850. scriptMenu.addHeader('v' + GM_info.script.version);
  2851. }
  2852.  
  2853. function addControls() {
  2854. const checkboxDetails = scriptMenu.addDetails(I18N('SETTINGS'));
  2855. for (let name in checkboxes) {
  2856. checkboxes[name].cbox = scriptMenu.addCheckbox(checkboxes[name].label, checkboxes[name].title, checkboxDetails);
  2857. /**
  2858. * Getting the state of checkboxes from storage
  2859. * Получаем состояние чекбоксов из storage
  2860. */
  2861. let val = storage.get(name, null);
  2862. if (val != null) {
  2863. checkboxes[name].cbox.checked = val;
  2864. } else {
  2865. storage.set(name, checkboxes[name].default);
  2866. checkboxes[name].cbox.checked = checkboxes[name].default;
  2867. }
  2868. /**
  2869. * Tracing the change event of the checkbox for writing to storage
  2870. * Отсеживание события изменения чекбокса для записи в storage
  2871. */
  2872. checkboxes[name].cbox.dataset['name'] = name;
  2873. checkboxes[name].cbox.addEventListener('change', async function (event) {
  2874. const nameCheckbox = this.dataset['name'];
  2875. /*
  2876. if (this.checked && nameCheckbox == 'cancelBattle') {
  2877. this.checked = false;
  2878. if (await popup.confirm(I18N('MSG_BAN_ATTENTION'), [
  2879. { msg: I18N('BTN_NO_I_AM_AGAINST'), result: true },
  2880. { msg: I18N('BTN_YES_I_AGREE'), result: false },
  2881. ])) {
  2882. return;
  2883. }
  2884. this.checked = true;
  2885. }
  2886. */
  2887. storage.set(nameCheckbox, this.checked);
  2888. })
  2889. }
  2890.  
  2891. const inputDetails = scriptMenu.addDetails(I18N('VALUES'));
  2892. for (let name in inputs) {
  2893. inputs[name].input = scriptMenu.addInputText(inputs[name].title, false, inputDetails);
  2894. /**
  2895. * Get inputText state from storage
  2896. * Получаем состояние inputText из storage
  2897. */
  2898. let val = storage.get(name, null);
  2899. if (val != null) {
  2900. inputs[name].input.value = val;
  2901. } else {
  2902. storage.set(name, inputs[name].default);
  2903. inputs[name].input.value = inputs[name].default;
  2904. }
  2905. /**
  2906. * Tracing a field change event for a record in storage
  2907. * Отсеживание события изменения поля для записи в storage
  2908. */
  2909. inputs[name].input.dataset['name'] = name;
  2910. inputs[name].input.addEventListener('input', function () {
  2911. const inputName = this.dataset['name'];
  2912. let value = +this.value;
  2913. if (!value || Number.isNaN(value)) {
  2914. value = storage.get(inputName, inputs[inputName].default);
  2915. inputs[name].input.value = value;
  2916. }
  2917. storage.set(inputName, value);
  2918. })
  2919. }
  2920. const inputDetails2 = scriptMenu.addDetails(I18N('SAVING'));
  2921. for (let name in inputs2) {
  2922. inputs2[name].input = scriptMenu.addInputText(inputs2[name].title, false, inputDetails2);
  2923. /**
  2924. * Get inputText state from storage
  2925. * Получаем состояние inputText из storage
  2926. */
  2927. let val = storage.get(name, null);
  2928. if (val != null) {
  2929. inputs2[name].input.value = val;
  2930. } else {
  2931. storage.set(name, inputs2[name].default);
  2932. inputs2[name].input.value = inputs2[name].default;
  2933. }
  2934. /**
  2935. * Tracing a field change event for a record in storage
  2936. * Отсеживание события изменения поля для записи в storage
  2937. */
  2938. inputs2[name].input.dataset['name'] = name;
  2939. inputs2[name].input.addEventListener('input', function () {
  2940. const inputName = this.dataset['name'];
  2941. let value = +this.value;
  2942. if (!value || Number.isNaN(value)) {
  2943. value = storage.get(inputName, inputs2[inputName].default);
  2944. inputs2[name].input.value = value;
  2945. }
  2946. storage.set(inputName, value);
  2947. })
  2948. }
  2949. }
  2950.  
  2951. /**
  2952. * Sending a request
  2953. *
  2954. * Отправка запроса
  2955. */
  2956. function send(json, callback, pr) {
  2957. if (typeof json == 'string') {
  2958. json = JSON.parse(json);
  2959. }
  2960. for (const call of json.calls) {
  2961. if (!call?.context?.actionTs) {
  2962. call.context = {
  2963. actionTs: performance.now()
  2964. }
  2965. }
  2966. }
  2967. json = JSON.stringify(json);
  2968. /**
  2969. * We get the headlines of the previous intercepted request
  2970. * Получаем заголовки предыдущего перехваченого запроса
  2971. */
  2972. let headers = lastHeaders;
  2973. /**
  2974. * We increase the header of the query Certifier by 1
  2975. * Увеличиваем заголовок идетификатора запроса на 1
  2976. */
  2977. headers["X-Request-Id"]++;
  2978. /**
  2979. * We calculate the title with the signature
  2980. * Расчитываем заголовок с сигнатурой
  2981. */
  2982. headers["X-Auth-Signature"] = getSignature(headers, json);
  2983. /**
  2984. * Create a new ajax request
  2985. * Создаем новый AJAX запрос
  2986. */
  2987. let xhr = new XMLHttpRequest;
  2988. /**
  2989. * Indicate the previously saved URL for API queries
  2990. * Указываем ранее сохраненный URL для API запросов
  2991. */
  2992. xhr.open('POST', apiUrl, true);
  2993. /**
  2994. * Add the function to the event change event
  2995. * Добавляем функцию к событию смены статуса запроса
  2996. */
  2997. xhr.onreadystatechange = function() {
  2998. /**
  2999. * If the result of the request is obtained, we call the flask function
  3000. * Если результат запроса получен вызываем колбек функцию
  3001. */
  3002. if(xhr.readyState == 4) {
  3003. let randTimeout = Math.random() * 200 + 200;
  3004. setTimeout(callback, randTimeout, xhr.response, pr);
  3005. }
  3006. };
  3007. /**
  3008. * Indicate the type of request
  3009. * Указываем тип запроса
  3010. */
  3011. xhr.responseType = 'json';
  3012. /**
  3013. * We set the request headers
  3014. * Задаем заголовки запроса
  3015. */
  3016. for(let nameHeader in headers) {
  3017. let head = headers[nameHeader];
  3018. xhr.setRequestHeader(nameHeader, head);
  3019. }
  3020. /**
  3021. * Sending a request
  3022. * Отправляем запрос
  3023. */
  3024. xhr.send(json);
  3025. }
  3026.  
  3027. let hideTimeoutProgress = 0;
  3028. /**
  3029. * Hide progress
  3030. *
  3031. * Скрыть прогресс
  3032. */
  3033. function hideProgress(timeout) {
  3034. timeout = timeout || 0;
  3035. clearTimeout(hideTimeoutProgress);
  3036. hideTimeoutProgress = setTimeout(function () {
  3037. scriptMenu.setStatus('');
  3038. }, timeout);
  3039. }
  3040. /**
  3041. * Progress display
  3042. *
  3043. * Отображение прогресса
  3044. */
  3045. function setProgress(text, hide, onclick) {
  3046. scriptMenu.setStatus(text, onclick);
  3047. hide = hide || false;
  3048. if (hide) {
  3049. hideProgress(3000);
  3050. }
  3051. }
  3052.  
  3053. /**
  3054. * Returns the timer value depending on the subscription
  3055. *
  3056. * Возвращает значение таймера в зависимости от подписки
  3057. */
  3058. function getTimer(time) {
  3059. let speedDiv = 5;
  3060. if (subEndTime < Date.now()) {
  3061. speedDiv = 1.5;
  3062. }
  3063. return Math.max(time / speedDiv + 1.5, 4);
  3064. }
  3065.  
  3066.  
  3067. /**
  3068. * Calculates HASH MD5 from string
  3069. *
  3070. * Расчитывает HASH MD5 из строки
  3071. *
  3072. * [js-md5]{@link https://github.com/emn178/js-md5}
  3073. *
  3074. * @namespace md5
  3075. * @version 0.7.3
  3076. * @author Chen, Yi-Cyuan [emn178@gmail.com]
  3077. * @copyright Chen, Yi-Cyuan 2014-2017
  3078. * @license MIT
  3079. */
  3080. !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 _}))}();
  3081.  
  3082. /**
  3083. * Script for beautiful dialog boxes
  3084. *
  3085. * Скрипт для красивых диалоговых окошек
  3086. */
  3087. const popup = new (function () {
  3088. this.popUp,
  3089. this.downer,
  3090. this.middle,
  3091. this.msgText,
  3092. this.buttons = [];
  3093. this.checkboxes = [];
  3094.  
  3095. function init() {
  3096. addStyle();
  3097. addBlocks();
  3098. }
  3099.  
  3100. const addStyle = () => {
  3101. let style = document.createElement('style');
  3102. style.innerText = `
  3103. .PopUp_ {
  3104. position: absolute;
  3105. min-width: 300px;
  3106. max-width: 500px;
  3107. max-height: 500px;
  3108. background-color: #190e08e6;
  3109. z-index: 10001;
  3110. top: 169px;
  3111. left: 345px;
  3112. border: 3px #ce9767 solid;
  3113. border-radius: 10px;
  3114. display: flex;
  3115. flex-direction: column;
  3116. justify-content: space-around;
  3117. padding: 15px 12px;
  3118. }
  3119.  
  3120. .PopUp_back {
  3121. position: absolute;
  3122. background-color: #00000066;
  3123. width: 100%;
  3124. height: 100%;
  3125. z-index: 10000;
  3126. top: 0;
  3127. left: 0;
  3128. }
  3129.  
  3130. .PopUp_close {
  3131. width: 40px;
  3132. height: 40px;
  3133. position: absolute;
  3134. right: -18px;
  3135. top: -18px;
  3136. border: 3px solid #c18550;
  3137. border-radius: 20px;
  3138. background: radial-gradient(circle, rgba(190,30,35,1) 0%, rgba(0,0,0,1) 100%);
  3139. background-position-y: 3px;
  3140. box-shadow: -1px 1px 3px black;
  3141. cursor: pointer;
  3142. box-sizing: border-box;
  3143. }
  3144.  
  3145. .PopUp_close:hover {
  3146. filter: brightness(1.2);
  3147. }
  3148.  
  3149. .PopUp_crossClose {
  3150. width: 100%;
  3151. height: 100%;
  3152. background-size: 65%;
  3153. background-position: center;
  3154. background-repeat: no-repeat;
  3155. 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")
  3156. }
  3157.  
  3158. .PopUp_blocks {
  3159. width: 100%;
  3160. height: 50%;
  3161. display: flex;
  3162. justify-content: space-evenly;
  3163. align-items: center;
  3164. flex-wrap: wrap;
  3165. justify-content: center;
  3166. }
  3167.  
  3168. .PopUp_blocks:last-child {
  3169. margin-top: 25px;
  3170. }
  3171.  
  3172. .PopUp_buttons {
  3173. display: flex;
  3174. margin: 10px 12px;
  3175. flex-direction: column;
  3176. }
  3177.  
  3178. .PopUp_button {
  3179. background-color: #52A81C;
  3180. border-radius: 5px;
  3181. box-shadow: inset 0px -4px 10px, inset 0px 3px 2px #99fe20, 0px 0px 4px, 0px -3px 1px #d7b275, 0px 0px 0px 3px #ce9767;
  3182. cursor: pointer;
  3183. padding: 5px 15px 7px;
  3184. }
  3185.  
  3186. .PopUp_input {
  3187. text-align: center;
  3188. font-size: 16px;
  3189. height: 27px;
  3190. border: 1px solid #cf9250;
  3191. border-radius: 9px 9px 0px 0px;
  3192. background: transparent;
  3193. color: #fce1ac;
  3194. padding: 1px 10px;
  3195. box-sizing: border-box;
  3196. box-shadow: 0px 0px 4px, 0px 0px 0px 3px #ce9767;
  3197. }
  3198.  
  3199. .PopUp_checkboxes {
  3200. display: flex;
  3201. flex-direction: column;
  3202. margin: 15px 15px -5px 15px;
  3203. align-items: flex-start;
  3204. }
  3205.  
  3206. .PopUp_ContCheckbox {
  3207. margin: 2px 0px;
  3208. }
  3209.  
  3210. .PopUp_checkbox {
  3211. position: absolute;
  3212. z-index: -1;
  3213. opacity: 0;
  3214. }
  3215. .PopUp_checkbox+label {
  3216. display: inline-flex;
  3217. align-items: center;
  3218. user-select: none;
  3219.  
  3220. font-size: 15px;
  3221. font-family: sans-serif;
  3222. font-weight: 600;
  3223. font-stretch: condensed;
  3224. letter-spacing: 1px;
  3225. color: #fce1ac;
  3226. text-shadow: 0px 0px 1px;
  3227. }
  3228. .PopUp_checkbox+label::before {
  3229. content: '';
  3230. display: inline-block;
  3231. width: 20px;
  3232. height: 20px;
  3233. border: 1px solid #cf9250;
  3234. border-radius: 7px;
  3235. margin-right: 7px;
  3236. }
  3237. .PopUp_checkbox:checked+label::before {
  3238. 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");
  3239. }
  3240.  
  3241. .PopUp_input::placeholder {
  3242. color: #fce1ac75;
  3243. }
  3244.  
  3245. .PopUp_input:focus {
  3246. outline: 0;
  3247. }
  3248.  
  3249. .PopUp_input + .PopUp_button {
  3250. border-radius: 0px 0px 5px 5px;
  3251. padding: 2px 18px 5px;
  3252. }
  3253.  
  3254. .PopUp_button:hover {
  3255. filter: brightness(1.2);
  3256. }
  3257.  
  3258. .PopUp_text {
  3259. font-size: 22px;
  3260. font-family: sans-serif;
  3261. font-weight: 600;
  3262. font-stretch: condensed;
  3263. white-space: pre-wrap;
  3264. letter-spacing: 1px;
  3265. text-align: center;
  3266. }
  3267.  
  3268. .PopUp_buttonText {
  3269. color: #E4FF4C;
  3270. text-shadow: 0px 1px 2px black;
  3271. }
  3272.  
  3273. .PopUp_msgText {
  3274. color: #FDE5B6;
  3275. text-shadow: 0px 0px 2px;
  3276. }
  3277.  
  3278. .PopUp_hideBlock {
  3279. display: none;
  3280. }
  3281. `;
  3282. document.head.appendChild(style);
  3283. }
  3284.  
  3285. const addBlocks = () => {
  3286. this.back = document.createElement('div');
  3287. this.back.classList.add('PopUp_back');
  3288. this.back.classList.add('PopUp_hideBlock');
  3289. document.body.append(this.back);
  3290.  
  3291. this.popUp = document.createElement('div');
  3292. this.popUp.classList.add('PopUp_');
  3293. this.back.append(this.popUp);
  3294.  
  3295. let upper = document.createElement('div')
  3296. upper.classList.add('PopUp_blocks');
  3297. this.popUp.append(upper);
  3298.  
  3299. this.middle = document.createElement('div')
  3300. this.middle.classList.add('PopUp_blocks');
  3301. this.middle.classList.add('PopUp_checkboxes');
  3302. this.popUp.append(this.middle);
  3303.  
  3304. this.downer = document.createElement('div')
  3305. this.downer.classList.add('PopUp_blocks');
  3306. this.popUp.append(this.downer);
  3307.  
  3308. this.msgText = document.createElement('div');
  3309. this.msgText.classList.add('PopUp_text', 'PopUp_msgText');
  3310. upper.append(this.msgText);
  3311. }
  3312.  
  3313. this.showBack = function () {
  3314. this.back.classList.remove('PopUp_hideBlock');
  3315. }
  3316.  
  3317. this.hideBack = function () {
  3318. this.back.classList.add('PopUp_hideBlock');
  3319. }
  3320.  
  3321. this.show = function () {
  3322. if (this.checkboxes.length) {
  3323. this.middle.classList.remove('PopUp_hideBlock');
  3324. }
  3325. this.showBack();
  3326. this.popUp.classList.remove('PopUp_hideBlock');
  3327. this.popUp.style.left = (window.innerWidth - this.popUp.offsetWidth) / 2 + 'px';
  3328. this.popUp.style.top = (window.innerHeight - this.popUp.offsetHeight) / 3 + 'px';
  3329. }
  3330.  
  3331. this.hide = function () {
  3332. this.hideBack();
  3333. this.popUp.classList.add('PopUp_hideBlock');
  3334. }
  3335.  
  3336. this.addAnyButton = (option) => {
  3337. const contButton = document.createElement('div');
  3338. contButton.classList.add('PopUp_buttons');
  3339. this.downer.append(contButton);
  3340.  
  3341. let inputField = {
  3342. value: option.result || option.default
  3343. }
  3344. if (option.isInput) {
  3345. inputField = document.createElement('input');
  3346. inputField.type = 'text';
  3347. if (option.placeholder) {
  3348. inputField.placeholder = option.placeholder;
  3349. }
  3350. if (option.default) {
  3351. inputField.value = option.default;
  3352. }
  3353. inputField.classList.add('PopUp_input');
  3354. contButton.append(inputField);
  3355. }
  3356.  
  3357. const button = document.createElement('div');
  3358. button.classList.add('PopUp_button');
  3359. button.title = option.title || '';
  3360. contButton.append(button);
  3361.  
  3362. const buttonText = document.createElement('div');
  3363. buttonText.classList.add('PopUp_text', 'PopUp_buttonText');
  3364. buttonText.innerText = option.msg;
  3365. button.append(buttonText);
  3366.  
  3367. return { button, contButton, inputField };
  3368. }
  3369.  
  3370. this.addCloseButton = () => {
  3371. let button = document.createElement('div')
  3372. button.classList.add('PopUp_close');
  3373. this.popUp.append(button);
  3374.  
  3375. let crossClose = document.createElement('div')
  3376. crossClose.classList.add('PopUp_crossClose');
  3377. button.append(crossClose);
  3378.  
  3379. return { button, contButton: button };
  3380. }
  3381.  
  3382. this.addButton = (option, buttonClick) => {
  3383.  
  3384. const { button, contButton, inputField } = option.isClose ? this.addCloseButton() : this.addAnyButton(option);
  3385.  
  3386. button.addEventListener('click', () => {
  3387. let result = '';
  3388. if (option.isInput) {
  3389. result = inputField.value;
  3390. }
  3391. buttonClick(result);
  3392. });
  3393.  
  3394. this.buttons.push(contButton);
  3395. }
  3396.  
  3397. this.clearButtons = () => {
  3398. while (this.buttons.length) {
  3399. this.buttons.pop().remove();
  3400. }
  3401. }
  3402.  
  3403. this.addCheckBox = (checkBox) => {
  3404. const contCheckbox = document.createElement('div');
  3405. contCheckbox.classList.add('PopUp_ContCheckbox');
  3406. this.middle.append(contCheckbox);
  3407.  
  3408. const checkbox = document.createElement('input');
  3409. checkbox.type = 'checkbox';
  3410. checkbox.id = 'PopUpCheckbox' + this.checkboxes.length;
  3411. checkbox.dataset.name = checkBox.name;
  3412. checkbox.checked = checkBox.checked;
  3413. checkbox.label = checkBox.label;
  3414. checkbox.title = checkBox.title || '';
  3415. checkbox.classList.add('PopUp_checkbox');
  3416. contCheckbox.appendChild(checkbox)
  3417.  
  3418. const checkboxLabel = document.createElement('label');
  3419. checkboxLabel.innerText = checkBox.label;
  3420. checkboxLabel.title = checkBox.title || '';
  3421. checkboxLabel.setAttribute('for', checkbox.id);
  3422. contCheckbox.appendChild(checkboxLabel);
  3423.  
  3424. this.checkboxes.push(checkbox);
  3425. }
  3426.  
  3427. this.clearCheckBox = () => {
  3428. this.middle.classList.add('PopUp_hideBlock');
  3429. while (this.checkboxes.length) {
  3430. this.checkboxes.pop().parentNode.remove();
  3431. }
  3432. }
  3433.  
  3434. this.setMsgText = (text) => {
  3435. this.msgText.innerHTML = text;
  3436. }
  3437.  
  3438. this.getCheckBoxes = () => {
  3439. const checkBoxes = [];
  3440.  
  3441. for (const checkBox of this.checkboxes) {
  3442. checkBoxes.push({
  3443. name: checkBox.dataset.name,
  3444. label: checkBox.label,
  3445. checked: checkBox.checked
  3446. });
  3447. }
  3448.  
  3449. return checkBoxes;
  3450. }
  3451.  
  3452. this.confirm = async (msg, buttOpt, checkBoxes = []) => {
  3453. this.clearButtons();
  3454. this.clearCheckBox();
  3455. return new Promise((complete, failed) => {
  3456. this.setMsgText(msg);
  3457. if (!buttOpt) {
  3458. buttOpt = [{ msg: 'Ok', result: true, isInput: false }];
  3459. }
  3460. for (const checkBox of checkBoxes) {
  3461. this.addCheckBox(checkBox);
  3462. }
  3463. for (let butt of buttOpt) {
  3464. this.addButton(butt, (result) => {
  3465. result = result || butt.result;
  3466. complete(result);
  3467. popup.hide();
  3468. });
  3469. }
  3470. this.show();
  3471. });
  3472. }
  3473.  
  3474. document.addEventListener('DOMContentLoaded', init);
  3475. });
  3476. /**
  3477. * Script control panel
  3478. *
  3479. * Панель управления скриптом
  3480. */
  3481. const scriptMenu = new (function () {
  3482.  
  3483. this.mainMenu,
  3484. this.buttons = [],
  3485. this.checkboxes = [];
  3486. this.option = {
  3487. showMenu: false,
  3488. showDetails: {}
  3489. };
  3490.  
  3491. this.init = function (option = {}) {
  3492. this.option = Object.assign(this.option, option);
  3493. this.option.showDetails = this.loadShowDetails();
  3494. addStyle();
  3495. addBlocks();
  3496. }
  3497.  
  3498. const addStyle = () => {
  3499. style = document.createElement('style');
  3500. style.innerText = `
  3501. .scriptMenu_status {
  3502. position: absolute;
  3503. z-index: 10001;
  3504. white-space: pre-wrap; //тест для выравнивания кнопок
  3505. /* max-height: 30px; */
  3506. top: -1px;
  3507. left: 30%;
  3508. cursor: pointer;
  3509. border-radius: 0px 0px 10px 10px;
  3510. background: #190e08e6;
  3511. border: 1px #ce9767 solid;
  3512. font-size: 18px;
  3513. font-family: sans-serif;
  3514. font-weight: 600;
  3515. font-stretch: condensed;
  3516. letter-spacing: 1px;
  3517. color: #fce1ac;
  3518. text-shadow: 0px 0px 1px;
  3519. transition: 0.5s;
  3520. padding: 2px 10px 3px;
  3521. }
  3522. .scriptMenu_statusHide {
  3523. top: -35px;
  3524. height: 30px;
  3525. overflow: hidden;
  3526. }
  3527. .scriptMenu_label {
  3528. position: absolute;
  3529. top: 30%;
  3530. left: -4px;
  3531. z-index: 9999;
  3532. cursor: pointer;
  3533. width: 30px;
  3534. height: 30px;
  3535. background: radial-gradient(circle, #47a41b 0%, #1a2f04 100%);
  3536. border: 1px solid #1a2f04;
  3537. border-radius: 5px;
  3538. box-shadow:
  3539. inset 0px 2px 4px #83ce26,
  3540. inset 0px -4px 6px #1a2f04,
  3541. 0px 0px 2px black,
  3542. 0px 0px 0px 2px #ce9767;
  3543. }
  3544. .scriptMenu_label:hover {
  3545. filter: brightness(1.2);
  3546. }
  3547. .scriptMenu_arrowLabel {
  3548. width: 100%;
  3549. height: 100%;
  3550. background-size: 75%;
  3551. background-position: center;
  3552. background-repeat: no-repeat;
  3553. 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");
  3554. box-shadow: 0px 1px 2px #000;
  3555. border-radius: 5px;
  3556. filter: drop-shadow(0px 1px 2px #000D);
  3557. }
  3558. .scriptMenu_main {
  3559. position: absolute;
  3560. max-width: 285px;
  3561. z-index: 9999;
  3562. top: 50%;
  3563. transform: translateY(-50%);
  3564. background: #190e08e6;
  3565. border: 1px #ce9767 solid;
  3566. border-radius: 0px 10px 10px 0px;
  3567. border-left: none;
  3568. padding: 5px 10px 5px 5px;
  3569. box-sizing: border-box;
  3570. font-size: 15px;
  3571. font-family: sans-serif;
  3572. font-weight: 600;
  3573. font-stretch: condensed;
  3574. letter-spacing: 1px;
  3575. color: #fce1ac;
  3576. text-shadow: 0px 0px 1px;
  3577. transition: 1s;
  3578. display: flex;
  3579. flex-direction: column;
  3580. flex-wrap: nowrap;
  3581. }
  3582. .scriptMenu_showMenu {
  3583. display: none;
  3584. }
  3585. .scriptMenu_showMenu:checked~.scriptMenu_main {
  3586. left: 0px;
  3587. }
  3588. .scriptMenu_showMenu:not(:checked)~.scriptMenu_main {
  3589. left: -300px;
  3590. }
  3591. .scriptMenu_divInput {
  3592. margin: 2px;
  3593. }
  3594. .scriptMenu_divInputText {
  3595. margin: 2px;
  3596. align-self: center;
  3597. display: flex;
  3598. }
  3599. .scriptMenu_checkbox {
  3600. position: absolute;
  3601. z-index: -1;
  3602. opacity: 0;
  3603. }
  3604. .scriptMenu_checkbox+label {
  3605. display: inline-flex;
  3606. align-items: center;
  3607. user-select: none;
  3608. }
  3609. .scriptMenu_checkbox+label::before {
  3610. content: '';
  3611. display: inline-block;
  3612. width: 20px;
  3613. height: 20px;
  3614. border: 1px solid #cf9250;
  3615. border-radius: 7px;
  3616. margin-right: 7px;
  3617. }
  3618. .scriptMenu_checkbox:checked+label::before {
  3619. 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");
  3620. }
  3621. .scriptMenu_close {
  3622. width: 40px;
  3623. height: 40px;
  3624. position: absolute;
  3625. right: -18px;
  3626. top: -18px;
  3627. border: 3px solid #c18550;
  3628. border-radius: 20px;
  3629. background: radial-gradient(circle, rgba(190,30,35,1) 0%, rgba(0,0,0,1) 100%);
  3630. background-position-y: 3px;
  3631. box-shadow: -1px 1px 3px black;
  3632. cursor: pointer;
  3633. box-sizing: border-box;
  3634. }
  3635. .scriptMenu_close:hover {
  3636. filter: brightness(1.2);
  3637. }
  3638. .scriptMenu_crossClose {
  3639. width: 100%;
  3640. height: 100%;
  3641. background-size: 65%;
  3642. background-position: center;
  3643. background-repeat: no-repeat;
  3644. 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")
  3645. }
  3646. .scriptMenu_button {
  3647. user-select: none;
  3648. border-radius: 5px;
  3649. cursor: pointer;
  3650. padding: 5px 14px 8px;
  3651. margin: 4px;
  3652. background: radial-gradient(circle, rgba(165,120,56,1) 80%, rgba(0,0,0,1) 110%);
  3653. box-shadow: inset 0px -4px 6px #442901, inset 0px 1px 6px #442901, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 2px #ce9767;
  3654. }
  3655. .scriptMenu_button:hover {
  3656. filter: brightness(1.2);
  3657. }
  3658. .scriptMenu_buttonText {
  3659. color: #fce5b7;
  3660. text-shadow: 0px 1px 2px black;
  3661. text-align: center;
  3662. }
  3663. .scriptMenu_header {
  3664. text-align: center;
  3665. align-self: center;
  3666. font-size: 15px;
  3667. margin: 0px 15px;
  3668. }
  3669. .scriptMenu_header a {
  3670. color: #fce5b7;
  3671. text-decoration: none;
  3672. }
  3673. .scriptMenu_InputText {
  3674. text-align: center;
  3675. width: 130px;
  3676. height: 24px;
  3677. border: 1px solid #cf9250;
  3678. border-radius: 9px;
  3679. background: transparent;
  3680. color: #fce1ac;
  3681. padding: 0px 10px;
  3682. box-sizing: border-box;
  3683. }
  3684. .scriptMenu_InputText:focus {
  3685. filter: brightness(1.2);
  3686. outline: 0;
  3687. }
  3688. .scriptMenu_InputText::placeholder {
  3689. color: #fce1ac75;
  3690. }
  3691. .scriptMenu_Summary {
  3692. cursor: pointer;
  3693. margin-left: 7px;
  3694. }
  3695. .scriptMenu_Details {
  3696. align-self: center;
  3697. }
  3698. `;
  3699. document.head.appendChild(style);
  3700. }
  3701.  
  3702. const addBlocks = () => {
  3703. const main = document.createElement('div');
  3704. document.body.appendChild(main);
  3705.  
  3706. this.status = document.createElement('div');
  3707. this.status.classList.add('scriptMenu_status');
  3708. this.setStatus('');
  3709. main.appendChild(this.status);
  3710.  
  3711. const label = document.createElement('label');
  3712. label.classList.add('scriptMenu_label');
  3713. label.setAttribute('for', 'checkbox_showMenu');
  3714. main.appendChild(label);
  3715.  
  3716. const arrowLabel = document.createElement('div');
  3717. arrowLabel.classList.add('scriptMenu_arrowLabel');
  3718. label.appendChild(arrowLabel);
  3719.  
  3720. const checkbox = document.createElement('input');
  3721. checkbox.type = 'checkbox';
  3722. checkbox.id = 'checkbox_showMenu';
  3723. checkbox.checked = this.option.showMenu;
  3724. checkbox.classList.add('scriptMenu_showMenu');
  3725. main.appendChild(checkbox);
  3726.  
  3727. this.mainMenu = document.createElement('div');
  3728. this.mainMenu.classList.add('scriptMenu_main');
  3729. main.appendChild(this.mainMenu);
  3730.  
  3731. const closeButton = document.createElement('label');
  3732. closeButton.classList.add('scriptMenu_close');
  3733. closeButton.setAttribute('for', 'checkbox_showMenu');
  3734. this.mainMenu.appendChild(closeButton);
  3735.  
  3736. const crossClose = document.createElement('div');
  3737. crossClose.classList.add('scriptMenu_crossClose');
  3738. closeButton.appendChild(crossClose);
  3739. }
  3740.  
  3741. this.setStatus = (text, onclick) => {
  3742. if (!text) {
  3743. this.status.classList.add('scriptMenu_statusHide');
  3744. } else {
  3745. this.status.classList.remove('scriptMenu_statusHide');
  3746. this.status.innerHTML = text;
  3747. }
  3748.  
  3749. if (typeof onclick == 'function') {
  3750. this.status.addEventListener("click", onclick, {
  3751. once: true
  3752. });
  3753. }
  3754. }
  3755.  
  3756. /**
  3757. * Adding a text element
  3758. *
  3759. * Добавление текстового элемента
  3760. * @param {String} text text // текст
  3761. * @param {Function} func Click function // функция по клику
  3762. * @param {HTMLDivElement} main parent // родитель
  3763. */
  3764. this.addHeader = (text, func, main) => {
  3765. main = main || this.mainMenu;
  3766. const header = document.createElement('div');
  3767. header.classList.add('scriptMenu_header');
  3768. header.innerHTML = text;
  3769. if (typeof func == 'function') {
  3770. header.addEventListener('click', func);
  3771. }
  3772. main.appendChild(header);
  3773. }
  3774.  
  3775. /**
  3776. * Adding a button
  3777. *
  3778. * Добавление кнопки
  3779. * @param {String} text
  3780. * @param {Function} func
  3781. * @param {String} title
  3782. * @param {HTMLDivElement} main parent // родитель
  3783. */
  3784. this.addButton = (text, func, title, main) => {
  3785. main = main || this.mainMenu;
  3786. const button = document.createElement('div');
  3787. button.classList.add('scriptMenu_button');
  3788. button.title = title;
  3789. button.addEventListener('click', func);
  3790. main.appendChild(button);
  3791.  
  3792. const buttonText = document.createElement('div');
  3793. buttonText.classList.add('scriptMenu_buttonText');
  3794. buttonText.innerText = text;
  3795. button.appendChild(buttonText);
  3796. this.buttons.push(button);
  3797.  
  3798. return button;
  3799. }
  3800.  
  3801. /**
  3802. * Adding checkbox
  3803. *
  3804. * Добавление чекбокса
  3805. * @param {String} label
  3806. * @param {String} title
  3807. * @param {HTMLDivElement} main parent // родитель
  3808. * @returns
  3809. */
  3810. this.addCheckbox = (label, title, main) => {
  3811. main = main || this.mainMenu;
  3812. const divCheckbox = document.createElement('div');
  3813. divCheckbox.classList.add('scriptMenu_divInput');
  3814. divCheckbox.title = title;
  3815. main.appendChild(divCheckbox);
  3816.  
  3817. const checkbox = document.createElement('input');
  3818. checkbox.type = 'checkbox';
  3819. checkbox.id = 'scriptMenuCheckbox' + this.checkboxes.length;
  3820. checkbox.classList.add('scriptMenu_checkbox');
  3821. divCheckbox.appendChild(checkbox)
  3822.  
  3823. const checkboxLabel = document.createElement('label');
  3824. checkboxLabel.innerText = label;
  3825. checkboxLabel.setAttribute('for', checkbox.id);
  3826. divCheckbox.appendChild(checkboxLabel);
  3827.  
  3828. this.checkboxes.push(checkbox);
  3829. return checkbox;
  3830. }
  3831.  
  3832. /**
  3833. * Adding input field
  3834. *
  3835. * Добавление поля ввода
  3836. * @param {String} title
  3837. * @param {String} placeholder
  3838. * @param {HTMLDivElement} main parent // родитель
  3839. * @returns
  3840. */
  3841. this.addInputText = (title, placeholder, main) => {
  3842. main = main || this.mainMenu;
  3843. const divInputText = document.createElement('div');
  3844. divInputText.classList.add('scriptMenu_divInputText');
  3845. divInputText.title = title;
  3846. main.appendChild(divInputText);
  3847.  
  3848. const newInputText = document.createElement('input');
  3849. newInputText.type = 'text';
  3850. if (placeholder) {
  3851. newInputText.placeholder = placeholder;
  3852. }
  3853. newInputText.classList.add('scriptMenu_InputText');
  3854. divInputText.appendChild(newInputText)
  3855. return newInputText;
  3856. }
  3857.  
  3858. /**
  3859. * Adds a dropdown block
  3860. *
  3861. * Добавляет раскрывающийся блок
  3862. * @param {String} summary
  3863. * @param {String} name
  3864. * @returns
  3865. */
  3866. this.addDetails = (summaryText, name = null) => {
  3867. const details = document.createElement('details');
  3868. details.classList.add('scriptMenu_Details');
  3869. this.mainMenu.appendChild(details);
  3870.  
  3871. const summary = document.createElement('summary');
  3872. summary.classList.add('scriptMenu_Summary');
  3873. summary.innerText = summaryText;
  3874. if (name) {
  3875. const self = this;
  3876. details.open = this.option.showDetails[name];
  3877. details.dataset.name = name;
  3878. summary.addEventListener('click', () => {
  3879. self.option.showDetails[details.dataset.name] = !details.open;
  3880. self.saveShowDetails(self.option.showDetails);
  3881. });
  3882. }
  3883. details.appendChild(summary);
  3884.  
  3885. return details;
  3886. }
  3887.  
  3888. /**
  3889. * Saving the expanded state of the details blocks
  3890. *
  3891. * Сохранение состояния развенутости блоков details
  3892. * @param {*} value
  3893. */
  3894. this.saveShowDetails = (value) => {
  3895. localStorage.setItem('scriptMenu_showDetails', JSON.stringify(value));
  3896. }
  3897.  
  3898. /**
  3899. * Loading the state of expanded blocks details
  3900. *
  3901. * Загрузка состояния развенутости блоков details
  3902. * @returns
  3903. */
  3904. this.loadShowDetails = () => {
  3905. let showDetails = localStorage.getItem('scriptMenu_showDetails');
  3906.  
  3907. if (!showDetails) {
  3908. return {};
  3909. }
  3910.  
  3911. try {
  3912. showDetails = JSON.parse(showDetails);
  3913. } catch (e) {
  3914. return {};
  3915. }
  3916.  
  3917. return showDetails;
  3918. }
  3919. });
  3920. /**
  3921. * Game Library
  3922. *
  3923. * Игровая библиотека
  3924. */
  3925. class Library {
  3926. defaultLibUrl = 'https://heroesru-a.akamaihd.net/vk/v1074/lib/lib.json';
  3927.  
  3928. constructor() {
  3929. if (!Library.instance) {
  3930. Library.instance = this;
  3931. }
  3932.  
  3933. return Library.instance;
  3934. }
  3935.  
  3936. async load(data) {
  3937. if (data) {
  3938. this.data = data;
  3939. return;
  3940. }
  3941. try {
  3942. this.data = await fetch(this.defaultLibUrl).then(e => e.json())
  3943. } catch (error) {
  3944. console.error('Не удалось загрузить библиотеку')
  3945. }
  3946. }
  3947.  
  3948. getData(id) {
  3949. return this.data[id];
  3950. }
  3951. }
  3952.  
  3953. this.lib = new Library();
  3954. /**
  3955. * Database
  3956. *
  3957. * База данных
  3958. */
  3959. class Database {
  3960. constructor(dbName, storeName) {
  3961. this.dbName = dbName;
  3962. this.storeName = storeName;
  3963. this.db = null;
  3964. }
  3965.  
  3966. async open() {
  3967. return new Promise((resolve, reject) => {
  3968. const request = indexedDB.open(this.dbName);
  3969.  
  3970. request.onerror = () => {
  3971. reject(new Error(`Failed to open database ${this.dbName}`));
  3972. };
  3973.  
  3974. request.onsuccess = () => {
  3975. this.db = request.result;
  3976. resolve();
  3977. };
  3978.  
  3979. request.onupgradeneeded = (event) => {
  3980. const db = event.target.result;
  3981. if (!db.objectStoreNames.contains(this.storeName)) {
  3982. db.createObjectStore(this.storeName);
  3983. }
  3984. };
  3985. });
  3986. }
  3987.  
  3988. async set(key, value) {
  3989. return new Promise((resolve, reject) => {
  3990. const transaction = this.db.transaction([this.storeName], 'readwrite');
  3991. const store = transaction.objectStore(this.storeName);
  3992. const request = store.put(value, key);
  3993.  
  3994. request.onerror = () => {
  3995. reject(new Error(`Failed to save value with key ${key}`));
  3996. };
  3997.  
  3998. request.onsuccess = () => {
  3999. resolve();
  4000. };
  4001. });
  4002. }
  4003.  
  4004. async get(key, def) {
  4005. return new Promise((resolve, reject) => {
  4006. const transaction = this.db.transaction([this.storeName], 'readonly');
  4007. const store = transaction.objectStore(this.storeName);
  4008. const request = store.get(key);
  4009.  
  4010. request.onerror = () => {
  4011. resolve(def);
  4012. };
  4013.  
  4014. request.onsuccess = () => {
  4015. resolve(request.result);
  4016. };
  4017. });
  4018. }
  4019.  
  4020. async delete(key) {
  4021. return new Promise((resolve, reject) => {
  4022. const transaction = this.db.transaction([this.storeName], 'readwrite');
  4023. const store = transaction.objectStore(this.storeName);
  4024. const request = store.delete(key);
  4025.  
  4026. request.onerror = () => {
  4027. reject(new Error(`Failed to delete value with key ${key}`));
  4028. };
  4029.  
  4030. request.onsuccess = () => {
  4031. resolve();
  4032. };
  4033. });
  4034. }
  4035. }
  4036.  
  4037. /**
  4038. * Returns the stored value
  4039. *
  4040. * Возвращает сохраненное значение
  4041. */
  4042. function getSaveVal(saveName, def) {
  4043. const result = storage.get(saveName, def);
  4044. return result;
  4045. }
  4046.  
  4047. /**
  4048. * Stores value
  4049. *
  4050. * Сохраняет значение
  4051. */
  4052. function setSaveVal(saveName, value) {
  4053. storage.set(saveName, value);
  4054. }
  4055.  
  4056. /**
  4057. * Database initialization
  4058. *
  4059. * Инициализация базы данных
  4060. */
  4061. const db = new Database(GM_info.script.name, 'settings');
  4062.  
  4063. /**
  4064. * Data store
  4065. *
  4066. * Хранилище данных
  4067. */
  4068. const storage = {
  4069. userId: 0,
  4070. /**
  4071. * Default values
  4072. *
  4073. * Значения по умолчанию
  4074. */
  4075. values: [
  4076. ...Object.entries(checkboxes).map(e => ({ [e[0]]: e[1].default })),
  4077. ...Object.entries(inputs).map(e => ({ [e[0]]: e[1].default })),
  4078. ...Object.entries(inputs2).map(e => ({ [e[0]]: e[1].default })),
  4079. ].reduce((acc, obj) => ({ ...acc, ...obj }), {}),
  4080. name: GM_info.script.name,
  4081. get: function (key, def) {
  4082. if (key in this.values) {
  4083. return this.values[key];
  4084. }
  4085. return def;
  4086. },
  4087. set: function (key, value) {
  4088. this.values[key] = value;
  4089. db.set(this.userId, this.values).catch(
  4090. e => null
  4091. );
  4092. localStorage[this.name + ':' + key] = value;
  4093. },
  4094. delete: function (key) {
  4095. delete this.values[key];
  4096. db.set(this.userId, this.values);
  4097. delete localStorage[this.name + ':' + key];
  4098. }
  4099. }
  4100.  
  4101. /**
  4102. * Returns all keys from localStorage that start with prefix (for migration)
  4103. *
  4104. * Возвращает все ключи из localStorage которые начинаются с prefix (для миграции)
  4105. */
  4106. function getAllValuesStartingWith(prefix) {
  4107. const values = [];
  4108. for (let i = 0; i < localStorage.length; i++) {
  4109. const key = localStorage.key(i);
  4110. if (key.startsWith(prefix)) {
  4111. const val = localStorage.getItem(key);
  4112. const keyValue = key.split(':')[1];
  4113. values.push({ key: keyValue, val });
  4114. }
  4115. }
  4116. return values;
  4117. }
  4118.  
  4119. /**
  4120. * Opens or migrates to a database
  4121. *
  4122. * Открывает или мигрирует в базу данных
  4123. */
  4124. async function openOrMigrateDatabase(userId) {
  4125. storage.userId = userId;
  4126. try {
  4127. await db.open();
  4128. } catch(e) {
  4129. return;
  4130. }
  4131. let settings = await db.get(userId, false);
  4132.  
  4133. if (settings) {
  4134. storage.values = settings;
  4135. return;
  4136. }
  4137.  
  4138. const values = getAllValuesStartingWith(GM_info.script.name);
  4139. for (const value of values) {
  4140. let val = null;
  4141. try {
  4142. val = JSON.parse(value.val);
  4143. } catch {
  4144. break;
  4145. }
  4146. storage.values[value.key] = val;
  4147. }
  4148. await db.set(userId, storage.values);
  4149. }
  4150.  
  4151. /**
  4152. * Sending expeditions
  4153. *
  4154. * Отправка экспедиций
  4155. */
  4156. function checkExpedition() {
  4157. return new Promise((resolve, reject) => {
  4158. const expedition = new Expedition(resolve, reject);
  4159. expedition.start();
  4160. });
  4161. }
  4162.  
  4163. class Expedition {
  4164. checkExpedInfo = {
  4165. calls: [{
  4166. name: "expeditionGet",
  4167. args: {},
  4168. ident: "expeditionGet"
  4169. }, {
  4170. name: "heroGetAll",
  4171. args: {},
  4172. ident: "heroGetAll"
  4173. }]
  4174. }
  4175.  
  4176. constructor(resolve, reject) {
  4177. this.resolve = resolve;
  4178. this.reject = reject;
  4179. }
  4180.  
  4181. async start() {
  4182. const data = await Send(JSON.stringify(this.checkExpedInfo));
  4183.  
  4184. const expedInfo = data.results[0].result.response;
  4185. const dataHeroes = data.results[1].result.response;
  4186. const dataExped = { useHeroes: [], exped: [] };
  4187. const calls = [];
  4188.  
  4189. /**
  4190. * Adding expeditions to collect
  4191. * Добавляем экспедиции для сбора
  4192. */
  4193. for (var n in expedInfo) {
  4194. const exped = expedInfo[n];
  4195. const dateNow = (Date.now() / 1000);
  4196. if (exped.status == 2 && exped.endTime != 0 && dateNow > exped.endTime) {
  4197. calls.push({
  4198. name: "expeditionFarm",
  4199. args: { expeditionId: exped.id },
  4200. ident: "expeditionFarm_" + exped.id
  4201. });
  4202. } else {
  4203. dataExped.useHeroes = dataExped.useHeroes.concat(exped.heroes);
  4204. }
  4205. if (exped.status == 1) {
  4206. dataExped.exped.push({ id: exped.id, power: exped.power });
  4207. }
  4208. }
  4209. dataExped.exped = dataExped.exped.sort((a, b) => (b.power - a.power));
  4210.  
  4211. /**
  4212. * Putting together a list of heroes
  4213. * Собираем список героев
  4214. */
  4215. const heroesArr = [];
  4216. for (let n in dataHeroes) {
  4217. const hero = dataHeroes[n];
  4218. if (hero.xp > 0 && !dataExped.useHeroes.includes(hero.id)) {
  4219. heroesArr.push({ id: hero.id, power: hero.power })
  4220. }
  4221. }
  4222.  
  4223. /**
  4224. * Adding expeditions to send
  4225. * Добавляем экспедиции для отправки
  4226. */
  4227. heroesArr.sort((a, b) => (a.power - b.power));
  4228. for (const exped of dataExped.exped) {
  4229. let heroesIds = this.selectionHeroes(heroesArr, exped.power);
  4230. if (heroesIds && heroesIds.length > 4) {
  4231. for (let q in heroesArr) {
  4232. if (heroesIds.includes(heroesArr[q].id)) {
  4233. delete heroesArr[q];
  4234. }
  4235. }
  4236. calls.push({
  4237. name: "expeditionSendHeroes",
  4238. args: {
  4239. expeditionId: exped.id,
  4240. heroes: heroesIds
  4241. },
  4242. ident: "expeditionSendHeroes_" + exped.id
  4243. });
  4244. }
  4245. }
  4246.  
  4247. await Send(JSON.stringify({ calls }));
  4248. this.end();
  4249. }
  4250.  
  4251. /**
  4252. * Selection of heroes for expeditions
  4253. *
  4254. * Подбор героев для экспедиций
  4255. */
  4256. selectionHeroes(heroes, power) {
  4257. const resultHeroers = [];
  4258. const heroesIds = [];
  4259. for (let q = 0; q < 5; q++) {
  4260. for (let i in heroes) {
  4261. let hero = heroes[i];
  4262. if (heroesIds.includes(hero.id)) {
  4263. continue;
  4264. }
  4265.  
  4266. const summ = resultHeroers.reduce((acc, hero) => acc + hero.power, 0);
  4267. const need = Math.round((power - summ) / (5 - resultHeroers.length));
  4268. if (hero.power > need) {
  4269. resultHeroers.push(hero);
  4270. heroesIds.push(hero.id);
  4271. break;
  4272. }
  4273. }
  4274. }
  4275.  
  4276. const summ = resultHeroers.reduce((acc, hero) => acc + hero.power, 0);
  4277. if (summ < power) {
  4278. return false;
  4279. }
  4280. return heroesIds;
  4281. }
  4282.  
  4283. /**
  4284. * Ends expedition script
  4285. *
  4286. * Завершает скрипт экспедиции
  4287. */
  4288. end() {
  4289. setProgress(I18N('EXPEDITIONS_SENT'), true);
  4290. this.resolve()
  4291. }
  4292. }
  4293.  
  4294. /**
  4295. * Walkthrough of the dungeon
  4296. *
  4297. * Прохождение подземелья
  4298. */
  4299. function testDungeon() {
  4300. return new Promise((resolve, reject) => {
  4301. const dung = new executeDungeon(resolve, reject);
  4302. const titanit = getInput('countTitanit');
  4303. dung.start(titanit);
  4304. });
  4305. }
  4306.  
  4307. /**
  4308. * Walkthrough of the dungeon
  4309. *
  4310. * Прохождение подземелья
  4311. */
  4312. function executeDungeon(resolve, reject) {
  4313. dungeonActivity = 0;
  4314. maxDungeonActivity = 150;
  4315.  
  4316. titanGetAll = [];
  4317.  
  4318. teams = {
  4319. heroes: [],
  4320. earth: [],
  4321. fire: [],
  4322. neutral: [],
  4323. water: [],
  4324. }
  4325.  
  4326. titanStats = [];
  4327.  
  4328. titansStates = {};
  4329.  
  4330. callsExecuteDungeon = {
  4331. calls: [{
  4332. name: "dungeonGetInfo",
  4333. args: {},
  4334. ident: "dungeonGetInfo"
  4335. }, {
  4336. name: "teamGetAll",
  4337. args: {},
  4338. ident: "teamGetAll"
  4339. }, {
  4340. name: "teamGetFavor",
  4341. args: {},
  4342. ident: "teamGetFavor"
  4343. }, {
  4344. name: "clanGetInfo",
  4345. args: {},
  4346. ident: "clanGetInfo"
  4347. }, {
  4348. name: "titanGetAll",
  4349. args: {},
  4350. ident: "titanGetAll"
  4351. }, {
  4352. name: "inventoryGet",
  4353. args: {},
  4354. ident: "inventoryGet"
  4355. }]
  4356. }
  4357.  
  4358. this.start = function(titanit) {
  4359. maxDungeonActivity = titanit || getInput('countTitanit');
  4360. send(JSON.stringify(callsExecuteDungeon), startDungeon);
  4361. }
  4362.  
  4363. /**
  4364. * Getting data on the dungeon
  4365. *
  4366. * Получаем данные по подземелью
  4367. */
  4368. function startDungeon(e) {
  4369. stopDung = false; // стоп подземка
  4370. res = e.results;
  4371. dungeonGetInfo = res[0].result.response;
  4372. if (!dungeonGetInfo) {
  4373. endDungeon('noDungeon', res);
  4374. return;
  4375. }
  4376. teamGetAll = res[1].result.response;
  4377. teamGetFavor = res[2].result.response;
  4378. dungeonActivity = res[3].result.response.stat.todayDungeonActivity;
  4379. titanGetAll = Object.values(res[4].result.response);
  4380. countPredictionCard = res[5].result.response.consumable[81];
  4381.  
  4382. teams.hero = {
  4383. favor: teamGetFavor.dungeon_hero,
  4384. heroes: teamGetAll.dungeon_hero.filter(id => id < 6000),
  4385. teamNum: 0,
  4386. }
  4387. heroPet = teamGetAll.dungeon_hero.filter(id => id >= 6000).pop();
  4388. if (heroPet) {
  4389. teams.hero.pet = heroPet;
  4390. }
  4391.  
  4392. teams.neutral = {
  4393. favor: {},
  4394. heroes: getTitanTeam(titanGetAll, 'neutral'),
  4395. teamNum: 0,
  4396. };
  4397. teams.water = {
  4398. favor: {},
  4399. heroes: getTitanTeam(titanGetAll, 'water'),
  4400. teamNum: 0,
  4401. };
  4402. teams.fire = {
  4403. favor: {},
  4404. heroes: getTitanTeam(titanGetAll, 'fire'),
  4405. teamNum: 0,
  4406. };
  4407. teams.earth = {
  4408. favor: {},
  4409. heroes: getTitanTeam(titanGetAll, 'earth'),
  4410. teamNum: 0,
  4411. };
  4412.  
  4413.  
  4414. checkFloor(dungeonGetInfo);
  4415. }
  4416.  
  4417. function getTitanTeam(titans, type) {
  4418. switch (type) {
  4419. case 'neutral':
  4420. return titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  4421. case 'water':
  4422. return titans.filter(e => e.id.toString().slice(2, 3) == '0').map(e => e.id);
  4423. case 'fire':
  4424. return titans.filter(e => e.id.toString().slice(2, 3) == '1').map(e => e.id);
  4425. case 'earth':
  4426. return titans.filter(e => e.id.toString().slice(2, 3) == '2').map(e => e.id);
  4427. }
  4428. }
  4429.  
  4430. function getNeutralTeam() {
  4431. const titans = titanGetAll.filter(e => !titansStates[e.id]?.isDead)
  4432. return titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  4433. }
  4434.  
  4435. function fixTitanTeam(titans) {
  4436. titans.heroes = titans.heroes.filter(e => !titansStates[e]?.isDead);
  4437. return titans;
  4438. }
  4439.  
  4440. /**
  4441. * Checking the floor
  4442. *
  4443. * Проверяем этаж
  4444. */
  4445. async function checkFloor(dungeonInfo) {
  4446. if (!('floor' in dungeonInfo) || dungeonInfo.floor?.state == 2) {
  4447. saveProgress();
  4448. return;
  4449. }
  4450. // console.log(dungeonInfo, dungeonActivity);
  4451. setProgress(`${I18N('DUNGEON')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity}`);
  4452. if (dungeonActivity >= maxDungeonActivity) {
  4453. //тест
  4454. //endDungeon('endDungeon', 'maxActive ' + dungeonActivity + '/' + maxDungeonActivity);
  4455. endDungeon('Стоп подземка,', 'набрано титанита: ' + dungeonActivity + '/' + maxDungeonActivity);
  4456. return;
  4457. }
  4458. titansStates = dungeonInfo.states.titans;
  4459. titanStats = titanObjToArray(titansStates);
  4460. if (stopDung){
  4461. endDungeon('Стоп подземка,', 'набрано титанита: ' + dungeonActivity + '/' + maxDungeonActivity);
  4462. return;
  4463. }
  4464. const floorChoices = dungeonInfo.floor.userData;
  4465. const floorType = dungeonInfo.floorType;
  4466. //const primeElement = dungeonInfo.elements.prime;
  4467. if (floorType == "battle") {
  4468. const calls = [];
  4469. for (let teamNum in floorChoices) {
  4470. attackerType = floorChoices[teamNum].attackerType;
  4471. const args = fixTitanTeam(teams[attackerType]);
  4472. if (attackerType == 'neutral') {
  4473. args.heroes = getNeutralTeam();
  4474. }
  4475. if (!args.heroes.length) {
  4476. continue;
  4477. }
  4478. args.teamNum = teamNum;
  4479. calls.push({
  4480. name: "dungeonStartBattle",
  4481. args,
  4482. ident: "body_" + teamNum
  4483. })
  4484. }
  4485. if (!calls.length) {
  4486. endDungeon('endDungeon', 'All Dead');
  4487. return;
  4488. }
  4489. const battleDatas = await Send(JSON.stringify({ calls }))
  4490. .then(e => e.results.map(n => n.result.response))
  4491. const battleResults = [];
  4492. for (n in battleDatas) {
  4493. battleData = battleDatas[n]
  4494. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  4495. battleResults.push(await Calc(battleData).then(result => {
  4496. result.teamNum = n;
  4497. result.attackerType = floorChoices[n].attackerType;
  4498. return result;
  4499. }));
  4500. }
  4501. processingPromises(battleResults)
  4502. }
  4503. }
  4504.  
  4505. function processingPromises(results) {
  4506. let selectBattle = results[0];
  4507. if (results.length < 2) {
  4508. // console.log(selectBattle);
  4509. if (!selectBattle.result.win) {
  4510. endDungeon('dungeonEndBattle\n', selectBattle);
  4511. return;
  4512. }
  4513. endBattle(selectBattle);
  4514. return;
  4515. }
  4516.  
  4517. selectBattle = false;
  4518. let bestState = -1000;
  4519. for (const result of results) {
  4520. const recovery = getState(result);
  4521. if (recovery > bestState) {
  4522. bestState = recovery;
  4523. selectBattle = result
  4524. }
  4525. }
  4526. // console.log(selectBattle.teamNum, results);
  4527. if (!selectBattle || bestState <= -1000) {
  4528. endDungeon('dungeonEndBattle\n', results);
  4529. return;
  4530. }
  4531.  
  4532. startBattle(selectBattle.teamNum, selectBattle.attackerType)
  4533. .then(endBattle);
  4534. }
  4535.  
  4536. /**
  4537. * Let's start the fight
  4538. *
  4539. * Начинаем бой
  4540. */
  4541. function startBattle(teamNum, attackerType) {
  4542. return new Promise(function (resolve, reject) {
  4543. args = fixTitanTeam(teams[attackerType]);
  4544. args.teamNum = teamNum;
  4545. if (attackerType == 'neutral') {
  4546. const titans = titanGetAll.filter(e => !titansStates[e.id]?.isDead)
  4547. args.heroes = titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  4548. }
  4549. startBattleCall = {
  4550. calls: [{
  4551. name: "dungeonStartBattle",
  4552. args,
  4553. ident: "body"
  4554. }]
  4555. }
  4556. send(JSON.stringify(startBattleCall), resultBattle, {
  4557. resolve,
  4558. teamNum,
  4559. attackerType
  4560. });
  4561. });
  4562. }
  4563. /**
  4564. * Returns the result of the battle in a promise
  4565. *
  4566. * Возращает резульат боя в промис
  4567. */
  4568. function resultBattle(resultBattles, args) {
  4569. battleData = resultBattles.results[0].result.response;
  4570. battleType = "get_tower";
  4571. if (battleData.type == "dungeon_titan") {
  4572. battleType = "get_titan";
  4573. }
  4574. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  4575. BattleCalc(battleData, battleType, function (result) {
  4576. result.teamNum = args.teamNum;
  4577. result.attackerType = args.attackerType;
  4578. args.resolve(result);
  4579. });
  4580. }
  4581. /**
  4582. * Finishing the fight
  4583. *
  4584. * Заканчиваем бой
  4585. */
  4586. async function endBattle(battleInfo) {
  4587. if (battleInfo.result.win) {
  4588. const args = {
  4589. result: battleInfo.result,
  4590. progress: battleInfo.progress,
  4591. }
  4592. if (countPredictionCard > 0) {
  4593. args.isRaid = true;
  4594. } else {
  4595. const timer = getTimer(battleInfo.battleTime);
  4596. console.log(timer);
  4597. await countdownTimer(timer, `${I18N('DUNGEON')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity}`);
  4598. }
  4599. const calls = [{
  4600. name: "dungeonEndBattle",
  4601. args,
  4602. ident: "body"
  4603. }];
  4604. lastDungeonBattleData = null;
  4605. send(JSON.stringify({ calls }), resultEndBattle);
  4606. } else {
  4607. endDungeon('dungeonEndBattle win: false\n', battleInfo);
  4608. }
  4609. }
  4610.  
  4611. /**
  4612. * Getting and processing battle results
  4613. *
  4614. * Получаем и обрабатываем результаты боя
  4615. */
  4616. function resultEndBattle(e) {
  4617. if ('error' in e) {
  4618. popup.confirm(I18N('ERROR_MSG', {
  4619. name: e.error.name,
  4620. description: e.error.description,
  4621. }));
  4622. endDungeon('errorRequest', e);
  4623. return;
  4624. }
  4625. battleResult = e.results[0].result.response;
  4626. if ('error' in battleResult) {
  4627. endDungeon('errorBattleResult', battleResult);
  4628. return;
  4629. }
  4630. dungeonGetInfo = battleResult.dungeon ?? battleResult;
  4631. dungeonActivity += battleResult.reward.dungeonActivity ?? 0;
  4632. checkFloor(dungeonGetInfo);
  4633. }
  4634.  
  4635. /**
  4636. * Returns the coefficient of condition of the
  4637. * difference in titanium before and after the battle
  4638. *
  4639. * Возвращает коэффициент состояния титанов после боя
  4640. */
  4641. function getState(result) {
  4642. if (!result.result.win) {
  4643. return -1000;
  4644. }
  4645.  
  4646. let beforeSumFactor = 0;
  4647. const beforeTitans = result.battleData.attackers;
  4648. for (let titanId in beforeTitans) {
  4649. const titan = beforeTitans[titanId];
  4650. const state = titan.state;
  4651. let factor = 1;
  4652. if (state) {
  4653. const hp = state.hp / titan.hp;
  4654. const energy = state.energy / 1e3;
  4655. factor = hp + energy / 20
  4656. }
  4657. beforeSumFactor += factor;
  4658. }
  4659.  
  4660. let afterSumFactor = 0;
  4661. const afterTitans = result.progress[0].attackers.heroes;
  4662. for (let titanId in afterTitans) {
  4663. const titan = afterTitans[titanId];
  4664. const hp = titan.hp / beforeTitans[titanId].hp;
  4665. const energy = titan.energy / 1e3;
  4666. const factor = hp + energy / 20;
  4667. afterSumFactor += factor;
  4668. }
  4669. return afterSumFactor - beforeSumFactor;
  4670. }
  4671.  
  4672. /**
  4673. * Converts an object with IDs to an array with IDs
  4674. *
  4675. * Преобразует объект с идетификаторами в массив с идетификаторами
  4676. */
  4677. function titanObjToArray(obj) {
  4678. let titans = [];
  4679. for (let id in obj) {
  4680. obj[id].id = id;
  4681. titans.push(obj[id]);
  4682. }
  4683. return titans;
  4684. }
  4685.  
  4686. function saveProgress() {
  4687. let saveProgressCall = {
  4688. calls: [{
  4689. name: "dungeonSaveProgress",
  4690. args: {},
  4691. ident: "body"
  4692. }]
  4693. }
  4694. send(JSON.stringify(saveProgressCall), resultEndBattle);
  4695. }
  4696.  
  4697. function endDungeon(reason, info) {
  4698. console.warn(reason, info);
  4699. setProgress(`${I18N('DUNGEON')} ${I18N('COMPLETED')}`, true);
  4700. resolve();
  4701. }
  4702. }
  4703.  
  4704. /**
  4705. * Passing the tower
  4706. *
  4707. * Прохождение башни
  4708. */
  4709. function testTower() {
  4710. return new Promise((resolve, reject) => {
  4711. tower = new executeTower(resolve, reject);
  4712. tower.start();
  4713. });
  4714. }
  4715.  
  4716. /**
  4717. * Passing the tower
  4718. *
  4719. * Прохождение башни
  4720. */
  4721. function executeTower(resolve, reject) {
  4722. lastTowerInfo = {};
  4723.  
  4724. scullCoin = 0;
  4725.  
  4726. heroGetAll = [];
  4727.  
  4728. heroesStates = {};
  4729.  
  4730. argsBattle = {
  4731. heroes: [],
  4732. favor: {},
  4733. };
  4734.  
  4735. callsExecuteTower = {
  4736. calls: [{
  4737. name: "towerGetInfo",
  4738. args: {},
  4739. ident: "towerGetInfo"
  4740. }, {
  4741. name: "teamGetAll",
  4742. args: {},
  4743. ident: "teamGetAll"
  4744. }, {
  4745. name: "teamGetFavor",
  4746. args: {},
  4747. ident: "teamGetFavor"
  4748. }, {
  4749. name: "inventoryGet",
  4750. args: {},
  4751. ident: "inventoryGet"
  4752. }, {
  4753. name: "heroGetAll",
  4754. args: {},
  4755. ident: "heroGetAll"
  4756. }]
  4757. }
  4758.  
  4759. buffIds = [
  4760. {id: 0, cost: 0, isBuy: false}, // plug // заглушка
  4761. {id: 1, cost: 1, isBuy: true}, // 3% attack // 3% атака
  4762. {id: 2, cost: 6, isBuy: true}, // 2% attack // 2% атака
  4763. {id: 3, cost: 16, isBuy: true}, // 4% attack // 4% атака
  4764. {id: 4, cost: 40, isBuy: true}, // 8% attack // 8% атака
  4765. {id: 5, cost: 1, isBuy: true}, // 10% armor // 10% броня
  4766. {id: 6, cost: 6, isBuy: true}, // 5% armor // 5% броня
  4767. {id: 7, cost: 16, isBuy: true}, // 10% armor // 10% броня
  4768. {id: 8, cost: 40, isBuy: true}, // 20% armor // 20% броня
  4769. { id: 9, cost: 1, isBuy: true }, // 10% protection from magic // 10% защита от магии
  4770. { id: 10, cost: 6, isBuy: true }, // 5% protection from magic // 5% защита от магии
  4771. { id: 11, cost: 16, isBuy: true }, // 10% protection from magic // 10% защита от магии
  4772. { id: 12, cost: 40, isBuy: true }, // 20% protection from magic // 20% защита от магии
  4773. { id: 13, cost: 1, isBuy: false }, // 40% health hero // 40% здоровья герою
  4774. { id: 14, cost: 6, isBuy: false }, // 40% health hero // 40% здоровья герою
  4775. { id: 15, cost: 16, isBuy: false }, // 80% health hero // 80% здоровья герою
  4776. { id: 16, cost: 40, isBuy: false }, // 40% health to all heroes // 40% здоровья всем героям
  4777. { id: 17, cost: 1, isBuy: false }, // 40% energy to the hero // 40% энергии герою
  4778. { id: 18, cost: 3, isBuy: false }, // 40% energy to the hero // 40% энергии герою
  4779. { id: 19, cost: 8, isBuy: false }, // 80% energy to the hero // 80% энергии герою
  4780. { id: 20, cost: 20, isBuy: false }, // 40% energy to all heroes // 40% энергии всем героям
  4781. { id: 21, cost: 40, isBuy: false }, // Hero Resurrection // Воскрешение героя
  4782. ]
  4783.  
  4784. this.start = function () {
  4785. send(JSON.stringify(callsExecuteTower), startTower);
  4786. }
  4787.  
  4788. /**
  4789. * Getting data on the Tower
  4790. *
  4791. * Получаем данные по башне
  4792. */
  4793. function startTower(e) {
  4794. res = e.results;
  4795. towerGetInfo = res[0].result.response;
  4796. if (!towerGetInfo) {
  4797. endTower('noTower', res);
  4798. return;
  4799. }
  4800. teamGetAll = res[1].result.response;
  4801. teamGetFavor = res[2].result.response;
  4802. inventoryGet = res[3].result.response;
  4803. heroGetAll = Object.values(res[4].result.response);
  4804.  
  4805. scullCoin = inventoryGet.coin[7] ?? 0;
  4806.  
  4807. argsBattle.favor = teamGetFavor.tower;
  4808. argsBattle.heroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  4809. pet = teamGetAll.tower.filter(id => id >= 6000).pop();
  4810. if (pet) {
  4811. argsBattle.pet = pet;
  4812. }
  4813.  
  4814. checkFloor(towerGetInfo);
  4815. }
  4816.  
  4817. function fixHeroesTeam(argsBattle) {
  4818. let fixHeroes = argsBattle.heroes.filter(e => !heroesStates[e]?.isDead);
  4819. if (fixHeroes.length < 5) {
  4820. heroGetAll = heroGetAll.filter(e => !heroesStates[e.id]?.isDead);
  4821. fixHeroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  4822. Object.keys(argsBattle.favor).forEach(e => {
  4823. if (!fixHeroes.includes(+e)) {
  4824. delete argsBattle.favor[e];
  4825. }
  4826. })
  4827. }
  4828. argsBattle.heroes = fixHeroes;
  4829. return argsBattle;
  4830. }
  4831.  
  4832. /**
  4833. * Check the floor
  4834. *
  4835. * Проверяем этаж
  4836. */
  4837. function checkFloor(towerInfo) {
  4838. lastTowerInfo = towerInfo;
  4839. maySkipFloor = +towerInfo.maySkipFloor;
  4840. floorNumber = +towerInfo.floorNumber;
  4841. heroesStates = towerInfo.states.heroes;
  4842. floorInfo = towerInfo.floor;
  4843.  
  4844. /**
  4845. * Is there at least one chest open on the floor
  4846. * Открыт ли на этаже хоть один сундук
  4847. */
  4848. isOpenChest = false;
  4849. if (towerInfo.floorType == "chest") {
  4850. isOpenChest = towerInfo.floor.chests.reduce((n, e) => n + e.opened, 0);
  4851. }
  4852.  
  4853. setProgress(`${I18N('TOWER')}: ${I18N('FLOOR')} ${floorNumber}`);
  4854. if (floorNumber > 49) {
  4855. if (isOpenChest) {
  4856. endTower('alreadyOpenChest 50 floor', floorNumber);
  4857. return;
  4858. }
  4859. }
  4860. /**
  4861. * If the chest is open and you can skip floors, then move on
  4862. * Если сундук открыт и можно скипать этажи, то переходим дальше
  4863. */
  4864. if (towerInfo.mayFullSkip && +towerInfo.teamLevel == 130) {
  4865. if (isOpenChest) {
  4866. nextOpenChest(floorNumber);
  4867. } else {
  4868. nextChestOpen(floorNumber);
  4869. }
  4870. return;
  4871. }
  4872.  
  4873. // console.log(towerInfo, scullCoin);
  4874. switch (towerInfo.floorType) {
  4875. case "battle":
  4876. if (floorNumber <= maySkipFloor) {
  4877. skipFloor();
  4878. return;
  4879. }
  4880. if (floorInfo.state == 2) {
  4881. nextFloor();
  4882. return;
  4883. }
  4884. startBattle().then(endBattle);
  4885. return;
  4886. case "buff":
  4887. checkBuff(towerInfo);
  4888. return;
  4889. case "chest":
  4890. openChest(floorNumber);
  4891. return;
  4892. default:
  4893. console.log('!', towerInfo.floorType, towerInfo);
  4894. break;
  4895. }
  4896. }
  4897.  
  4898. /**
  4899. * Let's start the fight
  4900. *
  4901. * Начинаем бой
  4902. */
  4903. function startBattle() {
  4904. return new Promise(function (resolve, reject) {
  4905. towerStartBattle = {
  4906. calls: [{
  4907. name: "towerStartBattle",
  4908. args: fixHeroesTeam(argsBattle),
  4909. ident: "body"
  4910. }]
  4911. }
  4912. send(JSON.stringify(towerStartBattle), resultBattle, resolve);
  4913. });
  4914. }
  4915. /**
  4916. * Returns the result of the battle in a promise
  4917. *
  4918. * Возращает резульат боя в промис
  4919. */
  4920. function resultBattle(resultBattles, resolve) {
  4921. battleData = resultBattles.results[0].result.response;
  4922. battleType = "get_tower";
  4923. BattleCalc(battleData, battleType, function (result) {
  4924. resolve(result);
  4925. });
  4926. }
  4927. /**
  4928. * Finishing the fight
  4929. *
  4930. * Заканчиваем бой
  4931. */
  4932. function endBattle(battleInfo) {
  4933. if (battleInfo.result.stars >= 3) {
  4934. endBattleCall = {
  4935. calls: [{
  4936. name: "towerEndBattle",
  4937. args: {
  4938. result: battleInfo.result,
  4939. progress: battleInfo.progress,
  4940. },
  4941. ident: "body"
  4942. }]
  4943. }
  4944. send(JSON.stringify(endBattleCall), resultEndBattle);
  4945. } else {
  4946. endTower('towerEndBattle win: false\n', battleInfo);
  4947. }
  4948. }
  4949.  
  4950. /**
  4951. * Getting and processing battle results
  4952. *
  4953. * Получаем и обрабатываем результаты боя
  4954. */
  4955. function resultEndBattle(e) {
  4956. battleResult = e.results[0].result.response;
  4957. if ('error' in battleResult) {
  4958. endTower('errorBattleResult', battleResult);
  4959. return;
  4960. }
  4961. if ('reward' in battleResult) {
  4962. scullCoin += battleResult.reward?.coin[7] ?? 0;
  4963. }
  4964. nextFloor();
  4965. }
  4966.  
  4967. function nextFloor() {
  4968. nextFloorCall = {
  4969. calls: [{
  4970. name: "towerNextFloor",
  4971. args: {},
  4972. ident: "body"
  4973. }]
  4974. }
  4975. send(JSON.stringify(nextFloorCall), checkDataFloor);
  4976. }
  4977.  
  4978. function openChest(floorNumber) {
  4979. floorNumber = floorNumber || 0;
  4980. openChestCall = {
  4981. calls: [{
  4982. name: "towerOpenChest",
  4983. args: {
  4984. num: 2
  4985. },
  4986. ident: "body"
  4987. }]
  4988. }
  4989. send(JSON.stringify(openChestCall), floorNumber < 50 ? nextFloor : lastChest);
  4990. }
  4991.  
  4992. function lastChest() {
  4993. endTower('openChest 50 floor', floorNumber);
  4994. }
  4995.  
  4996. function skipFloor() {
  4997. skipFloorCall = {
  4998. calls: [{
  4999. name: "towerSkipFloor",
  5000. args: {},
  5001. ident: "body"
  5002. }]
  5003. }
  5004. send(JSON.stringify(skipFloorCall), checkDataFloor);
  5005. }
  5006.  
  5007. function checkBuff(towerInfo) {
  5008. buffArr = towerInfo.floor;
  5009. promises = [];
  5010. for (let buff of buffArr) {
  5011. buffInfo = buffIds[buff.id];
  5012. if (buffInfo.isBuy && buffInfo.cost <= scullCoin) {
  5013. scullCoin -= buffInfo.cost;
  5014. promises.push(buyBuff(buff.id));
  5015. }
  5016. }
  5017. Promise.all(promises).then(nextFloor);
  5018. }
  5019.  
  5020. function buyBuff(buffId) {
  5021. return new Promise(function (resolve, reject) {
  5022. buyBuffCall = {
  5023. calls: [{
  5024. name: "towerBuyBuff",
  5025. args: {
  5026. buffId
  5027. },
  5028. ident: "body"
  5029. }]
  5030. }
  5031. send(JSON.stringify(buyBuffCall), resolve);
  5032. });
  5033. }
  5034.  
  5035. function checkDataFloor(result) {
  5036. towerInfo = result.results[0].result.response;
  5037. if ('reward' in towerInfo && towerInfo.reward?.coin) {
  5038. scullCoin += towerInfo.reward?.coin[7] ?? 0;
  5039. }
  5040. if ('tower' in towerInfo) {
  5041. towerInfo = towerInfo.tower;
  5042. }
  5043. if ('skullReward' in towerInfo) {
  5044. scullCoin += towerInfo.skullReward?.coin[7] ?? 0;
  5045. }
  5046. checkFloor(towerInfo);
  5047. }
  5048. /**
  5049. * Getting tower rewards
  5050. *
  5051. * Получаем награды башни
  5052. */
  5053. function farmTowerRewards(reason) {
  5054. let { pointRewards, points } = lastTowerInfo;
  5055. let pointsAll = Object.getOwnPropertyNames(pointRewards);
  5056. let farmPoints = pointsAll.filter(e => +e <= +points && !pointRewards[e]);
  5057. if (!farmPoints.length) {
  5058. return;
  5059. }
  5060. let farmTowerRewardsCall = {
  5061. calls: [{
  5062. name: "tower_farmPointRewards",
  5063. args: {
  5064. points: farmPoints
  5065. },
  5066. ident: "tower_farmPointRewards"
  5067. }]
  5068. }
  5069.  
  5070. if (scullCoin > 0 && reason == 'openChest 50 floor') {
  5071. farmTowerRewardsCall.calls.push({
  5072. name: "tower_farmSkullReward",
  5073. args: {},
  5074. ident: "tower_farmSkullReward"
  5075. });
  5076. }
  5077.  
  5078. send(JSON.stringify(farmTowerRewardsCall), () => { });
  5079. }
  5080.  
  5081. function fullSkipTower() {
  5082. /**
  5083. * Next chest
  5084. *
  5085. * Следующий сундук
  5086. */
  5087. function nextChest(n) {
  5088. return {
  5089. name: "towerNextChest",
  5090. args: {},
  5091. ident: "group_" + n + "_body"
  5092. }
  5093. }
  5094. /**
  5095. * Open chest
  5096. *
  5097. * Открыть сундук
  5098. */
  5099. function openChest(n) {
  5100. return {
  5101. name: "towerOpenChest",
  5102. args: {
  5103. "num": 2
  5104. },
  5105. ident: "group_" + n + "_body"
  5106. }
  5107. }
  5108.  
  5109. const fullSkipTowerCall = {
  5110. calls: []
  5111. }
  5112.  
  5113. let n = 0;
  5114. for (let i = 0; i < 15; i++) {
  5115. fullSkipTowerCall.calls.push(nextChest(++n));
  5116. fullSkipTowerCall.calls.push(openChest(++n));
  5117. }
  5118.  
  5119. send(JSON.stringify(fullSkipTowerCall), data => {
  5120. data.results[0] = data.results[28];
  5121. checkDataFloor(data);
  5122. });
  5123. }
  5124.  
  5125. function nextChestOpen(floorNumber) {
  5126. const calls = [{
  5127. name: "towerOpenChest",
  5128. args: {
  5129. num: 2
  5130. },
  5131. ident: "towerOpenChest"
  5132. }];
  5133.  
  5134. Send(JSON.stringify({ calls })).then(e => {
  5135. nextOpenChest(floorNumber);
  5136. });
  5137. }
  5138.  
  5139. function nextOpenChest(floorNumber) {
  5140. if (floorNumber > 49) {
  5141. endTower('openChest 50 floor', floorNumber);
  5142. return;
  5143. }
  5144. if (floorNumber == 1) {
  5145. fullSkipTower();
  5146. return;
  5147. }
  5148.  
  5149. let nextOpenChestCall = {
  5150. calls: [{
  5151. name: "towerNextChest",
  5152. args: {},
  5153. ident: "towerNextChest"
  5154. }, {
  5155. name: "towerOpenChest",
  5156. args: {
  5157. num: 2
  5158. },
  5159. ident: "towerOpenChest"
  5160. }]
  5161. }
  5162. send(JSON.stringify(nextOpenChestCall), checkDataFloor);
  5163. }
  5164.  
  5165. function endTower(reason, info) {
  5166. console.log(reason, info);
  5167. if (reason != 'noTower') {
  5168. farmTowerRewards(reason);
  5169. }
  5170. setProgress(`${I18N('TOWER')} ${I18N('COMPLETED')}!`, true);
  5171. resolve();
  5172. }
  5173. }
  5174.  
  5175. /**
  5176. * Passage of the arena of the titans
  5177. *
  5178. * Прохождение арены титанов
  5179. */
  5180. function testTitanArena() {
  5181. return new Promise((resolve, reject) => {
  5182. titAren = new executeTitanArena(resolve, reject);
  5183. titAren.start();
  5184. });
  5185. }
  5186.  
  5187. /**
  5188. * Passage of the arena of the titans
  5189. *
  5190. * Прохождение арены титанов
  5191. */
  5192. function executeTitanArena(resolve, reject) {
  5193. let titan_arena = [];
  5194. let finishListBattle = [];
  5195. /**
  5196. * ID of the current batch
  5197. *
  5198. * Идетификатор текущей пачки
  5199. */
  5200. let currentRival = 0;
  5201. /**
  5202. * Number of attempts to finish off the pack
  5203. *
  5204. * Количество попыток добития пачки
  5205. */
  5206. let attempts = 0;
  5207. /**
  5208. * Was there an attempt to finish off the current shooting range
  5209. *
  5210. * Была ли попытка добития текущего тира
  5211. */
  5212. let isCheckCurrentTier = false;
  5213. /**
  5214. * Current shooting range
  5215. *
  5216. * Текущий тир
  5217. */
  5218. let currTier = 0;
  5219. /**
  5220. * Number of battles on the current dash
  5221. *
  5222. * Количество битв на текущем тире
  5223. */
  5224. let countRivalsTier = 0;
  5225.  
  5226. let callsStart = {
  5227. calls: [{
  5228. name: "titanArenaGetStatus",
  5229. args: {},
  5230. ident: "titanArenaGetStatus"
  5231. }, {
  5232. name: "teamGetAll",
  5233. args: {},
  5234. ident: "teamGetAll"
  5235. }]
  5236. }
  5237.  
  5238. this.start = function () {
  5239. send(JSON.stringify(callsStart), startTitanArena);
  5240. }
  5241.  
  5242. function startTitanArena(data) {
  5243. let titanArena = data.results[0].result.response;
  5244. if (titanArena.status == 'disabled') {
  5245. endTitanArena('disabled', titanArena);
  5246. return;
  5247. }
  5248.  
  5249. let teamGetAll = data.results[1].result.response;
  5250. titan_arena = teamGetAll.titan_arena;
  5251.  
  5252. checkTier(titanArena)
  5253. }
  5254.  
  5255. function checkTier(titanArena) {
  5256. if (titanArena.status == "peace_time") {
  5257. endTitanArena('Peace_time', titanArena);
  5258. return;
  5259. }
  5260. currTier = titanArena.tier;
  5261. if (currTier) {
  5262. setProgress(`${I18N('TITAN_ARENA')}: ${I18N('LEVEL')} ${currTier}`);
  5263. }
  5264.  
  5265. if (titanArena.status == "completed_tier") {
  5266. titanArenaCompleteTier();
  5267. return;
  5268. }
  5269. /**
  5270. * Checking for the possibility of a raid
  5271. * Проверка на возможность рейда
  5272. */
  5273. if (titanArena.canRaid) {
  5274. titanArenaStartRaid();
  5275. return;
  5276. }
  5277. /**
  5278. * Check was an attempt to achieve the current shooting range
  5279. * Проверка была ли попытка добития текущего тира
  5280. */
  5281. if (!isCheckCurrentTier) {
  5282. checkRivals(titanArena.rivals);
  5283. return;
  5284. }
  5285.  
  5286. endTitanArena('Done or not canRaid', titanArena);
  5287. }
  5288. /**
  5289. * Submit dash information for verification
  5290. *
  5291. * Отправка информации о тире на проверку
  5292. */
  5293. function checkResultInfo(data) {
  5294. let titanArena = data.results[0].result.response;
  5295. checkTier(titanArena);
  5296. }
  5297. /**
  5298. * Finish the current tier
  5299. *
  5300. * Завершить текущий тир
  5301. */
  5302. function titanArenaCompleteTier() {
  5303. isCheckCurrentTier = false;
  5304. let calls = [{
  5305. name: "titanArenaCompleteTier",
  5306. args: {},
  5307. ident: "body"
  5308. }];
  5309. send(JSON.stringify({calls}), checkResultInfo);
  5310. }
  5311. /**
  5312. * Gathering points to be completed
  5313. *
  5314. * Собираем точки которые нужно добить
  5315. */
  5316. function checkRivals(rivals) {
  5317. finishListBattle = [];
  5318. for (let n in rivals) {
  5319. if (rivals[n].attackScore < 250) {
  5320. finishListBattle.push(n);
  5321. }
  5322. }
  5323. console.log('checkRivals', finishListBattle);
  5324. countRivalsTier = finishListBattle.length;
  5325. roundRivals();
  5326. }
  5327. /**
  5328. * Selecting the next point to finish off
  5329. *
  5330. * Выбор следующей точки для добития
  5331. */
  5332. function roundRivals() {
  5333. let countRivals = finishListBattle.length;
  5334. if (!countRivals) {
  5335. /**
  5336. * Whole range checked
  5337. *
  5338. * Весь тир проверен
  5339. */
  5340. isCheckCurrentTier = true;
  5341. titanArenaGetStatus();
  5342. return;
  5343. }
  5344. // setProgress('TitanArena: Уровень ' + currTier + ' Бои: ' + (countRivalsTier - countRivals + 1) + '/' + countRivalsTier);
  5345. currentRival = finishListBattle.pop();
  5346. attempts = +currentRival;
  5347. // console.log('roundRivals', currentRival);
  5348. titanArenaStartBattle(currentRival);
  5349. }
  5350. /**
  5351. * The start of a solo battle
  5352. *
  5353. * Начало одиночной битвы
  5354. */
  5355. function titanArenaStartBattle(rivalId) {
  5356. let calls = [{
  5357. name: "titanArenaStartBattle",
  5358. args: {
  5359. rivalId: rivalId,
  5360. titans: titan_arena
  5361. },
  5362. ident: "body"
  5363. }];
  5364. send(JSON.stringify({calls}), calcResult);
  5365. }
  5366. /**
  5367. * Calculation of the results of the battle
  5368. *
  5369. * Расчет результатов боя
  5370. */
  5371. function calcResult(data) {
  5372. let battlesInfo = data.results[0].result.response.battle;
  5373. /**
  5374. * If attempts are equal to the current battle number we make
  5375. * Если попытки равны номеру текущего боя делаем прерасчет
  5376. */
  5377. if (attempts == currentRival) {
  5378. preCalcBattle(battlesInfo);
  5379. return;
  5380. }
  5381. /**
  5382. * If there are still attempts, we calculate a new battle
  5383. * Если попытки еще есть делаем расчет нового боя
  5384. */
  5385. if (attempts > 0) {
  5386. attempts--;
  5387. calcBattleResult(battlesInfo)
  5388. .then(resultCalcBattle);
  5389. return;
  5390. }
  5391. /**
  5392. * Otherwise, go to the next opponent
  5393. * Иначе переходим к следующему сопернику
  5394. */
  5395. roundRivals();
  5396. }
  5397. /**
  5398. * Processing the results of the battle calculation
  5399. *
  5400. * Обработка результатов расчета битвы
  5401. */
  5402. function resultCalcBattle(resultBattle) {
  5403. // console.log('resultCalcBattle', currentRival, attempts, resultBattle.result.win);
  5404. /**
  5405. * If the current calculation of victory is not a chance or the attempt ended with the finish the battle
  5406. * Если текущий расчет победа или шансов нет или попытки кончились завершаем бой
  5407. */
  5408. if (resultBattle.result.win || !attempts) {
  5409. titanArenaEndBattle({
  5410. progress: resultBattle.progress,
  5411. result: resultBattle.result,
  5412. rivalId: resultBattle.battleData.typeId
  5413. });
  5414. return;
  5415. }
  5416. /**
  5417. * If not victory and there are attempts we start a new battle
  5418. * Если не победа и есть попытки начинаем новый бой
  5419. */
  5420. titanArenaStartBattle(resultBattle.battleData.typeId);
  5421. }
  5422. /**
  5423. * Returns the promise of calculating the results of the battle
  5424. *
  5425. * Возращает промис расчета результатов битвы
  5426. */
  5427. function getBattleInfo(battle, isRandSeed) {
  5428. return new Promise(function (resolve) {
  5429. if (isRandSeed) {
  5430. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  5431. }
  5432. // console.log(battle.seed);
  5433. BattleCalc(battle, "get_titanClanPvp", e => resolve(e));
  5434. });
  5435. }
  5436. /**
  5437. * Recalculate battles
  5438. *
  5439. * Прерасчтет битвы
  5440. */
  5441. function preCalcBattle(battle) {
  5442. let actions = [getBattleInfo(battle, false)];
  5443. const countTestBattle = getInput('countTestBattle');
  5444. for (let i = 0; i < countTestBattle; i++) {
  5445. actions.push(getBattleInfo(battle, true));
  5446. }
  5447. Promise.all(actions)
  5448. .then(resultPreCalcBattle);
  5449. }
  5450. /**
  5451. * Processing the results of the battle recalculation
  5452. *
  5453. * Обработка результатов прерасчета битвы
  5454. */
  5455. function resultPreCalcBattle(e) {
  5456. let wins = e.map(n => n.result.win);
  5457. let firstBattle = e.shift();
  5458. let countWin = wins.reduce((w, s) => w + s);
  5459. let numReval = countRivalsTier - finishListBattle.length;
  5460. // setProgress('TitanArena: Уровень ' + currTier + ' Бои: ' + numReval + '/' + countRivalsTier + ' - ' + countWin + '/11');
  5461. console.log('resultPreCalcBattle', countWin + '/11' )
  5462. if (countWin > 0) {
  5463. attempts = getInput('countAutoBattle');
  5464. } else {
  5465. attempts = 0;
  5466. }
  5467. resultCalcBattle(firstBattle);
  5468. }
  5469.  
  5470. /**
  5471. * Complete an arena battle
  5472. *
  5473. * Завершить битву на арене
  5474. */
  5475. function titanArenaEndBattle(args) {
  5476. let calls = [{
  5477. name: "titanArenaEndBattle",
  5478. args,
  5479. ident: "body"
  5480. }];
  5481. send(JSON.stringify({calls}), resultTitanArenaEndBattle);
  5482. }
  5483.  
  5484. function resultTitanArenaEndBattle(e) {
  5485. let attackScore = e.results[0].result.response.attackScore;
  5486. let numReval = countRivalsTier - finishListBattle.length;
  5487. setProgress(`${I18N('TITAN_ARENA')}: ${I18N('LEVEL')} ${currTier} </br>${I18N('BATTLES')}: ${numReval}/${countRivalsTier} - ${attackScore}`);
  5488. /**
  5489. * TODO: Might need to improve the results.
  5490. * TODO: Возможно стоит сделать улучшение результатов
  5491. */
  5492. // console.log('resultTitanArenaEndBattle', e)
  5493. console.log('resultTitanArenaEndBattle', numReval + '/' + countRivalsTier, attempts)
  5494. roundRivals();
  5495. }
  5496. /**
  5497. * Arena State
  5498. *
  5499. * Состояние арены
  5500. */
  5501. function titanArenaGetStatus() {
  5502. let calls = [{
  5503. name: "titanArenaGetStatus",
  5504. args: {},
  5505. ident: "body"
  5506. }];
  5507. send(JSON.stringify({calls}), checkResultInfo);
  5508. }
  5509. /**
  5510. * Arena Raid Request
  5511. *
  5512. * Запрос рейда арены
  5513. */
  5514. function titanArenaStartRaid() {
  5515. let calls = [{
  5516. name: "titanArenaStartRaid",
  5517. args: {
  5518. titans: titan_arena
  5519. },
  5520. ident: "body"
  5521. }];
  5522. send(JSON.stringify({calls}), calcResults);
  5523. }
  5524.  
  5525. function calcResults(data) {
  5526. let battlesInfo = data.results[0].result.response;
  5527. let {attackers, rivals} = battlesInfo;
  5528.  
  5529. let promises = [];
  5530. for (let n in rivals) {
  5531. rival = rivals[n];
  5532. promises.push(calcBattleResult({
  5533. attackers: attackers,
  5534. defenders: [rival.team],
  5535. seed: rival.seed,
  5536. typeId: n,
  5537. }));
  5538. }
  5539.  
  5540. Promise.all(promises)
  5541. .then(results => {
  5542. const endResults = {};
  5543. for (let info of results) {
  5544. let id = info.battleData.typeId;
  5545. endResults[id] = {
  5546. progress: info.progress,
  5547. result: info.result,
  5548. }
  5549. }
  5550. titanArenaEndRaid(endResults);
  5551. });
  5552. }
  5553.  
  5554. function calcBattleResult(battleData) {
  5555. return new Promise(function (resolve, reject) {
  5556. BattleCalc(battleData, "get_titanClanPvp", resolve);
  5557. });
  5558. }
  5559.  
  5560. /**
  5561. * Sending Raid Results
  5562. *
  5563. * Отправка результатов рейда
  5564. */
  5565. function titanArenaEndRaid(results) {
  5566. titanArenaEndRaidCall = {
  5567. calls: [{
  5568. name: "titanArenaEndRaid",
  5569. args: {
  5570. results
  5571. },
  5572. ident: "body"
  5573. }]
  5574. }
  5575. send(JSON.stringify(titanArenaEndRaidCall), checkRaidResults);
  5576. }
  5577.  
  5578. function checkRaidResults(data) {
  5579. results = data.results[0].result.response.results;
  5580. isSucsesRaid = true;
  5581. for (let i in results) {
  5582. isSucsesRaid &&= (results[i].attackScore >= 250);
  5583. }
  5584.  
  5585. if (isSucsesRaid) {
  5586. titanArenaCompleteTier();
  5587. } else {
  5588. titanArenaGetStatus();
  5589. }
  5590. }
  5591.  
  5592. function titanArenaFarmDailyReward() {
  5593. titanArenaFarmDailyRewardCall = {
  5594. calls: [{
  5595. name: "titanArenaFarmDailyReward",
  5596. args: {},
  5597. ident: "body"
  5598. }]
  5599. }
  5600. send(JSON.stringify(titanArenaFarmDailyRewardCall), () => {console.log('Done farm daily reward')});
  5601. }
  5602.  
  5603. function endTitanArena(reason, info) {
  5604. if (!['Peace_time', 'disabled'].includes(reason)) {
  5605. titanArenaFarmDailyReward();
  5606. }
  5607. console.log(reason, info);
  5608. setProgress(`${I18N('TITAN_ARENA')} ${I18N('COMPLETED')}!`, true);
  5609. resolve();
  5610. }
  5611. }
  5612.  
  5613. function hackGame() {
  5614. self = this;
  5615. selfGame = null;
  5616. bindId = 1e9;
  5617. this.libGame = null;
  5618.  
  5619. /**
  5620. * List of correspondence of used classes to their names
  5621. *
  5622. * Список соответствия используемых классов их названиям
  5623. */
  5624. ObjectsList = [
  5625. {name:"BattlePresets", prop:"game.battle.controller.thread.BattlePresets"},
  5626. {name:"DataStorage", prop:"game.data.storage.DataStorage"},
  5627. {name:"BattleConfigStorage", prop:"game.data.storage.battle.BattleConfigStorage"},
  5628. {name:"BattleInstantPlay", prop:"game.battle.controller.instant.BattleInstantPlay"},
  5629. {name:"MultiBattleResult", prop:"game.battle.controller.MultiBattleResult"},
  5630.  
  5631. {name:"PlayerMissionData", prop:"game.model.user.mission.PlayerMissionData"},
  5632. {name:"PlayerMissionBattle", prop:"game.model.user.mission.PlayerMissionBattle"},
  5633. {name:"GameModel", prop:"game.model.GameModel"},
  5634. {name:"CommandManager", prop:"game.command.CommandManager"},
  5635. {name:"MissionCommandList", prop:"game.command.rpc.mission.MissionCommandList"},
  5636. {name:"RPCCommandBase", prop:"game.command.rpc.RPCCommandBase"},
  5637. {name:"PlayerTowerData", prop:"game.model.user.tower.PlayerTowerData"},
  5638. {name:"TowerCommandList", prop:"game.command.tower.TowerCommandList"},
  5639. {name:"PlayerHeroTeamResolver", prop:"game.model.user.hero.PlayerHeroTeamResolver"},
  5640. {name:"BattlePausePopup", prop:"game.view.popup.battle.BattlePausePopup"},
  5641. {name:"BattlePopup", prop:"game.view.popup.battle.BattlePopup"},
  5642. {name:"DisplayObjectContainer", prop:"starling.display.DisplayObjectContainer"},
  5643. {name:"GuiClipContainer", prop:"engine.core.clipgui.GuiClipContainer"},
  5644. {name:"BattlePausePopupClip", prop:"game.view.popup.battle.BattlePausePopupClip"},
  5645. {name:"ClipLabel", prop:"game.view.gui.components.ClipLabel"},
  5646. {name:"ClipLabelBase", prop:"game.view.gui.components.ClipLabelBase"},
  5647. {name:"Translate", prop:"com.progrestar.common.lang.Translate"},
  5648. {name:"ClipButtonLabeledCentered", prop:"game.view.gui.components.ClipButtonLabeledCentered"},
  5649. {name:"BattlePausePopupMediator", prop:"game.mediator.gui.popup.battle.BattlePausePopupMediator"},
  5650. {name:"SettingToggleButton", prop:"game.mechanics.settings.popup.view.SettingToggleButton"},
  5651. {name:"PlayerDungeonData", prop:"game.mechanics.dungeon.model.PlayerDungeonData"},
  5652. {name:"NextDayUpdatedManager", prop:"game.model.user.NextDayUpdatedManager"},
  5653. {name:"BattleController", prop:"game.battle.controller.BattleController"},
  5654. {name:"BattleSettingsModel", prop:"game.battle.controller.BattleSettingsModel"},
  5655. {name:"BooleanProperty", prop:"engine.core.utils.property.BooleanProperty"},
  5656. {name:"RuleStorage", prop:"game.data.storage.rule.RuleStorage"},
  5657. {name:"BattleConfig", prop:"battle.BattleConfig"},
  5658. {name:"SpecialShopModel", prop:"game.model.user.shop.SpecialShopModel"},
  5659. {name:"BattleGuiMediator", prop:"game.battle.gui.BattleGuiMediator"},
  5660. {name:"BooleanPropertyWriteable", prop:"engine.core.utils.property.BooleanPropertyWriteable"},
  5661. { name: "BattleLogEncoder", prop: "battle.log.BattleLogEncoder" },
  5662. { name: "BattleLogReader", prop: "battle.log.BattleLogReader" },
  5663. ];
  5664.  
  5665. /**
  5666. * Contains the game classes needed to write and override game methods
  5667. *
  5668. * Содержит классы игры необходимые для написания и подмены методов игры
  5669. */
  5670. Game = {
  5671. /**
  5672. * Function 'e'
  5673. * Функция 'e'
  5674. */
  5675. bindFunc: function (a, b) {
  5676. if (null == b)
  5677. return null;
  5678. null == b.__id__ && (b.__id__ = bindId++);
  5679. var c;
  5680. null == a.hx__closures__ ? a.hx__closures__ = {} :
  5681. c = a.hx__closures__[b.__id__];
  5682. null == c && (c = b.bind(a), a.hx__closures__[b.__id__] = c);
  5683. return c
  5684. },
  5685. };
  5686.  
  5687. /**
  5688. * Connects to game objects via the object creation event
  5689. *
  5690. * Подключается к объектам игры через событие создания объекта
  5691. */
  5692. function connectGame() {
  5693. for (let obj of ObjectsList) {
  5694. /**
  5695. * https: //stackoverflow.com/questions/42611719/how-to-intercept-and-modify-a-specific-property-for-any-object
  5696. */
  5697. Object.defineProperty(Object.prototype, obj.prop, {
  5698. set: function (value) {
  5699. if (!selfGame) {
  5700. selfGame = this;
  5701. }
  5702. if (!Game[obj.name]) {
  5703. Game[obj.name] = value;
  5704. }
  5705. // console.log('set ' + obj.prop, this, value);
  5706. this[obj.prop + '_'] = value;
  5707. },
  5708. get: function () {
  5709. // console.log('get ' + obj.prop, this);
  5710. return this[obj.prop + '_'];
  5711. }
  5712. });
  5713. }
  5714. }
  5715.  
  5716. /**
  5717. * Game.BattlePresets
  5718. * @param {bool} a isReplay
  5719. * @param {bool} b autoToggleable
  5720. * @param {bool} c auto On Start
  5721. * @param {object} d config
  5722. * @param {bool} f showBothTeams
  5723. */
  5724. /**
  5725. * Returns the results of the battle to the callback function
  5726. * Возвращает в функцию callback результаты боя
  5727. * @param {*} battleData battle data данные боя
  5728. * @param {*} battleConfig combat configuration type options:
  5729. *
  5730. * тип конфигурации боя варианты:
  5731. *
  5732. * "get_invasion", "get_titanPvpManual", "get_titanPvp",
  5733. * "get_titanClanPvp","get_clanPvp","get_titan","get_boss",
  5734. * "get_tower","get_pve","get_pvpManual","get_pvp","get_core"
  5735. *
  5736. * You can specify the xYc function in the game.assets.storage.BattleAssetStorage class
  5737. *
  5738. * Можно уточнить в классе game.assets.storage.BattleAssetStorage функция xYc
  5739. * @param {*} callback функция в которую вернуться результаты боя
  5740. */
  5741. this.BattleCalc = function (battleData, battleConfig, callback) {
  5742. // battleConfig = battleConfig || getBattleType(battleData.type)
  5743. if (!Game.BattlePresets) throw Error('Use connectGame');
  5744. battlePresets = new Game.BattlePresets(!!battleData.progress, !1, !0, Game.DataStorage[getFn(Game.DataStorage, 23)][getF(Game.BattleConfigStorage, battleConfig)](), !1);
  5745. battleInstantPlay = new Game.BattleInstantPlay(battleData, battlePresets);
  5746. battleInstantPlay[getProtoFn(Game.BattleInstantPlay, 8)].add((battleInstant) => {
  5747. const battleResult = battleInstant[getF(Game.BattleInstantPlay, 'get_result')]();
  5748. const battleData = battleInstant[getF(Game.BattleInstantPlay, 'get_rawBattleInfo')]();
  5749. const battleLog = Game.BattleLogEncoder.read(new Game.BattleLogReader(battleResult[getProtoFn(Game.MultiBattleResult, 2)][0]));
  5750. const timeLimit = battlePresets[getF(Game.BattlePresets, 'get_timeLimit')]();
  5751. const battleTime = Math.max(...battleLog.map(e => e.time < timeLimit ? e.time : 0));
  5752. callback({
  5753. battleTime,
  5754. battleData,
  5755. progress: battleResult[getF(Game.MultiBattleResult, 'get_progress')](),
  5756. result: battleResult[getF(Game.MultiBattleResult, 'get_result')]()
  5757. })
  5758. });
  5759. battleInstantPlay.start();
  5760. }
  5761.  
  5762. /**
  5763. * Returns a function with the specified name from the class
  5764. *
  5765. * Возвращает из класса функцию с указанным именем
  5766. * @param {Object} classF Class // класс
  5767. * @param {String} nameF function name // имя функции
  5768. * @param {String} pos name and alias order // порядок имени и псевдонима
  5769. * @returns
  5770. */
  5771. function getF(classF, nameF, pos) {
  5772. pos = pos || false;
  5773. let prop = Object.entries(classF.prototype.__properties__)
  5774. if (!pos) {
  5775. return prop.filter((e) => e[1] == nameF).pop()[0];
  5776. } else {
  5777. return prop.filter((e) => e[0] == nameF).pop()[1];
  5778. }
  5779. }
  5780.  
  5781. /**
  5782. * Returns a function with the specified name from the class
  5783. *
  5784. * Возвращает из класса функцию с указанным именем
  5785. * @param {Object} classF Class // класс
  5786. * @param {String} nameF function name // имя функции
  5787. * @returns
  5788. */
  5789. function getFnP(classF, nameF) {
  5790. let prop = Object.entries(classF.__properties__)
  5791. return prop.filter((e) => e[1] == nameF).pop()[0];
  5792. }
  5793.  
  5794. /**
  5795. * Returns the function name with the specified ordinal from the class
  5796. *
  5797. * Возвращает имя функции с указаным порядковым номером из класса
  5798. * @param {Object} classF Class // класс
  5799. * @param {Number} nF Order number of function // порядковый номер функции
  5800. * @returns
  5801. */
  5802. function getFn(classF, nF) {
  5803. let prop = Object.keys(classF);
  5804. return prop[nF];
  5805. }
  5806.  
  5807. /**
  5808. * Returns the name of the function with the specified serial number from the prototype of the class
  5809. *
  5810. * Возвращает имя функции с указаным порядковым номером из прототипа класса
  5811. * @param {Object} classF Class // класс
  5812. * @param {Number} nF Order number of function // порядковый номер функции
  5813. * @returns
  5814. */
  5815. function getProtoFn(classF, nF) {
  5816. let prop = Object.keys(classF.prototype);
  5817. return prop[nF];
  5818. }
  5819. /**
  5820. * Description of replaced functions
  5821. *
  5822. * Описание подменяемых функций
  5823. */
  5824. replaceFunction = {
  5825. company: function() {
  5826. let PMD_12 = getProtoFn(Game.PlayerMissionData, 12);
  5827. let oldSkipMisson = Game.PlayerMissionData.prototype[PMD_12];
  5828. Game.PlayerMissionData.prototype[PMD_12] = function (a, b, c) {
  5829. if (isChecked('passBattle')) {
  5830. this[getProtoFn(Game.PlayerMissionData, 9)] = new Game.PlayerMissionBattle(a, b, c);
  5831.  
  5832. var a = new Game.BattlePresets(!1, !1, !0, Game.DataStorage[getFn(Game.DataStorage, 23)][getProtoFn(Game.BattleConfigStorage, 17)](), !1);
  5833. a = new Game.BattleInstantPlay(c, a);
  5834. a[getProtoFn(Game.BattleInstantPlay, 8)].add(Game.bindFunc(this, this.P$h));
  5835. a.start()
  5836. } else {
  5837. oldSkipMisson.call(this, a, b, c);
  5838. }
  5839. }
  5840.  
  5841. Game.PlayerMissionData.prototype.P$h = function (a) {
  5842. let GM_2 = getFn(Game.GameModel, 2);
  5843. let GM_P2 = getProtoFn(Game.GameModel, 2);
  5844. let CM_20 = getProtoFn(Game.CommandManager, 20);
  5845. let MCL_2 = getProtoFn(Game.MissionCommandList, 2);
  5846. let MBR_15 = getProtoFn(Game.MultiBattleResult, 15);
  5847. let RPCCB_15 = getProtoFn(Game.RPCCommandBase, 15);
  5848. let PMD_32 = getProtoFn(Game.PlayerMissionData, 32);
  5849. Game.GameModel[GM_2]()[GM_P2][CM_20][MCL_2](a[MBR_15]())[RPCCB_15](Game.bindFunc(this, this[PMD_32]))
  5850. }
  5851. },
  5852. tower: function() {
  5853. let PTD_67 = getProtoFn(Game.PlayerTowerData, 67);
  5854. let oldSkipTower = Game.PlayerTowerData.prototype[PTD_67];
  5855. Game.PlayerTowerData.prototype[PTD_67] = function (a) {
  5856. if (isChecked('passBattle')) {
  5857. var p = new Game.BattlePresets(!1, !1, !0, Game.DataStorage[getFn(Game.DataStorage, 23)][getProtoFn(Game.BattleConfigStorage,17)](), !1);
  5858. a = new Game.BattleInstantPlay(a, p);
  5859. a[getProtoFn(Game.BattleInstantPlay,8)].add(Game.bindFunc(this, this.P$h));
  5860. a.start()
  5861. } else {
  5862. oldSkipTower.call(this, a);;
  5863. }
  5864. }
  5865.  
  5866. Game.PlayerTowerData.prototype.P$h = function (a) {
  5867. const GM_2 = getFnP(Game.GameModel, "get_instance");
  5868. const GM_P2 = getProtoFn(Game.GameModel, 2);
  5869. const CM_29 = getProtoFn(Game.CommandManager, 29);
  5870. const TCL_5 = getProtoFn(Game.TowerCommandList, 5);
  5871. const MBR_15 = getF(Game.MultiBattleResult, "get_result");
  5872. const RPCCB_15 = getProtoFn(Game.RPCCommandBase, 16);
  5873. const PTD_78 = getProtoFn(Game.PlayerTowerData, 78);
  5874. Game.GameModel[GM_2]()[GM_P2][CM_29][TCL_5](a[MBR_15]())[RPCCB_15](Game.bindFunc(this, this[PTD_78]));
  5875. }
  5876. },
  5877. // skipSelectHero: function() {
  5878. // if (!HOST) throw Error('Use connectGame');
  5879. // Game.PlayerHeroTeamResolver.prototype[getProtoFn(Game.PlayerHeroTeamResolver, 3)] = () => false;
  5880. // },
  5881. passBattle: function() {
  5882. let BPP_4 = getProtoFn(Game.BattlePausePopup, 4);
  5883. let oldPassBattle = Game.BattlePausePopup.prototype[BPP_4];
  5884. Game.BattlePausePopup.prototype[BPP_4] = function (a) {
  5885. if (isChecked('passBattle')) {
  5886. Game.BattlePopup.prototype[getProtoFn(Game.BattlePausePopup, 4)].call(this, a);
  5887. this[getProtoFn(Game.BattlePausePopup, 3)]();
  5888. this[getProtoFn(Game.DisplayObjectContainer, 3)](this.clip[getProtoFn(Game.GuiClipContainer, 2)]());
  5889. this.clip[getProtoFn(Game.BattlePausePopupClip, 1)][getProtoFn(Game.ClipLabelBase, 9)](Game.Translate.translate("UI_POPUP_BATTLE_PAUSE"));
  5890.  
  5891. 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)])));
  5892. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 2)](
  5893. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 14)](),
  5894. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 13)]() ?
  5895. (q = this[getProtoFn(Game.BattlePausePopup, 1)], Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 18)])) :
  5896. (q = this[getProtoFn(Game.BattlePausePopup, 1)], Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 18)]))
  5897. );
  5898.  
  5899. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 0)][getProtoFn(Game.ClipLabelBase, 24)]();
  5900. this.clip[getProtoFn(Game.BattlePausePopupClip, 3)][getProtoFn(Game.SettingToggleButton, 3)](this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 9)]());
  5901. this.clip[getProtoFn(Game.BattlePausePopupClip, 4)][getProtoFn(Game.SettingToggleButton, 3)](this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 10)]());
  5902. this.clip[getProtoFn(Game.BattlePausePopupClip, 6)][getProtoFn(Game.SettingToggleButton, 3)](this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 11)]());
  5903. /*
  5904. Какая-то ненужная фигня
  5905. if (!HC.lSb()) {
  5906. this.clip.r6b.g().B(!1);
  5907. a = this.clip.r6b.g().X() + 7;
  5908. var b = this.clip.ba.g();
  5909. b.$(b.X() - a);
  5910. b = this.clip.IS.g();
  5911. b.sa(b.Fa() - a)
  5912. }
  5913. */
  5914. } else {
  5915. oldPassBattle.call(this, a);
  5916. }
  5917. }
  5918.  
  5919. let retreatButtonLabel = getF(Game.BattlePausePopupMediator, "get_retreatButtonLabel");
  5920. let oldFunc = Game.BattlePausePopupMediator.prototype[retreatButtonLabel];
  5921. Game.BattlePausePopupMediator.prototype[retreatButtonLabel] = function () {
  5922. if (isChecked('passBattle')) {
  5923. return I18N('BTN_PASS');
  5924. } else {
  5925. return oldFunc.call(this);
  5926. }
  5927. }
  5928. },
  5929. endlessCards: function() {
  5930. let PDD_15 = getProtoFn(Game.PlayerDungeonData, 15);
  5931. let oldEndlessCards = Game.PlayerDungeonData.prototype[PDD_15];
  5932. Game.PlayerDungeonData.prototype[PDD_15] = function () {
  5933. if (countPredictionCard <= 0) {
  5934. return true;
  5935. } else {
  5936. return oldEndlessCards.call(this);
  5937. }
  5938. }
  5939. },
  5940. speedBattle: function () {
  5941. const get_timeScale = getF(Game.BattleController, "get_timeScale");
  5942. const oldSpeedBattle = Game.BattleController.prototype[get_timeScale];
  5943. Game.BattleController.prototype[get_timeScale] = function () {
  5944. const speedBattle = Number.parseFloat(getInput('speedBattle'));
  5945. if (speedBattle) {
  5946. const BC_11 = getProtoFn(Game.BattleController, 11);
  5947. const BSM_11 = getProtoFn(Game.BattleSettingsModel, 11);
  5948. const BP_get_value = getF(Game.BooleanProperty, "get_value");
  5949. if (this[BC_11][BSM_11][BP_get_value]()) {
  5950. return 0;
  5951. }
  5952. const BSM_2 = getProtoFn(Game.BattleSettingsModel, 2);
  5953. const BC_44 = getProtoFn(Game.BattleController, 44);
  5954. const BSM_1 = getProtoFn(Game.BattleSettingsModel, 1);
  5955. const BC_13 = getProtoFn(Game.BattleController, 13);
  5956. const BC_3 = getFn(Game.BattleController, 3);
  5957. if (this[BC_11][BSM_2][BP_get_value]()) {
  5958. var a = speedBattle * this[BC_44]();
  5959. } else {
  5960. a = this[BC_11][BSM_1][BP_get_value]();
  5961. //const multiple = a == 1 ? speedBattle : this[BC_13][a];
  5962. a = this[BC_13][a] * Game.BattleController[BC_3][BP_get_value]() * this[BC_44]();
  5963. }
  5964. const BSM_22 = getProtoFn(Game.BattleSettingsModel, 22);
  5965. a > this[BC_11][BSM_22][BP_get_value]() && (a = this[BC_11][BSM_22][BP_get_value]());
  5966. const DS_22 = getFn(Game.DataStorage, 22);
  5967. const get_battleSpeedMultiplier = getF(Game.RuleStorage, "get_battleSpeedMultiplier", true);
  5968. // const RS_167 = getProtoFn(Game.RuleStorage, 167); // get_battleSpeedMultiplier
  5969. var b = Game.DataStorage[DS_22][get_battleSpeedMultiplier]();
  5970. const R_1 = getFn(selfGame.Reflect, 1);
  5971. const BC_1 = getFn(Game.BattleController, 1);
  5972. const get_config = getF(Game.BattlePresets, "get_config");
  5973. // const BC_0 = getProtoFn(Game.BattleConfig, 0); // .ident
  5974. 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"));
  5975. return a
  5976. } else {
  5977. return oldSpeedBattle.call(this);
  5978. }
  5979. }
  5980. },
  5981.  
  5982. /**
  5983. * Remove the rare shop
  5984. *
  5985. * Удаление торговца редкими товарами
  5986. */
  5987. /*
  5988. removeWelcomeShop: function () {
  5989. let SSM_3 = getProtoFn(Game.SpecialShopModel, 3);
  5990. const oldWelcomeShop = Game.SpecialShopModel.prototype[SSM_3];
  5991. Game.SpecialShopModel.prototype[SSM_3] = function () {
  5992. if (isChecked('noOfferDonat')) {
  5993. return null;
  5994. } else {
  5995. return oldWelcomeShop.call(this);
  5996. }
  5997. }
  5998. },
  5999. */
  6000.  
  6001. /**
  6002. * Acceleration button without Valkyries favor
  6003. *
  6004. * Кнопка ускорения без Покровительства Валькирий
  6005. */
  6006. battleFastKey: function () {
  6007. const BGM_40 = getProtoFn(Game.BattleGuiMediator, 40);
  6008. const oldBattleFastKey = Game.BattleGuiMediator.prototype[BGM_40];
  6009. Game.BattleGuiMediator.prototype[BGM_40] = function () {
  6010. if (true) {
  6011. const BGM_8 = getProtoFn(Game.BattleGuiMediator, 8);
  6012. const BGM_9 = getProtoFn(Game.BattleGuiMediator, 9);
  6013. const BPW_0 = getProtoFn(Game.BooleanPropertyWriteable, 0);
  6014. this[BGM_8][BPW_0](true);
  6015. this[BGM_9][BPW_0](true);
  6016. } else {
  6017. return oldBattleFastKey.call(this);
  6018. }
  6019. }
  6020. }
  6021. }
  6022.  
  6023. /**
  6024. * Starts replacing recorded functions
  6025. *
  6026. * Запускает замену записанных функций
  6027. */
  6028. this.activateHacks = function () {
  6029. if (!selfGame) throw Error('Use connectGame');
  6030. for (let func in replaceFunction) {
  6031. replaceFunction[func]();
  6032. }
  6033. }
  6034.  
  6035. /**
  6036. * Returns the game object
  6037. *
  6038. * Возвращает объект игры
  6039. */
  6040. this.getSelfGame = function () {
  6041. return selfGame;
  6042. }
  6043.  
  6044. /**
  6045. * Updates game data
  6046. *
  6047. * Обновляет данные игры
  6048. */
  6049. this.refreshGame = function () {
  6050. (new Game.NextDayUpdatedManager)[getProtoFn(Game.NextDayUpdatedManager, 5)]();
  6051. }
  6052.  
  6053. /**
  6054. * Change the play screen on windowName
  6055. *
  6056. * Сменить экран игры на windowName
  6057. *
  6058. * Possible options:
  6059. *
  6060. * Возможные варианты:
  6061. *
  6062. * 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
  6063. */
  6064. this.goNavigtor = function (windowName) {
  6065. let mechanicStorage = selfGame["game.data.storage.mechanic.MechanicStorage"];
  6066. let window = mechanicStorage[windowName];
  6067. let event = new selfGame["game.mediator.gui.popup.PopupStashEventParams"];
  6068. let Game = selfGame['Game'];
  6069. let navigator = getF(Game, "get_navigator")
  6070. let navigate = getProtoFn(selfGame["game.screen.navigator.GameNavigator"], 18)
  6071. let instance = getFnP(Game, 'get_instance');
  6072. Game[instance]()[navigator]()[navigate](window, event);
  6073. }
  6074.  
  6075. /**
  6076. * Move to the sanctuary cheats.goSanctuary()
  6077. *
  6078. * Переместиться в святилище cheats.goSanctuary()
  6079. */
  6080. this.goSanctuary = () => {
  6081. this.goNavigtor("SANCTUARY");
  6082. }
  6083.  
  6084. /**
  6085. * Go to Guild War
  6086. *
  6087. * Перейти к Войне Гильдий
  6088. */
  6089. this.goClanWar = function() {
  6090. let instance = getFnP(selfGame["game.model.GameModel"], 'get_instance')
  6091. let player = selfGame["game.model.GameModel"][instance]().A;
  6092. let clanWarSelect = selfGame["game.mechanics.cross_clan_war.popup.selectMode.CrossClanWarSelectModeMediator"];
  6093. new clanWarSelect(player).open();
  6094. }
  6095.  
  6096. /**
  6097. * Go to BrawlShop
  6098. *
  6099. * Переместиться в BrawlShop
  6100. */
  6101. this.goBrawlShop = () => {
  6102. const instance = getFnP(selfGame["game.model.GameModel"], 'get_instance')
  6103. const P_36 = getProtoFn(selfGame["game.model.user.Player"], 36);
  6104. const PSD_0 = getProtoFn(selfGame["game.model.user.shop.PlayerShopData"], 0);
  6105. const IM_0 = getProtoFn(selfGame["haxe.ds.IntMap"], 0);
  6106. const PSDE_4 = getProtoFn(selfGame["game.model.user.shop.PlayerShopDataEntry"], 4);
  6107.  
  6108. const player = selfGame["game.model.GameModel"][instance]().A;
  6109. const shop = player[P_36][PSD_0][IM_0][1038][PSDE_4];
  6110. const shopPopup = new selfGame["game.mechanics.brawl.mediator.BrawlShopPopupMediator"](player, shop)
  6111. shopPopup.open(new selfGame["game.mediator.gui.popup.PopupStashEventParams"])
  6112. }
  6113.  
  6114. /**
  6115. * Game library availability tracker
  6116. *
  6117. * Отслеживание доступности игровой библиотеки
  6118. */
  6119. function checkLibLoad() {
  6120. timeout = setTimeout(() => {
  6121. if (Game.GameModel) {
  6122. changeLib();
  6123. } else {
  6124. checkLibLoad();
  6125. }
  6126. }, 100)
  6127. }
  6128.  
  6129. /**
  6130. * Game library data spoofing
  6131. *
  6132. * Подмена данных игровой библиотеки
  6133. */
  6134. function changeLib() {
  6135. console.log('lib connect');
  6136. const originalStartFunc = Game.GameModel.prototype.start;
  6137. Game.GameModel.prototype.start = function (a, b, c) {
  6138. self.libGame = b.raw;
  6139. try {
  6140. b.raw.shop[26].requirements = null;
  6141. } catch (e) {
  6142. console.warn(e);
  6143. }
  6144. originalStartFunc.call(this, a, b, c);
  6145. }
  6146. }
  6147.  
  6148. /**
  6149. * Returns the value of a language constant
  6150. *
  6151. * Возвращает значение языковой константы
  6152. * @param {*} langConst language constant // языковая константа
  6153. * @returns
  6154. */
  6155. this.translate = function (langConst) {
  6156. return Game.Translate.translate(langConst);
  6157. }
  6158.  
  6159. connectGame();
  6160. checkLibLoad();
  6161. }
  6162.  
  6163. /**
  6164. * Auto collection of gifts
  6165. *
  6166. * Автосбор подарков
  6167. */
  6168. function getAutoGifts() {
  6169. let valName = 'giftSendIds_' + userInfo.id;
  6170.  
  6171. if (!localStorage['clearGift' + userInfo.id]) {
  6172. localStorage[valName] = '';
  6173. localStorage['clearGift' + userInfo.id] = '+';
  6174. }
  6175.  
  6176. if (!localStorage[valName]) {
  6177. localStorage[valName] = '';
  6178. }
  6179.  
  6180. /**
  6181. * Submit a request to receive gift codes
  6182. *
  6183. * Отправка запроса для получения кодов подарков
  6184. */
  6185. fetch('https://zingery.ru/heroes/getGifts.php', {
  6186. method: 'POST',
  6187. body: JSON.stringify({scriptInfo, userInfo})
  6188. }).then(
  6189. response => response.json()
  6190. ).then(
  6191. data => {
  6192. let freebieCheckCalls = {
  6193. calls: []
  6194. }
  6195. data.forEach((giftId, n) => {
  6196. if (localStorage[valName].includes(giftId)) return;
  6197. //localStorage[valName] += ';' + giftId;
  6198. freebieCheckCalls.calls.push({
  6199. name: "freebieCheck",
  6200. args: {
  6201. giftId
  6202. },
  6203. ident: giftId
  6204. });
  6205. });
  6206.  
  6207. if (!freebieCheckCalls.calls.length) {
  6208. return;
  6209. }
  6210.  
  6211. send(JSON.stringify(freebieCheckCalls), e => {
  6212. let countGetGifts = 0;
  6213. const gifts = [];
  6214. for (check of e.results) {
  6215. gifts.push(check.ident);
  6216. if (check.result.response != null) {
  6217. countGetGifts++;
  6218. }
  6219. }
  6220. const saveGifts = localStorage[valName].split(';');
  6221. localStorage[valName] = [...saveGifts, ...gifts].slice(-50).join(';');
  6222. console.log(`${I18N('GIFTS')}: ${countGetGifts}`);
  6223. });
  6224. }
  6225. )
  6226. }
  6227.  
  6228. /**
  6229. * To fill the kills in the Forge of Souls
  6230. *
  6231. * Набить килов в горниле душ
  6232. */
  6233. async function bossRatingEvent() {
  6234. const topGet = await Send(JSON.stringify({ calls: [{ name: "topGet", args: { type: "bossRatingTop", extraId: 0 }, ident: "body" }] }));
  6235. if (!topGet) {
  6236. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  6237. return;
  6238. }
  6239. const replayId = topGet.results[0].result.response[0].userData.replayId;
  6240. const result = await Send(JSON.stringify({
  6241. calls: [
  6242. { name: "battleGetReplay", args: { id: replayId }, ident: "battleGetReplay" },
  6243. { name: "heroGetAll", args: {}, ident: "heroGetAll" },
  6244. { name: "pet_getAll", args: {}, ident: "pet_getAll" },
  6245. { name: "offerGetAll", args: {}, ident: "offerGetAll" }
  6246. ]
  6247. }));
  6248. const bossEventInfo = result.results[3].result.response.find(e => e.offerType == "bossEvent");
  6249. if (!bossEventInfo) {
  6250. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  6251. return;
  6252. }
  6253. const usedHeroes = bossEventInfo.progress.usedHeroes;
  6254. const party = Object.values(result.results[0].result.response.replay.attackers);
  6255. const availableHeroes = Object.values(result.results[1].result.response).map(e => e.id);
  6256. const availablePets = Object.values(result.results[2].result.response).map(e => e.id);
  6257. const calls = [];
  6258. /**
  6259. * First pack
  6260. *
  6261. * Первая пачка
  6262. */
  6263. const args = {
  6264. heroes: [],
  6265. favor: {}
  6266. }
  6267. for (let hero of party) {
  6268. if (hero.id >= 6000 && availablePets.includes(hero.id)) {
  6269. args.pet = hero.id;
  6270. continue;
  6271. }
  6272. if (!availableHeroes.includes(hero.id) || usedHeroes.includes(hero.id)) {
  6273. continue;
  6274. }
  6275. args.heroes.push(hero.id);
  6276. if (hero.favorPetId) {
  6277. args.favor[hero.id] = hero.favorPetId;
  6278. }
  6279. }
  6280. if (args.heroes.length) {
  6281. calls.push({
  6282. name: "bossRatingEvent_startBattle",
  6283. args,
  6284. ident: "body_0"
  6285. });
  6286. }
  6287. /**
  6288. * Other packs
  6289. *
  6290. * Другие пачки
  6291. */
  6292. let heroes = [];
  6293. let count = 1;
  6294. while (heroId = availableHeroes.pop()) {
  6295. if (args.heroes.includes(heroId) || usedHeroes.includes(heroId)) {
  6296. continue;
  6297. }
  6298. heroes.push(heroId);
  6299. if (heroes.length == 5) {
  6300. calls.push({
  6301. name: "bossRatingEvent_startBattle",
  6302. args: {
  6303. heroes: [...heroes],
  6304. pet: availablePets[Math.floor(Math.random() * availablePets.length)]
  6305. },
  6306. ident: "body_" + count
  6307. });
  6308. heroes = [];
  6309. count++;
  6310. }
  6311. }
  6312.  
  6313. if (!calls.length) {
  6314. setProgress(`${I18N('NO_HEROES')}`, true);
  6315. return;
  6316. }
  6317.  
  6318. const resultBattles = await Send(JSON.stringify({ calls }));
  6319. console.log(resultBattles);
  6320. rewardBossRatingEvent();
  6321. }
  6322.  
  6323. /**
  6324. * Collecting Rewards from the Forge of Souls
  6325. *
  6326. * Сбор награды из Горнила Душ
  6327. */
  6328. function rewardBossRatingEvent() {
  6329. let rewardBossRatingCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  6330. send(rewardBossRatingCall, function (data) {
  6331. let bossEventInfo = data.results[0].result.response.find(e => e.offerType == "bossEvent");
  6332. if (!bossEventInfo) {
  6333. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  6334. return;
  6335. }
  6336.  
  6337. let farmedChests = bossEventInfo.progress.farmedChests;
  6338. let score = bossEventInfo.progress.score;
  6339. setProgress(`${I18N('DAMAGE_AMOUNT')}: ${score}`);
  6340. let revard = bossEventInfo.reward;
  6341.  
  6342. let getRewardCall = {
  6343. calls: []
  6344. }
  6345.  
  6346. let count = 0;
  6347. for (let i = 1; i < 10; i++) {
  6348. if (farmedChests.includes(i)) {
  6349. continue;
  6350. }
  6351. if (score < revard[i].score) {
  6352. break;
  6353. }
  6354. getRewardCall.calls.push({
  6355. name: "bossRatingEvent_getReward",
  6356. args: {
  6357. rewardId: i
  6358. },
  6359. ident: "body_" + i
  6360. });
  6361. count++;
  6362. }
  6363. if (!count) {
  6364. setProgress(`${I18N('NOTHING_TO_COLLECT')}`, true);
  6365. return;
  6366. }
  6367.  
  6368. send(JSON.stringify(getRewardCall), e => {
  6369. console.log(e);
  6370. setProgress(`${I18N('COLLECTED')} ${e?.results?.length} ${I18N('REWARD')}`, true);
  6371. });
  6372. });
  6373. }
  6374.  
  6375. /**
  6376. * Collect Easter eggs and event rewards
  6377. *
  6378. * Собрать пасхалки и награды событий
  6379. */
  6380. function offerFarmAllReward() {
  6381. const offerGetAllCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  6382. return Send(offerGetAllCall).then((data) => {
  6383. const offerGetAll = data.results[0].result.response.filter(e => e.type == "reward" && !e?.freeRewardObtained && e.reward);
  6384. if (!offerGetAll.length) {
  6385. setProgress(`${I18N('NOTHING_TO_COLLECT')}`, true);
  6386. return;
  6387. }
  6388.  
  6389. const calls = [];
  6390. for (let reward of offerGetAll) {
  6391. calls.push({
  6392. name: "offerFarmReward",
  6393. args: {
  6394. offerId: reward.id
  6395. },
  6396. ident: "offerFarmReward_" + reward.id
  6397. });
  6398. }
  6399.  
  6400. return Send(JSON.stringify({ calls })).then(e => {
  6401. console.log(e);
  6402. setProgress(`${I18N('COLLECTED')} ${e?.results?.length} ${I18N('REWARD')}`, true);
  6403. });
  6404. });
  6405. }
  6406.  
  6407. /**
  6408. * Assemble Outland
  6409. *
  6410. * Собрать запределье
  6411. */
  6412. function getOutland() {
  6413. return new Promise(function (resolve, reject) {
  6414. send('{"calls":[{"name":"bossGetAll","args":{},"ident":"bossGetAll"}]}', e => {
  6415. let bosses = e.results[0].result.response;
  6416.  
  6417. let bossRaidOpenChestCall = {
  6418. calls: []
  6419. };
  6420.  
  6421. for (let boss of bosses) {
  6422. if (boss.mayRaid) {
  6423. bossRaidOpenChestCall.calls.push({
  6424. name: "bossRaid",
  6425. args: {
  6426. bossId: boss.id
  6427. },
  6428. ident: "bossRaid_" + boss.id
  6429. });
  6430. bossRaidOpenChestCall.calls.push({
  6431. name: "bossOpenChest",
  6432. args: {
  6433. bossId: boss.id,
  6434. amount: 1,
  6435. starmoney: 0
  6436. },
  6437. ident: "bossOpenChest_" + boss.id
  6438. });
  6439. } else if (boss.chestId == 1) {
  6440. bossRaidOpenChestCall.calls.push({
  6441. name: "bossOpenChest",
  6442. args: {
  6443. bossId: boss.id,
  6444. amount: 1,
  6445. starmoney: 0
  6446. },
  6447. ident: "bossOpenChest_" + boss.id
  6448. });
  6449. }
  6450. }
  6451.  
  6452. if (!bossRaidOpenChestCall.calls.length) {
  6453. setProgress(`${I18N('OUTLAND')} ${I18N('NOTHING_TO_COLLECT')}`, true);
  6454. resolve();
  6455. return;
  6456. }
  6457.  
  6458. send(JSON.stringify(bossRaidOpenChestCall), e => {
  6459. setProgress(`${I18N('OUTLAND')} ${I18N('COLLECTED')}`, true);
  6460. resolve();
  6461. });
  6462. });
  6463. });
  6464. }
  6465.  
  6466. /**
  6467. * Collect all rewards
  6468. *
  6469. * Собрать все награды
  6470. */
  6471. function questAllFarm() {
  6472. return new Promise(function (resolve, reject) {
  6473. let questGetAllCall = {
  6474. calls: [{
  6475. name: "questGetAll",
  6476. args: {},
  6477. ident: "body"
  6478. }]
  6479. }
  6480. send(JSON.stringify(questGetAllCall), function (data) {
  6481. let questGetAll = data.results[0].result.response;
  6482. const questAllFarmCall = {
  6483. calls: []
  6484. }
  6485. let number = 0;
  6486. for (let quest of questGetAll) {
  6487. if (quest.id < 1e6 && quest.state == 2) {
  6488. questAllFarmCall.calls.push({
  6489. name: "questFarm",
  6490. args: {
  6491. questId: quest.id
  6492. },
  6493. ident: `group_${number}_body`
  6494. });
  6495. number++;
  6496. }
  6497. }
  6498.  
  6499. if (!questAllFarmCall.calls.length) {
  6500. setProgress(`${I18N('COLLECTED')} ${number} ${I18N('REWARD')}`, true);
  6501. resolve();
  6502. return;
  6503. }
  6504.  
  6505. send(JSON.stringify(questAllFarmCall), function (res) {
  6506. console.log(res);
  6507. setProgress(`${I18N('COLLECTED')} ${number} ${I18N('REWARD')}`, true);
  6508. resolve();
  6509. });
  6510. });
  6511. })
  6512. }
  6513.  
  6514. /**
  6515. * Mission auto repeat
  6516. *
  6517. * Автоповтор миссии
  6518. * isStopSendMission = false;
  6519. * isSendsMission = true;
  6520. **/
  6521. this.sendsMission = async function (param) {
  6522. if (isStopSendMission) {
  6523. isSendsMission = false;
  6524. console.log(I18N('STOPPED'));
  6525. setProgress('');
  6526. await popup.confirm(`${I18N('STOPPED')}<br>${I18N('REPETITIONS')}: ${param.count}`, [{
  6527. msg: 'Ok',
  6528. result: true
  6529. }, ])
  6530. return;
  6531. }
  6532.  
  6533. let missionStartCall = {
  6534. "calls": [{
  6535. "name": "missionStart",
  6536. "args": lastMissionStart,
  6537. "ident": "body"
  6538. }]
  6539. }
  6540. /**
  6541. * Mission Request
  6542. *
  6543. * Запрос на выполнение мисии
  6544. */
  6545. SendRequest(JSON.stringify(missionStartCall), async e => {
  6546. if (e['error']) {
  6547. isSendsMission = false;
  6548. console.log(e['error']);
  6549. setProgress('');
  6550. let msg = e['error'].name + ' ' + e['error'].description + `<br>${I18N('REPETITIONS')}: ${param.count}`;
  6551. await popup.confirm(msg, [
  6552. {msg: 'Ok', result: true},
  6553. ])
  6554. return;
  6555. }
  6556. /**
  6557. * Mission data calculation
  6558. *
  6559. * Расчет данных мисии
  6560. */
  6561. BattleCalc(e.results[0].result.response, 'get_tower', async r => {
  6562.  
  6563. let missionEndCall = {
  6564. "calls": [{
  6565. "name": "missionEnd",
  6566. "args": {
  6567. "id": param.id,
  6568. "result": r.result,
  6569. "progress": r.progress
  6570. },
  6571. "ident": "body"
  6572. }]
  6573. }
  6574. /**
  6575. * Mission Completion Request
  6576. *
  6577. * Запрос на завершение миссии
  6578. */
  6579. SendRequest(JSON.stringify(missionEndCall), async (e) => {
  6580. if (e['error']) {
  6581. isSendsMission = false;
  6582. console.log(e['error']);
  6583. setProgress('');
  6584. let msg = e['error'].name + ' ' + e['error'].description + `<br>${I18N('REPETITIONS')}: ${param.count}`;
  6585. await popup.confirm(msg, [
  6586. {msg: 'Ok', result: true},
  6587. ])
  6588. return;
  6589. }
  6590. r = e.results[0].result.response;
  6591. if (r['error']) {
  6592. isSendsMission = false;
  6593. console.log(r['error']);
  6594. setProgress('');
  6595. await popup.confirm(`<br>${I18N('REPETITIONS')}: ${param.count}` + ' 3 ' + r['error'], [
  6596. {msg: 'Ok', result: true},
  6597. ])
  6598. return;
  6599. }
  6600.  
  6601. param.count++;
  6602. let RaidMission = getInput('countRaid');
  6603.  
  6604. if (RaidMission==param.count){
  6605. isStopSendMission = true;
  6606. console.log(RaidMission);
  6607. }
  6608. setProgress(`${I18N('MISSIONS_PASSED')}: ${param.count} (${I18N('STOP')})`, false, () => {
  6609. isStopSendMission = true;
  6610. });
  6611. setTimeout(sendsMission, 1, param);
  6612. });
  6613. })
  6614. });
  6615. }
  6616.  
  6617. /**
  6618. * Recursive opening of matryoshka dolls
  6619. *
  6620. * Рекурсивное открытие матрешек
  6621. */
  6622. async function openRussianDolls(libId, amount) {
  6623. let sum = 0;
  6624. let sumResult = [];
  6625. while (amount) {
  6626. sum += amount;
  6627. setProgress(`${I18N('TOTAL_OPEN')} ${sum}`);
  6628. const calls = [{
  6629. name: "consumableUseLootBox",
  6630. args: { libId, amount },
  6631. ident: "body"
  6632. }];
  6633. const result = await Send(JSON.stringify({ calls })).then(e => e.results[0].result.response);
  6634. let newCount = 0;
  6635. for (let n of result) {
  6636. if (n?.consumable && n.consumable[libId]) {
  6637. newCount += n.consumable[libId]
  6638. }
  6639. }
  6640. sumResult = [...sumResult, ...result];
  6641. amount = newCount;
  6642. }
  6643. setProgress(`${I18N('TOTAL_OPEN')} ${sum}`, 5000);
  6644. return sumResult;
  6645. }
  6646.  
  6647. /**
  6648. * Collect all mail, except letters with energy and charges of the portal
  6649. *
  6650. * Собрать всю почту, кроме писем с энергией и зарядами портала
  6651. */
  6652. function mailGetAll() {
  6653. const getMailInfo = '{"calls":[{"name":"mailGetAll","args":{},"ident":"body"}]}';
  6654.  
  6655. return Send(getMailInfo).then(dataMail => {
  6656. const letters = dataMail.results[0].result.response.letters;
  6657. const letterIds = lettersFilter(letters);
  6658. if (!letterIds.length) {
  6659. setProgress(I18N('NOTHING_TO_COLLECT'), true);
  6660. return;
  6661. }
  6662.  
  6663. const calls = [
  6664. { name: "mailFarm", args: { letterIds }, ident: "body" }
  6665. ];
  6666.  
  6667. return Send(JSON.stringify({ calls })).then(res => {
  6668. const lettersIds = res.results[0].result.response;
  6669. if (lettersIds) {
  6670. const countLetters = Object.keys(lettersIds).length;
  6671. setProgress(`${I18N('RECEIVED')} ${countLetters} ${I18N('LETTERS')}`, true);
  6672. }
  6673. });
  6674. });
  6675. }
  6676.  
  6677. /**
  6678. * Filters received emails
  6679. *
  6680. * Фильтрует получаемые письма
  6681. */
  6682. function lettersFilter(letters) {
  6683. const lettersIds = [];
  6684. for (let l in letters) {
  6685. letter = letters[l];
  6686. const reward = letter.reward;
  6687. /**
  6688. * Mail Collection Exceptions
  6689. *
  6690. * Исключения на сбор писем
  6691. */
  6692. const isFarmLetter = !(
  6693. /** Portals // сферы портала */
  6694. (reward?.refillable ? reward.refillable[45] : false) ||
  6695. /** Energy // энергия */
  6696. (reward?.stamina ? reward.stamina : false) ||
  6697. /** accelerating energy gain // ускорение набора энергии */
  6698. (reward?.buff ? true : false) ||
  6699. /** VIP Points // вип очки */
  6700. (reward?.vipPoints ? reward.vipPoints : false) ||
  6701. /** souls of heroes // душы героев */
  6702. (reward?.fragmentHero ? true : false) ||
  6703. /** heroes // герои */
  6704. (reward?.bundleHeroReward ? true : false)
  6705. );
  6706. if (isFarmLetter) {
  6707. lettersIds.push(~~letter.id);
  6708. }
  6709. }
  6710. return lettersIds;
  6711. }
  6712.  
  6713. /**
  6714. * Displaying information about the areas of the portal and attempts on the VG
  6715. *
  6716. * Отображение информации о сферах портала и попытках на ВГ
  6717. */
  6718. async function justInfo() {
  6719. return new Promise(async (resolve, reject) => {
  6720. const calls = [{
  6721. name: "userGetInfo",
  6722. args: {},
  6723. ident: "userGetInfo"
  6724. },
  6725. {
  6726. name: "clanWarGetInfo",
  6727. args: {},
  6728. ident: "clanWarGetInfo"
  6729. }];
  6730. const result = await Send(JSON.stringify({ calls }));
  6731. const infos = result.results;
  6732. const portalSphere = infos[0].result.response.refillable.find(n => n.id == 45);
  6733. const clanWarMyTries = infos[1].result.response?.myTries ?? 0;
  6734. const sanctuaryButton = buttons['goToSanctuary'].button;
  6735. const clanWarButton = buttons['goToClanWar'].button;
  6736. /*if (portalSphere.amount) {
  6737. sanctuaryButton.style.color = portalSphere.amount >= 3 ? 'red' : 'brown';
  6738. sanctuaryButton.title = `${I18N('SANCTUARY_TITLE')}\n${portalSphere.amount} ${I18N('PORTALS')}`;
  6739. } else {*/
  6740. sanctuaryButton.style.color = '';
  6741. sanctuaryButton.title = I18N('SANCTUARY_TITLE');
  6742. //}
  6743. /*if (clanWarMyTries) {
  6744. clanWarButton.style.color = 'red';
  6745. clanWarButton.title = `${I18N('GUILD_WAR_TITLE')}\n${clanWarMyTries}${I18N('ATTEMPTS')}`;
  6746. } else {*/
  6747. clanWarButton.style.color = '';
  6748. clanWarButton.title = I18N('GUILD_WAR_TITLE');
  6749. //}
  6750. //тест убрал подсветку красным в меню
  6751. setProgress('<img src="https://zingery.ru/heroes/portal.png" style="height: 25px;position: relative;top: 5px;"> ' + `${portalSphere.amount} </br> ${I18N('GUILD_WAR')}: ${clanWarMyTries}`, true);
  6752. resolve();
  6753. });
  6754. }
  6755. // тест сделать все
  6756. /** Отправить подарки мое*/
  6757. function testclanSendDailyGifts() {
  6758.  
  6759. send('{"calls":[{"name":"clanSendDailyGifts","args":{},"ident":"clanSendDailyGifts"}]}', e => {
  6760. setProgress('Награды собраны', true);});
  6761. }
  6762. /** Открой сферу артефактов титанов*/
  6763. function testtitanArtifactChestOpen() {
  6764. send('{"calls":[{"name":"titanArtifactChestOpen","args":{"amount":1,"free":true},"ident":"body"}]}',
  6765. isWeCanDo => {
  6766. return info['inventoryGet']?.consumable[55] > 0
  6767. //setProgress('Награды собраны', true);
  6768. });
  6769. }
  6770. /** Воспользуйся призывом питомцев 1 раз*/
  6771. function testpet_chestOpen() {
  6772. send('{"calls":[{"name":"pet_chestOpen","args":{"amount":1,"paid":false},"ident":"pet_chestOpen"}]}',
  6773. isWeCanDo => {
  6774. return info['inventoryGet']?.consumable[90] > 0
  6775. //setProgress('Награды собраны', true);
  6776. });
  6777. }
  6778. async function buyWithPetExperience() {
  6779. const itemLib = lib.getData('inventoryItem');
  6780. const result = await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"},{"name":"shopGet","args":{"shopId":"26"},"ident":"shopGet"}]}').then(e => e.results.map(n => n.result.response));
  6781. const inventory = result[0];
  6782. const shop = result[1];
  6783. const slot = shop.slots[2];
  6784.  
  6785. const currentCount = inventory.consumable[85];
  6786. const price = slot.cost.consumable[85];
  6787.  
  6788. const typeBuyItem = Object.keys(slot.reward).pop();
  6789. const itemIdBuyItem = Object.keys(slot.reward[typeBuyItem]).pop();
  6790. const countBuyItem = slot.reward[typeBuyItem][itemIdBuyItem];
  6791. const itemName = cheats.translate(`LIB_${typeBuyItem.toUpperCase()}_NAME_${itemIdBuyItem}`);
  6792.  
  6793. if (slot.bought) {
  6794. await popup.confirm(I18N('SECRET_WEALTH_ALREADY'), [
  6795. { msg: 'Ok', result: true },
  6796. ]);
  6797. return;
  6798. }
  6799.  
  6800. const purchaseMsg = I18N('SECRET_WEALTH_BUY', { available: currentCount, countBuy: countBuyItem, name: itemName, price })
  6801. const answer = await popup.confirm(purchaseMsg, [
  6802. { msg: I18N('BTN_NO'), result: false },
  6803. { msg: I18N('BTN_YES'), result: true },
  6804. ]);
  6805.  
  6806. if (!answer) {
  6807. setProgress(I18N('SECRET_WEALTH_CANCELED'), true);
  6808. return;
  6809. }
  6810.  
  6811. if (currentCount < price) {
  6812. const msg = I18N('SECRET_WEALTH_NOT_ENOUGH', { available: currentCount, need: price });
  6813. await popup.confirm(msg, [
  6814. { msg: 'Ok', result: true },
  6815. ]);
  6816. return;
  6817. }
  6818.  
  6819. const calls = [{
  6820. name: "shopBuy",
  6821. args: {
  6822. shopId: 26,
  6823. slot: 2,
  6824. cost: slot.cost,
  6825. reward: slot.reward
  6826. },
  6827. ident: "body"
  6828. }];
  6829. const bought = await Send(JSON.stringify({ calls })).then(e => e.results[0].result.response);
  6830.  
  6831. const type = Object.keys(bought).pop();
  6832. const itemId = Object.keys(bought[type]).pop();
  6833. const count = bought[type][itemId];
  6834.  
  6835. const resultMsg = I18N('SECRET_WEALTH_PURCHASED', { count, name: itemName });
  6836. await popup.confirm(resultMsg, [
  6837. { msg: 'Ok', result: true },
  6838. ]);
  6839. }
  6840.  
  6841. async function buyWithPetExperienceAuto() {
  6842. const itemLib = lib.getData('inventoryItem');
  6843. const minCount = 450551;
  6844. const result = await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"},{"name":"shopGet","args":{"shopId":"26"},"ident":"shopGet"}]}').then(e => e.results.map(n => n.result.response));
  6845. const inventory = result[0];
  6846. const shop = result[1];
  6847. const slot = shop.slots[2];
  6848.  
  6849. const currentCount = inventory.consumable[85];
  6850. const price = slot.cost.consumable[85];
  6851.  
  6852. if (slot.bought) {
  6853. console.log(I18N('SECRET_WEALTH_ALREADY'));
  6854. setProgress(I18N('SECRET_WEALTH_ALREADY'), true);
  6855. return;
  6856. }
  6857.  
  6858. if (currentCount < price) {
  6859. const msg = I18N('SECRET_WEALTH_NOT_ENOUGH', { available: currentCount, need: price });
  6860. console.log(msg);
  6861. setProgress(msg, true);
  6862. return;
  6863. }
  6864.  
  6865. if ((currentCount - price) < minCount) {
  6866. console.log(I18N('SECRET_WEALTH_UPGRADE_NEW_PET'));
  6867. setProgress(I18N('SECRET_WEALTH_UPGRADE_NEW_PET'), true);
  6868. return;
  6869. }
  6870.  
  6871. const calls = [{
  6872. name: "shopBuy",
  6873. args: {
  6874. shopId: 26,
  6875. slot: 2,
  6876. cost: slot.cost,
  6877. reward: slot.reward
  6878. },
  6879. ident: "body"
  6880. }];
  6881. const bought = await Send(JSON.stringify({ calls })).then(e => e.results[0].result.response);
  6882.  
  6883. const type = Object.keys(bought).pop();
  6884. const itemId = Object.keys(bought[type]).pop();
  6885. const count = bought[type][itemId];
  6886. const itemName = itemLib[type][itemId].label;
  6887.  
  6888. const resultMsg = I18N('SECRET_WEALTH_PURCHASED', { count, name: itemName });
  6889. console.log(resultMsg, bought);
  6890. setProgress(resultMsg, true);
  6891. }
  6892.  
  6893. async function getDailyBonus() {
  6894. const dailyBonusInfo = await Send(JSON.stringify({
  6895. calls: [{
  6896. name: "dailyBonusGetInfo",
  6897. args: {},
  6898. ident: "body"
  6899. }]
  6900. })).then(e => e.results[0].result.response);
  6901. const { availableToday, availableVip, currentDay } = dailyBonusInfo;
  6902.  
  6903. if (!availableToday) {
  6904. console.log('Уже собрано');
  6905. return;
  6906. }
  6907.  
  6908. const currentVipPoints = +userInfo.vipPoints;
  6909. const dailyBonusStat = lib.getData('dailyBonusStatic');
  6910. const vipInfo = lib.getData('level').vip;
  6911. let currentVipLevel = 0;
  6912. for (let i in vipInfo) {
  6913. vipLvl = vipInfo[i];
  6914. if (currentVipPoints >= vipLvl.vipPoints) {
  6915. currentVipLevel = vipLvl.level;
  6916. }
  6917. }
  6918. const vipLevelDouble = dailyBonusStat[`${currentDay}_0_0`].vipLevelDouble;
  6919.  
  6920. const calls = [{
  6921. name: "dailyBonusFarm",
  6922. args: {
  6923. vip: availableVip && currentVipLevel >= vipLevelDouble ? 1 : 0
  6924. },
  6925. ident: "body"
  6926. }];
  6927.  
  6928. const result = await Send(JSON.stringify({ calls }));
  6929. if (result.error) {
  6930. console.error(result.error);
  6931. return;
  6932. }
  6933.  
  6934. const reward = result.results[0].result.response;
  6935. const type = Object.keys(reward).pop();
  6936. const itemId = Object.keys(reward[type]).pop();
  6937. const count = reward[type][itemId];
  6938. const itemName = cheats.translate(`LIB_${type.toUpperCase()}_NAME_${itemId}`);
  6939.  
  6940. console.log(`Ежедневная награда: Получено ${count} ${itemName}`, reward);
  6941. }
  6942.  
  6943. async function farmStamina() {
  6944. const lootBox = await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"}]}')
  6945. .then(e => e.results[0].result.response.consumable[148]);
  6946.  
  6947. /** Добавить другие ящики */
  6948. if (!lootBox) {
  6949. setProgress(I18N('NO_BOXES'), true);
  6950. return;
  6951. }
  6952.  
  6953. const isOpening = await popup.confirm(I18N('OPEN_LOOTBOX', { lootBox }), [
  6954. { result: false, isClose: true },
  6955. { msg: I18N('BTN_YES'), result: true },
  6956. ]);
  6957.  
  6958. if (!isOpening) {
  6959. return;
  6960. }
  6961.  
  6962. for (let count = lootBox; count > 0; count--) {
  6963. const result = await Send('{"calls":[{"name":"consumableUseLootBox","args":{"libId":148,"amount":1},"ident":"body"}]}')
  6964. .then(e => e.results[0].result.response[0]);
  6965. if ('stamina' in result) {
  6966. setProgress(`${I18N('OPEN')}: ${lootBox - count}/${lootBox} ${I18N('STAMINA')} +${result.stamina}`, true);
  6967. console.log('stamina +' + result.stamina);
  6968. return;
  6969. } else {
  6970. setProgress(`${I18N('OPEN')}: ${lootBox - count}/${lootBox}`, false);
  6971. console.log(result);
  6972. }
  6973. }
  6974.  
  6975. setProgress(I18N('BOXES_OVER'), true);
  6976. }
  6977.  
  6978. async function fillActive() {
  6979. const data = await Send(JSON.stringify({
  6980. calls: [{
  6981. name: "questGetAll",
  6982. args: {},
  6983. ident: "questGetAll"
  6984. }, {
  6985. name: "inventoryGet",
  6986. args: {},
  6987. ident: "inventoryGet"
  6988. }, {
  6989. name: "clanGetInfo",
  6990. args: {},
  6991. ident: "clanGetInfo"
  6992. }
  6993. ]
  6994. })).then(e => e.results.map(n => n.result.response));
  6995.  
  6996. const quests = data[0];
  6997. const inv = data[1];
  6998. const stat = data[2].stat;
  6999. const maxActive = 2000 - stat.todayItemsActivity;
  7000. if (maxActive <= 0) {
  7001. setProgress(I18N('NO_MORE_ACTIVITY'), true);
  7002. return;
  7003. }
  7004.  
  7005. let countGetActive = 0;
  7006. const quest = quests.find(e => e.id > 10046 && e.id < 10051);
  7007. if (quest) {
  7008. countGetActive = 1750 - quest.progress;
  7009. }
  7010.  
  7011. if (countGetActive <= 0) {
  7012. countGetActive = maxActive;
  7013. }
  7014. console.log(countGetActive);
  7015.  
  7016. countGetActive = +(await popup.confirm(I18N('EXCHANGE_ITEMS', { maxActive }), [
  7017. { result: false, isClose: true },
  7018. { msg: I18N('GET_ACTIVITY'), isInput: true, default: countGetActive.toString() },
  7019. ]));
  7020.  
  7021. if (!countGetActive) {
  7022. return;
  7023. }
  7024.  
  7025. if (countGetActive > maxActive) {
  7026. countGetActive = maxActive;
  7027. }
  7028.  
  7029. const items = lib.getData('inventoryItem');
  7030.  
  7031. let itemsInfo = [];
  7032. for (let type of ['gear', 'scroll']) {
  7033. for (let i in inv[type]) {
  7034. const v = items[type][i]?.enchantValue || 0;
  7035. itemsInfo.push({
  7036. id: i,
  7037. count: inv[type][i],
  7038. v,
  7039. type
  7040. })
  7041. }
  7042. const invType = 'fragment' + type.toLowerCase().charAt(0).toUpperCase() + type.slice(1);
  7043. for (let i in inv[invType]) {
  7044. const v = items[type][i]?.fragmentEnchantValue || 0;
  7045. itemsInfo.push({
  7046. id: i,
  7047. count: inv[invType][i],
  7048. v,
  7049. type: invType
  7050. })
  7051. }
  7052. }
  7053. itemsInfo = itemsInfo.filter(e => e.v < 4 && e.count > 200);
  7054. itemsInfo = itemsInfo.sort((a, b) => b.count - a.count);
  7055. console.log(itemsInfo);
  7056. const activeItem = itemsInfo.shift();
  7057. console.log(activeItem);
  7058. const countItem = Math.ceil(countGetActive / activeItem.v);
  7059. if (countItem > activeItem.count) {
  7060. setProgress(I18N('NOT_ENOUGH_ITEMS'), true);
  7061. console.log(activeItem);
  7062. return;
  7063. }
  7064.  
  7065. await Send(JSON.stringify({
  7066. calls: [{
  7067. name: "clanItemsForActivity",
  7068. args: {
  7069. items: {
  7070. [activeItem.type]: {
  7071. [activeItem.id]: countItem
  7072. }
  7073. }
  7074. },
  7075. ident: "body"
  7076. }]
  7077. })).then(e => {
  7078. /** TODO: Вывести потраченые предметы */
  7079. console.log(e);
  7080. setProgress(`${I18N('ACTIVITY_RECEIVED')}: ` + e.results[0].result.response, true);
  7081. });
  7082. }
  7083.  
  7084. async function buyHeroFragments() {
  7085. const result = await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"},{"name":"shopGetAll","args":{},"ident":"shopGetAll"}]}')
  7086. .then(e => e.results.map(n => n.result.response));
  7087. const inv = result[0];
  7088. const shops = Object.values(result[1]).filter(shop => [4, 5, 6, 8, 9, 10, 17].includes(shop.id));
  7089. const calls = [];
  7090.  
  7091. for (let shop of shops) {
  7092. const slots = Object.values(shop.slots);
  7093. for (const slot of slots) {
  7094. /* Уже куплено */
  7095. if (slot.bought) {
  7096. continue;
  7097. }
  7098. /* Не душа героя */
  7099. if (!('fragmentHero' in slot.reward)) {
  7100. continue;
  7101. }
  7102. const coin = Object.keys(slot.cost).pop();
  7103. const coinId = Object.keys(slot.cost[coin]).pop();
  7104. const stock = inv[coin][coinId] || 0;
  7105. /* Не хватает на покупку */
  7106. if (slot.cost[coin][coinId] > stock) {
  7107. continue;
  7108. }
  7109. inv[coin][coinId] -= slot.cost[coin][coinId];
  7110. calls.push({
  7111. name: "shopBuy",
  7112. args: {
  7113. shopId: shop.id,
  7114. slot: slot.id,
  7115. cost: slot.cost,
  7116. reward: slot.reward,
  7117. },
  7118. ident: `shopBuy_${shop.id}_${slot.id}`,
  7119. })
  7120. }
  7121. }
  7122.  
  7123. if (!calls.length) {
  7124. setProgress(I18N('NO_PURCHASABLE_HERO_SOULS'), true);
  7125. return;
  7126. }
  7127.  
  7128. const bought = await Send(JSON.stringify({ calls })).then(e => e.results.map(n => n.result.response));
  7129. if (!bought) {
  7130. console.log('что-то пошло не так')
  7131. return;
  7132. }
  7133.  
  7134. let countHeroSouls = 0;
  7135. for (const buy of bought) {
  7136. countHeroSouls += +Object.values(Object.values(buy).pop()).pop();
  7137. }
  7138. console.log(countHeroSouls, bought, calls);
  7139. setProgress(I18N('PURCHASED_HERO_SOULS', { countHeroSouls }), true);
  7140. }
  7141.  
  7142. /** Открыть платные сундуки в Запределье за 90 */
  7143. async function bossOpenChestPay() {
  7144. const info = await Send('{"calls":[{"name":"userGetInfo","args":{},"ident":"userGetInfo"},{"name":"bossGetAll","args":{},"ident":"bossGetAll"}]}')
  7145. .then(e => e.results.map(n => n.result.response));
  7146.  
  7147. const user = info[0];
  7148. const boses = info[1];
  7149.  
  7150. const currentStarMoney = user.starMoney;
  7151. if (currentStarMoney < 540) {
  7152. setProgress(I18N('NOT_ENOUGH_EMERALDS_540', { currentStarMoney }), true);
  7153. return;
  7154. }
  7155.  
  7156. const calls = [];
  7157.  
  7158. let n = 0;
  7159. const amount = 1;
  7160. for (let boss of boses) {
  7161. const bossId = boss.id;
  7162. if (boss.chestNum != 2) {
  7163. continue;
  7164. }
  7165. for (const starmoney of [90, 90, 0]) {
  7166. calls.push({
  7167. name: "bossOpenChest",
  7168. args: {
  7169. bossId,
  7170. amount,
  7171. starmoney
  7172. },
  7173. ident: "bossOpenChest_" + (++n)
  7174. });
  7175. }
  7176. }
  7177.  
  7178. if (!calls.length) {
  7179. setProgress(I18N('CHESTS_NOT_AVAILABLE'), true);
  7180. return;
  7181. }
  7182.  
  7183. const result = await Send(JSON.stringify({ calls }));
  7184. console.log(result);
  7185. if (result?.results) {
  7186. setProgress(`${I18N('OUTLAND_CHESTS_RECEIVED')}: ` + result.results.length, true);
  7187. } else {
  7188. setProgress(I18N('CHESTS_NOT_AVAILABLE'), true);
  7189. }
  7190. }
  7191.  
  7192. async function autoRaidAdventure() {
  7193. const calls = [
  7194. {
  7195. name: "userGetInfo",
  7196. args: {},
  7197. ident: "userGetInfo"
  7198. },
  7199. {
  7200. name: "adventure_raidGetInfo",
  7201. args: {},
  7202. ident: "adventure_raidGetInfo"
  7203. }
  7204. ];
  7205. const result = await Send(JSON.stringify({ calls }))
  7206. .then(e => e.results.map(n => n.result.response));
  7207.  
  7208. const portalSphere = result[0].refillable.find(n => n.id == 45);
  7209. const adventureRaid = Object.entries(result[1].raid).filter(e => e[1]).pop()
  7210. const adventureId = adventureRaid ? adventureRaid[0] : 0;
  7211.  
  7212. if (!portalSphere.amount || !adventureId) {
  7213. setProgress(I18N('RAID_NOT_AVAILABLE'), true);
  7214. return;
  7215. }
  7216.  
  7217. const countRaid = +(await popup.confirm(I18N('RAID_ADVENTURE', { adventureId }), [
  7218. { result: false, isClose: true },
  7219. { msg: 'Рейд', isInput: true, default: portalSphere.amount },
  7220. ]));
  7221.  
  7222. if (!countRaid) {
  7223. return;
  7224. }
  7225.  
  7226. if (countRaid > portalSphere.amount) {
  7227. countRaid = portalSphere.amount;
  7228. }
  7229.  
  7230. const resultRaid = await Send(JSON.stringify({
  7231. calls: [...Array(countRaid)].map((e, i) => ({
  7232. name: "adventure_raid",
  7233. args: {
  7234. adventureId
  7235. },
  7236. ident: `body_${i}`
  7237. }))
  7238. })).then(e => e.results.map(n => n.result.response));
  7239.  
  7240. if (!resultRaid.length) {
  7241. console.log(resultRaid);
  7242. setProgress(I18N('SOMETHING_WENT_WRONG'), true);
  7243. return;
  7244. }
  7245.  
  7246. console.log(resultRaid, adventureId, portalSphere.amount);
  7247. setProgress(I18N('ADVENTURE_COMPLETED', { adventureId, times: resultRaid.length }), true);
  7248. }
  7249.  
  7250. /** Вывести всю клановую статистику в консоль браузера */
  7251. async function clanStatistic() {
  7252. const copy = function (text) {
  7253. const copyTextarea = document.createElement("textarea");
  7254. copyTextarea.style.opacity = "0";
  7255. copyTextarea.textContent = text;
  7256. document.body.appendChild(copyTextarea);
  7257. copyTextarea.select();
  7258. document.execCommand("copy");
  7259. document.body.removeChild(copyTextarea);
  7260. delete copyTextarea;
  7261. }
  7262. const calls = [
  7263. { name: "clanGetInfo", args: {}, ident: "clanGetInfo" },
  7264. { name: "clanGetWeeklyStat", args: {}, ident: "clanGetWeeklyStat" },
  7265. { name: "clanGetLog", args: {}, ident: "clanGetLog" },
  7266. ];
  7267.  
  7268. const result = await Send(JSON.stringify({ calls }));
  7269.  
  7270. const dataClanInfo = result.results[0].result.response;
  7271. const dataClanStat = result.results[1].result.response;
  7272. const dataClanLog = result.results[2].result.response;
  7273.  
  7274. const membersStat = {};
  7275. for (let i = 0; i < dataClanStat.stat.length; i++) {
  7276. membersStat[dataClanStat.stat[i].id] = dataClanStat.stat[i];
  7277. }
  7278.  
  7279. const joinStat = {};
  7280. historyLog = dataClanLog.history;
  7281. for (let j in historyLog) {
  7282. his = historyLog[j];
  7283. if (his.event == 'join') {
  7284. joinStat[his.userId] = his.ctime;
  7285. }
  7286. }
  7287.  
  7288. const infoArr = [];
  7289. const members = dataClanInfo.clan.members;
  7290. for (let n in members) {
  7291. var member = [
  7292. n,
  7293. members[n].name,
  7294. members[n].level,
  7295. dataClanInfo.clan.warriors.includes(+n) ? 1 : 0,
  7296. (new Date(members[n].lastLoginTime * 1000)).toLocaleString().replace(',', ''),
  7297. joinStat[n] ? (new Date(joinStat[n] * 1000)).toLocaleString().replace(',', '') : '',
  7298. membersStat[n].activity.reverse().join('\t'),
  7299. membersStat[n].adventureStat.reverse().join('\t'),
  7300. membersStat[n].clanGifts.reverse().join('\t'),
  7301. membersStat[n].clanWarStat.reverse().join('\t'),
  7302. membersStat[n].dungeonActivity.reverse().join('\t'),
  7303. ];
  7304. infoArr.push(member);
  7305. }
  7306. const info = infoArr.sort((a, b) => (b[2] - a[2])).map((e) => e.join('\t')).join('\n');
  7307. console.log(info);
  7308. copy(info);
  7309. setProgress(I18N('CLAN_STAT_COPY'), true);
  7310. }
  7311.  
  7312. async function buyInStoreForGold() {
  7313. const result = await Send('{"calls":[{"name":"shopGetAll","args":{},"ident":"body"},{"name":"userGetInfo","args":{},"ident":"userGetInfo"}]}').then(e => e.results.map(n => n.result.response));
  7314. const shops = result[0];
  7315. const user = result[1];
  7316. let gold = user.gold;
  7317. const calls = [];
  7318. if (shops[17]) {
  7319. const slots = shops[17].slots;
  7320. for (let i = 1; i <= 2; i++) {
  7321. if (!slots[i].bought) {
  7322. const costGold = slots[i].cost.gold;
  7323. if ((gold - costGold) < 0) {
  7324. continue;
  7325. }
  7326. gold -= costGold;
  7327. calls.push({
  7328. name: "shopBuy",
  7329. args: {
  7330. shopId: 17,
  7331. slot: i,
  7332. cost: slots[i].cost,
  7333. reward: slots[i].reward,
  7334. },
  7335. ident: 'body_' + i,
  7336. })
  7337. }
  7338. }
  7339. }
  7340. const slots = shops[1].slots;
  7341. for (let i = 4; i <= 6; i++) {
  7342. if (!slots[i].bought && slots[i]?.cost?.gold) {
  7343. const costGold = slots[i].cost.gold;
  7344. if ((gold - costGold) < 0) {
  7345. continue;
  7346. }
  7347. gold -= costGold;
  7348. calls.push({
  7349. name: "shopBuy",
  7350. args: {
  7351. shopId: 1,
  7352. slot: i,
  7353. cost: slots[i].cost,
  7354. reward: slots[i].reward,
  7355. },
  7356. ident: 'body_' + i,
  7357. })
  7358. }
  7359. }
  7360.  
  7361. if (!calls.length) {
  7362. setProgress(I18N('NOTHING_BUY'), true);
  7363. return;
  7364. }
  7365.  
  7366. const resultBuy = await Send(JSON.stringify({ calls })).then(e => e.results.map(n => n.result.response));
  7367. console.log(resultBuy);
  7368. const countBuy = resultBuy.length;
  7369. setProgress(I18N('LOTS_BOUGHT', { countBuy }), true);
  7370. }
  7371.  
  7372. function rewardsAndMailFarm() {
  7373. return new Promise(function (resolve, reject) {
  7374. let questGetAllCall = {
  7375. calls: [{
  7376. name: "questGetAll",
  7377. args: {},
  7378. ident: "questGetAll"
  7379. }, {
  7380. name: "mailGetAll",
  7381. args: {},
  7382. ident: "mailGetAll"
  7383. }]
  7384. }
  7385. send(JSON.stringify(questGetAllCall), function (data) {
  7386. if (!data) return;
  7387. let questGetAll = data.results[0].result.response.filter(e => e.state == 2);
  7388. const questBattlePass = lib.getData('quest').battlePass;
  7389. const questChainBPass = lib.getData('battlePass').questChain;
  7390.  
  7391. const questAllFarmCall = {
  7392. calls: []
  7393. }
  7394. let number = 0;
  7395. for (let quest of questGetAll) {
  7396. if (quest.id > 1e6) {
  7397. const questInfo = questBattlePass[quest.id];
  7398. const chain = questChainBPass[questInfo.chain];
  7399. if (chain.requirement?.battlePassTicket) {
  7400. continue;
  7401. }
  7402. }
  7403. questAllFarmCall.calls.push({
  7404. name: "questFarm",
  7405. args: {
  7406. questId: quest.id
  7407. },
  7408. ident: `questFarm_${number}`
  7409. });
  7410. number++;
  7411. }
  7412.  
  7413. let letters = data?.results[1]?.result?.response?.letters;
  7414. letterIds = lettersFilter(letters);
  7415.  
  7416. if (letterIds.length) {
  7417. questAllFarmCall.calls.push({
  7418. name: "mailFarm",
  7419. args: { letterIds },
  7420. ident: "mailFarm"
  7421. })
  7422. }
  7423.  
  7424. if (!questAllFarmCall.calls.length) {
  7425. setProgress(I18N('NOTHING_TO_COLLECT'), true);
  7426. resolve();
  7427. return;
  7428. }
  7429.  
  7430. send(JSON.stringify(questAllFarmCall), function (res) {
  7431. let reSend = false;
  7432. let countQuests = 0;
  7433. let countMail = 0;
  7434. for (let call of res.results) {
  7435. if (call.ident.includes('questFarm')) {
  7436. countQuests++;
  7437. } else {
  7438. countMail = Object.keys(call.result.response).length;
  7439. }
  7440.  
  7441. /** TODO: Переписать чтоб не вызывать функцию дважды */
  7442. const newQuests = call.result.newQuests;
  7443. if (newQuests) {
  7444. for (let quest of newQuests) {
  7445. if (quest.id < 1e6 && quest.state == 2) {
  7446. reSend = true;
  7447. }
  7448. }
  7449. }
  7450. }
  7451. setProgress(I18N('COLLECT_REWARDS_AND_MAIL', { countQuests, countMail }), true);
  7452. if (reSend) {
  7453. rewardsAndMailFarm()
  7454. }
  7455. resolve();
  7456. });
  7457. });
  7458. })
  7459. }
  7460.  
  7461. class epicBrawl {
  7462. timeout = null;
  7463. time = null;
  7464.  
  7465. constructor() {
  7466. if (epicBrawl.inst) {
  7467. return epicBrawl.inst;
  7468. }
  7469. epicBrawl.inst = this;
  7470. return this;
  7471. }
  7472.  
  7473. check() {
  7474. console.log(new Date(this.time))
  7475. if (Date.now() > this.time) {
  7476. this.timeout = null;
  7477. this.start()
  7478. return;
  7479. }
  7480. this.timeout = setTimeout(this.check, 6e4);
  7481. }
  7482.  
  7483. async start() {
  7484. if (this.timeout) {
  7485. console.log(new Date(this.time))
  7486. setProgress(I18N('TIMER_ALREADY'), 3000);
  7487. return;
  7488. }
  7489. setProgress(I18N('EPIC_BRAWL'), true);
  7490. 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));
  7491. const refill = teamInfo[2].refillable.find(n => n.id == 52)
  7492. this.time = (refill.lastRefill + 3600) * 1000
  7493. const attempts = refill.amount;
  7494. if (!attempts) {
  7495. console.log(new Date(this.time));
  7496. this.check();
  7497. setProgress(I18N('NO_ATTEMPTS_TIMER_START'), 3000);
  7498. return;
  7499. }
  7500.  
  7501. const args = {
  7502. heroes: teamInfo[0].epic_brawl.filter(e => e < 1000),
  7503. pet: teamInfo[0].epic_brawl.filter(e => e > 6000).pop(),
  7504. favor: teamInfo[1].epic_brawl,
  7505. }
  7506.  
  7507. let wins = 0;
  7508. let coins = 0;
  7509. let streak = { progress: 0, nextStage: 0 };
  7510. for (let i = attempts; i > 0; i--) {
  7511. const info = await Send(JSON.stringify({
  7512. calls: [
  7513. { name: "epicBrawl_getEnemy", args: {}, ident: "epicBrawl_getEnemy" }, { name: "epicBrawl_startBattle", args, ident: "epicBrawl_startBattle" }
  7514. ]
  7515. })).then(e => e.results.map(n => n.result.response));
  7516.  
  7517. const { progress, result } = await Calc(info[1].battle);
  7518. 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));
  7519.  
  7520. const resultInfo = endResult[0].result;
  7521. streak = endResult[1];
  7522.  
  7523. wins += resultInfo.win;
  7524. coins += resultInfo.reward ? resultInfo.reward.coin[39] : 0;
  7525.  
  7526. console.log(endResult[0].result)
  7527. if (endResult[1].progress == endResult[1].nextStage) {
  7528. const farm = await Send('{"calls":[{"name":"epicBrawl_farmWinStreak","args":{},"ident":"body"}]}').then(e => e.results[0].result.response);
  7529. coins += farm.coin[39];
  7530. }
  7531.  
  7532. setProgress(I18N('EPIC_BRAWL_RESULT', {
  7533. i, wins, attempts, coins,
  7534. progress: streak.progress,
  7535. nextStage: streak.nextStage,
  7536. end: '',
  7537. }), false, hideProgress);
  7538. }
  7539.  
  7540. console.log(new Date(this.time));
  7541. this.check();
  7542. setProgress(I18N('EPIC_BRAWL_RESULT', {
  7543. wins, attempts, coins,
  7544. i: '',
  7545. progress: streak.progress,
  7546. nextStage: streak.nextStage,
  7547. end: I18N('ATTEMPT_ENDED'),
  7548. }), false, hideProgress);
  7549. }
  7550. }
  7551. /* тест остановка подземки*/
  7552. function stopDungeon(e) {
  7553. stopDung = true;
  7554. }
  7555. function Sleep(ms) {
  7556. return new Promise(resolve => setTimeout(resolve, ms));
  7557. }
  7558. function countdownTimer(seconds, message) {
  7559. message = message || I18N('TIMER');
  7560. const stopTimer = Date.now() + seconds * 1e3
  7561. return new Promise(resolve => {
  7562. const interval = setInterval(async () => {
  7563. const now = Date.now();
  7564. setProgress(`${message} ${((stopTimer - now) / 1000).toFixed(2)}`, false);
  7565. if (now > stopTimer) {
  7566. clearInterval(interval);
  7567. setProgress('', 1);
  7568. resolve();
  7569. }
  7570. }, 100);
  7571. });
  7572. }
  7573.  
  7574. /**
  7575. * Attack of the minions of Asgard
  7576. *
  7577. * Атака прислужников Асгарда
  7578. */
  7579. function testRaidNodes() {
  7580. return new Promise((resolve, reject) => {
  7581. const tower = new executeRaidNodes(resolve, reject);
  7582. tower.start();
  7583. });
  7584. }
  7585.  
  7586. /**
  7587. * Attack of the minions of Asgard
  7588. *
  7589. * Атака прислужников Асгарда
  7590. */
  7591. function executeRaidNodes(resolve, reject) {
  7592. let raidData = {
  7593. teams: [],
  7594. favor: {},
  7595. nodes: [],
  7596. attempts: 0,
  7597. countExecuteBattles: 0,
  7598. cancelBattle: 0,
  7599. }
  7600.  
  7601. callsExecuteRaidNodes = {
  7602. calls: [{
  7603. name: "clanRaid_getInfo",
  7604. args: {},
  7605. ident: "clanRaid_getInfo"
  7606. }, {
  7607. name: "teamGetAll",
  7608. args: {},
  7609. ident: "teamGetAll"
  7610. }, {
  7611. name: "teamGetFavor",
  7612. args: {},
  7613. ident: "teamGetFavor"
  7614. }]
  7615. }
  7616.  
  7617. this.start = function () {
  7618. send(JSON.stringify(callsExecuteRaidNodes), startRaidNodes);
  7619. }
  7620.  
  7621. function startRaidNodes(data) {
  7622. res = data.results;
  7623. clanRaidInfo = res[0].result.response;
  7624. teamGetAll = res[1].result.response;
  7625. teamGetFavor = res[2].result.response;
  7626.  
  7627. let index = 0;
  7628. for (let team of teamGetAll.clanRaid_nodes) {
  7629. raidData.teams.push({
  7630. data: {},
  7631. heroes: team.filter(id => id < 6000),
  7632. pet: team.filter(id => id >= 6000).pop(),
  7633. battleIndex: index++
  7634. });
  7635. }
  7636. raidData.favor = teamGetFavor.clanRaid_nodes;
  7637.  
  7638. raidData.nodes = clanRaidInfo.nodes;
  7639. raidData.attempts = clanRaidInfo.attempts;
  7640. isCancalBattle = false;
  7641.  
  7642. checkNodes();
  7643. }
  7644.  
  7645. function getAttackNode() {
  7646. for (let nodeId in raidData.nodes) {
  7647. let node = raidData.nodes[nodeId];
  7648. let points = 0
  7649. for (team of node.teams) {
  7650. points += team.points;
  7651. }
  7652. let now = Date.now() / 1000;
  7653. if (!points && now > node.timestamps.start && now < node.timestamps.end) {
  7654. let countTeam = node.teams.length;
  7655. delete raidData.nodes[nodeId];
  7656. return {
  7657. nodeId,
  7658. countTeam
  7659. };
  7660. }
  7661. }
  7662. return null;
  7663. }
  7664.  
  7665. function checkNodes() {
  7666. setProgress(`${I18N('REMAINING_ATTEMPTS')}: ${raidData.attempts}`);
  7667. let nodeInfo = getAttackNode();
  7668. if (nodeInfo && raidData.attempts) {
  7669. startNodeBattles(nodeInfo);
  7670. return;
  7671. }
  7672.  
  7673. endRaidNodes('EndRaidNodes');
  7674. }
  7675.  
  7676. function startNodeBattles(nodeInfo) {
  7677. let {nodeId, countTeam} = nodeInfo;
  7678. let teams = raidData.teams.slice(0, countTeam);
  7679. let heroes = raidData.teams.map(e => e.heroes).flat();
  7680. let favor = {...raidData.favor};
  7681. for (let heroId in favor) {
  7682. if (!heroes.includes(+heroId)) {
  7683. delete favor[heroId];
  7684. }
  7685. }
  7686.  
  7687. let calls = [{
  7688. name: "clanRaid_startNodeBattles",
  7689. args: {
  7690. nodeId,
  7691. teams,
  7692. favor
  7693. },
  7694. ident: "body"
  7695. }];
  7696.  
  7697. send(JSON.stringify({calls}), resultNodeBattles);
  7698. }
  7699.  
  7700. function resultNodeBattles(e) {
  7701. if (e['error']) {
  7702. endRaidNodes('nodeBattlesError', e['error']);
  7703. return;
  7704. }
  7705.  
  7706. console.log(e);
  7707. let battles = e.results[0].result.response.battles;
  7708. let promises = [];
  7709. let battleIndex = 0;
  7710. for (let battle of battles) {
  7711. battle.battleIndex = battleIndex++;
  7712. promises.push(calcBattleResult(battle));
  7713. }
  7714.  
  7715. Promise.all(promises)
  7716. .then(results => {
  7717. const endResults = {};
  7718. let isAllWin = true;
  7719. for (let r of results) {
  7720. isAllWin &&= r.result.win;
  7721. }
  7722. if (!isAllWin) {
  7723. cancelEndNodeBattle(results[0]);
  7724. return;
  7725. }
  7726. raidData.countExecuteBattles = results.length;
  7727. let timeout = 500;
  7728. for (let r of results) {
  7729. setTimeout(endNodeBattle, timeout, r);
  7730. timeout += 500;
  7731. }
  7732. });
  7733. }
  7734. /**
  7735. * Returns the battle calculation promise
  7736. *
  7737. * Возвращает промис расчета боя
  7738. */
  7739. function calcBattleResult(battleData) {
  7740. return new Promise(function (resolve, reject) {
  7741. BattleCalc(battleData, "get_clanPvp", resolve);
  7742. });
  7743. }
  7744. /**
  7745. * Cancels the fight
  7746. *
  7747. * Отменяет бой
  7748. */
  7749. function cancelEndNodeBattle(r) {
  7750. const fixBattle = function (heroes) {
  7751. for (const ids in heroes) {
  7752. hero = heroes[ids];
  7753. hero.energy = random(1, 999);
  7754. if (hero.hp > 0) {
  7755. hero.hp = random(1, hero.hp);
  7756. }
  7757. }
  7758. }
  7759. fixBattle(r.progress[0].attackers.heroes);
  7760. fixBattle(r.progress[0].defenders.heroes);
  7761. endNodeBattle(r);
  7762. }
  7763. /**
  7764. * Ends the fight
  7765. *
  7766. * Завершает бой
  7767. */
  7768. function endNodeBattle(r) {
  7769. let nodeId = r.battleData.result.nodeId;
  7770. let battleIndex = r.battleData.battleIndex;
  7771. let calls = [{
  7772. name: "clanRaid_endNodeBattle",
  7773. args: {
  7774. nodeId,
  7775. battleIndex,
  7776. result: r.result,
  7777. progress: r.progress
  7778. },
  7779. ident: "body"
  7780. }]
  7781.  
  7782. SendRequest(JSON.stringify({calls}), battleResult);
  7783. }
  7784. /**
  7785. * Processing the results of the battle
  7786. *
  7787. * Обработка результатов боя
  7788. */
  7789. function battleResult(e) {
  7790. if (e['error']) {
  7791. endRaidNodes('missionEndError', e['error']);
  7792. return;
  7793. }
  7794. r = e.results[0].result.response;
  7795. if (r['error']) {
  7796. if (r.reason == "invalidBattle") {
  7797. raidData.cancelBattle++;
  7798. checkNodes();
  7799. } else {
  7800. endRaidNodes('missionEndError', e['error']);
  7801. }
  7802. return;
  7803. }
  7804.  
  7805. if (!(--raidData.countExecuteBattles)) {
  7806. raidData.attempts--;
  7807. checkNodes();
  7808. }
  7809. }
  7810. /**
  7811. * Completing a task
  7812. *
  7813. * Завершение задачи
  7814. */
  7815. function endRaidNodes(reason, info) {
  7816. isCancalBattle = true;
  7817. let textCancel = raidData.cancelBattle ? ` ${I18N('BATTLES_CANCELED')}: ${raidData.cancelBattle}` : '';
  7818. setProgress(`${I18N('MINION_RAID')} ${I18N('COMPLETED')}! ${textCancel}`, true);
  7819. console.log(reason, info);
  7820. resolve();
  7821. }
  7822. }
  7823.  
  7824. /**
  7825. * Asgard Boss Attack Replay
  7826. *
  7827. * Повтор атаки босса Асгарда
  7828. */
  7829. function testBossBattle() {
  7830. return new Promise((resolve, reject) => {
  7831. const bossBattle = new executeBossBattle(resolve, reject);
  7832. bossBattle.start(lastBossBattle, lastBossBattleInfo);
  7833. });
  7834. }
  7835.  
  7836. /**
  7837. * Asgard Boss Attack Replay
  7838. *
  7839. * Повтор атаки босса Асгарда
  7840. */
  7841. function executeBossBattle(resolve, reject) {
  7842. let lastBossBattleArgs = {};
  7843. let reachDamage = 0;
  7844. let countBattle = 0;
  7845. let countMaxBattle = 10;
  7846. let lastDamage = 0;
  7847.  
  7848. this.start = function (battleArg, battleInfo) {
  7849. lastBossBattleArgs = battleArg;
  7850. preCalcBattle(battleInfo);
  7851. }
  7852.  
  7853. function getBattleInfo(battle) {
  7854. return new Promise(function (resolve) {
  7855. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  7856. BattleCalc(battle, getBattleType(battle.type), e => {
  7857. let extra = e.progress[0].defenders.heroes[1].extra;
  7858. resolve(extra.damageTaken + extra.damageTakenNextLevel);
  7859. });
  7860. });
  7861. }
  7862.  
  7863. function preCalcBattle(battle) {
  7864. let actions = [];
  7865. const countTestBattle = getInput('countTestBattle');
  7866. for (let i = 0; i < countTestBattle; i++) {
  7867. actions.push(getBattleInfo(battle, true));
  7868. }
  7869. Promise.all(actions)
  7870. .then(resultPreCalcBattle);
  7871. }
  7872.  
  7873. function fixDamage(damage) {
  7874. for (let i = 1e6; i > 1; i /= 10) {
  7875. if (damage > i) {
  7876. let n = i / 10;
  7877. damage = Math.ceil(damage / n) * n;
  7878. break;
  7879. }
  7880. }
  7881. return damage;
  7882. }
  7883.  
  7884. async function resultPreCalcBattle(damages) {
  7885. let maxDamage = 0;
  7886. let minDamage = 1e10;
  7887. let avgDamage = 0;
  7888. for (let damage of damages) {
  7889. avgDamage += damage
  7890. if (damage > maxDamage) {
  7891. maxDamage = damage;
  7892. }
  7893. if (damage < minDamage) {
  7894. minDamage = damage;
  7895. }
  7896. }
  7897. avgDamage /= damages.length;
  7898. console.log(damages.map(e => e.toLocaleString()).join('\n'), avgDamage, maxDamage);
  7899.  
  7900. reachDamage = fixDamage(avgDamage);
  7901. const result = await popup.confirm(
  7902. `${I18N('ROUND_STAT')} ${damages.length} ${I18N('BATTLE')}:` +
  7903. `<br>${I18N('MINIMUM')}: ` + minDamage.toLocaleString() +
  7904. `<br>${I18N('MAXIMUM')}: ` + maxDamage.toLocaleString() +
  7905. `<br>${I18N('AVERAGE')}: ` + avgDamage.toLocaleString()
  7906. /*+ '<br>Поиск урона больше чем ' + reachDamage.toLocaleString()*/
  7907. , [
  7908. { msg: I18N('BTN_OK'), result: 0},
  7909. /* {msg: 'Погнали', isInput: true, default: reachDamage}, */
  7910. ])
  7911. if (result) {
  7912. reachDamage = result;
  7913. isCancalBossBattle = false;
  7914. startBossBattle();
  7915. return;
  7916. }
  7917. endBossBattle(I18N('BTN_CANCEL'));
  7918. }
  7919.  
  7920. function startBossBattle() {
  7921. countBattle++;
  7922. countMaxBattle = getInput('countAutoBattle');
  7923. if (countBattle > countMaxBattle) {
  7924. setProgress('Превышен лимит попыток: ' + countMaxBattle, true);
  7925. endBossBattle('Превышен лимит попыток: ' + countMaxBattle);
  7926. return;
  7927. }
  7928. let calls = [{
  7929. name: "clanRaid_startBossBattle",
  7930. args: lastBossBattleArgs,
  7931. ident: "body"
  7932. }];
  7933. send(JSON.stringify({calls}), calcResultBattle);
  7934. }
  7935.  
  7936. function calcResultBattle(e) {
  7937. BattleCalc(e.results[0].result.response.battle, "get_clanPvp", resultBattle);
  7938. }
  7939.  
  7940. async function resultBattle(e) {
  7941. let extra = e.progress[0].defenders.heroes[1].extra
  7942. resultDamage = extra.damageTaken + extra.damageTakenNextLevel
  7943. console.log(resultDamage);
  7944. scriptMenu.setStatus(countBattle + ') ' + resultDamage.toLocaleString());
  7945. lastDamage = resultDamage;
  7946. if (resultDamage > reachDamage && await popup.confirm(countBattle + ') Урон ' + resultDamage.toLocaleString(), [
  7947. {msg: 'Ок', result: true},
  7948. {msg: 'Не пойдет', result: false},
  7949. ])) {
  7950. endBattle(e, false);
  7951. return;
  7952. }
  7953. cancelEndBattle(e);
  7954. }
  7955.  
  7956. function cancelEndBattle (r) {
  7957. const fixBattle = function (heroes) {
  7958. for (const ids in heroes) {
  7959. hero = heroes[ids];
  7960. hero.energy = random(1, 999);
  7961. if (hero.hp > 0) {
  7962. hero.hp = random(1, hero.hp);
  7963. }
  7964. }
  7965. }
  7966. fixBattle(r.progress[0].attackers.heroes);
  7967. fixBattle(r.progress[0].defenders.heroes);
  7968. endBattle(r, true);
  7969. }
  7970.  
  7971. function endBattle(battleResult, isCancal) {
  7972. let calls = [{
  7973. name: "clanRaid_endBossBattle",
  7974. args: {
  7975. result: battleResult.result,
  7976. progress: battleResult.progress
  7977. },
  7978. ident: "body"
  7979. }];
  7980.  
  7981. send(JSON.stringify({calls}), e => {
  7982. console.log(e);
  7983. if (isCancal) {
  7984. startBossBattle();
  7985. return;
  7986. }
  7987. scriptMenu.setStatus('Босс пробит нанесен урон: ' + lastDamage);
  7988. setTimeout(() => {
  7989. scriptMenu.setStatus('');
  7990. }, 5000);
  7991. endBossBattle('Узпех!');
  7992. });
  7993. }
  7994.  
  7995. /**
  7996. * Completing a task
  7997. *
  7998. * Завершение задачи
  7999. */
  8000. function endBossBattle(reason, info) {
  8001. isCancalBossBattle = true;
  8002. console.log(reason, info);
  8003. resolve();
  8004. }
  8005. }
  8006.  
  8007. /**
  8008. * Auto-repeat attack
  8009. *
  8010. * Автоповтор атаки
  8011. */
  8012. function testAutoBattle() {
  8013. return new Promise((resolve, reject) => {
  8014. const bossBattle = new executeAutoBattle(resolve, reject);
  8015. bossBattle.start(lastBattleArg, lastBattleInfo);
  8016. });
  8017. }
  8018.  
  8019. /**
  8020. * Auto-repeat attack
  8021. *
  8022. * Автоповтор атаки
  8023. */
  8024. function executeAutoBattle(resolve, reject) {
  8025. let battleArg = {};
  8026. let countBattle = 0;
  8027. let countMaxBattle = 10; //гудвин тест
  8028. let findCoeff = 0;
  8029.  
  8030. this.start = function (battleArgs, battleInfo) {
  8031. battleArg = battleArgs;
  8032. preCalcBattle(battleInfo);
  8033. }
  8034. /**
  8035. * Returns a promise for combat recalculation
  8036. *
  8037. * Возвращает промис для прерасчета боя
  8038. */
  8039. function getBattleInfo(battle) {
  8040. return new Promise(function (resolve) {
  8041. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  8042. Calc(battle).then(e => {
  8043. e.coeff = calcCoeff(e, 'defenders');
  8044. resolve(e);
  8045. });
  8046. });
  8047. }
  8048. /**
  8049. * Battle recalculation
  8050. *
  8051. * Прерасчет боя
  8052. */
  8053. function preCalcBattle(battle) {
  8054. let actions = [];
  8055. const countTestBattle = getInput('countTestBattle');
  8056. for (let i = 0; i < countTestBattle; i++) {
  8057. actions.push(getBattleInfo(battle));
  8058. }
  8059. Promise.all(actions)
  8060. .then(resultPreCalcBattle);
  8061. }
  8062. /**
  8063. * Processing the results of the battle recalculation
  8064. *
  8065. * Обработка результатов прерасчета боя
  8066. */
  8067. async function resultPreCalcBattle(results) {
  8068. let countWin = results.reduce((s, w) => w.result.win + s, 0);
  8069. setProgress(`${I18N('CHANCE_TO_WIN')} ${Math.floor(countWin / results.length * 100)}% (${results.length})`, true);
  8070. if (countWin > 0) {
  8071. isCancalBattle = false;
  8072. startBattle();
  8073. return;
  8074. }
  8075. let minCoeff = 100;
  8076. let maxCoeff = -100;
  8077. let avgCoeff = 0;
  8078. results.forEach(e => {
  8079. if (e.coeff < minCoeff) minCoeff = e.coeff;
  8080. if (e.coeff > maxCoeff) maxCoeff = e.coeff;
  8081. avgCoeff += e.coeff;
  8082. });
  8083. avgCoeff /= results.length;
  8084.  
  8085. const result = await popup.confirm(
  8086. I18N('VICTORY_IMPOSSIBLE') +
  8087. `<br>${I18N('ROUND_STAT')} ${results.length} ${I18N('BATTLE')}:` +
  8088. `<br>${I18N('MINIMUM')}: ` + minCoeff.toLocaleString() +
  8089. `<br>${I18N('MAXIMUM')}: ` + maxCoeff.toLocaleString() +
  8090. `<br>${I18N('AVERAGE')}: ` + avgCoeff.toLocaleString() +
  8091. `<br>${I18N('FIND_COEFF')} ` + avgCoeff.toLocaleString(), [
  8092. { msg: I18N('BTN_CANCEL'), result: 0 },
  8093. { msg: I18N('BTN_GO'), isInput: true, default: Math.round(avgCoeff * 1000) / 1000 },
  8094. ])
  8095. if (result) {
  8096. findCoeff = result;
  8097. isCancalBattle = false;
  8098. startBattle();
  8099. return;
  8100. }
  8101. setProgress(I18N('NOT_THIS_TIME'), true);
  8102. endAutoBattle(I18N('NOT_THIS_TIME'));
  8103. }
  8104.  
  8105. /**
  8106. * Calculation of the combat result coefficient
  8107. *
  8108. * Расчет коэфициента результата боя
  8109. */
  8110. function calcCoeff(result, packType) {
  8111. let beforeSumFactor = 0;
  8112. const beforePack = result.battleData[packType][0];
  8113. for (let heroId in beforePack) {
  8114. const hero = beforePack[heroId];
  8115. const state = hero.state;
  8116. let factor = 1;
  8117. if (state) {
  8118. const hp = state.hp / state.maxHp;
  8119. const energy = state.energy / 1e3;
  8120. factor = hp + energy / 20;
  8121. }
  8122. beforeSumFactor += factor;
  8123. }
  8124.  
  8125. let afterSumFactor = 0;
  8126. const afterPack = result.progress[0][packType].heroes;
  8127. for (let heroId in afterPack) {
  8128. const hero = afterPack[heroId];
  8129. const hp = hero.hp / beforePack[heroId].state.hp;
  8130. const energy = hero.energy / 1e3;
  8131. const factor = hp + energy / 20;
  8132. afterSumFactor += factor;
  8133. }
  8134. const resultCoeff = -(afterSumFactor - beforeSumFactor);
  8135. return Math.round(resultCoeff * 1000) / 1000;
  8136. }
  8137. /**
  8138. * Start battle
  8139. *
  8140. * Начало боя
  8141. */
  8142. function startBattle() {
  8143. countBattle++;
  8144. const countMaxBattle = getInput('countAutoBattle');
  8145. setProgress(countBattle + '/' + countMaxBattle);
  8146. if (countBattle > countMaxBattle) {
  8147. setProgress(`${I18N('RETRY_LIMIT_EXCEEDED')}: ${countMaxBattle}`, true);
  8148. endAutoBattle(`${I18N('RETRY_LIMIT_EXCEEDED')}: ${countMaxBattle}`)
  8149. return;
  8150. }
  8151. let calls = [{
  8152. name: nameFuncStartBattle,
  8153. args: battleArg,
  8154. ident: "body"
  8155. }];
  8156. send(JSON.stringify({
  8157. calls
  8158. }), calcResultBattle);
  8159. }
  8160. /**
  8161. * Battle calculation
  8162. *
  8163. * Расчет боя
  8164. */
  8165. function calcResultBattle(e) {
  8166. let battle = e.results[0].result.response.battle
  8167. BattleCalc(battle, getBattleType(battle.type), resultBattle);
  8168. }
  8169. /**
  8170. * Processing the results of the battle
  8171. *
  8172. * Обработка результатов боя
  8173. */
  8174. function resultBattle(e) {
  8175. const isWin = e.result.win;
  8176. console.log(isWin);
  8177. if (isWin) {
  8178. endBattle(e, false);
  8179. return;
  8180. }
  8181. if (findCoeff) {
  8182. const coeff = calcCoeff(e, 'defenders');
  8183. console.log(coeff);
  8184. setProgress(coeff, true);
  8185. if (coeff > findCoeff) {
  8186. endBattle(e, false);
  8187. return;
  8188. }
  8189. }
  8190. cancelEndBattle(e);
  8191. }
  8192. /**
  8193. * Cancel fight
  8194. *
  8195. * Отмена боя
  8196. */
  8197. function cancelEndBattle(r) {
  8198. const fixBattle = function (heroes) {
  8199. for (const ids in heroes) {
  8200. hero = heroes[ids];
  8201. hero.energy = random(1, 999);
  8202. if (hero.hp > 0) {
  8203. hero.hp = random(1, hero.hp);
  8204. }
  8205. }
  8206. }
  8207. fixBattle(r.progress[0].attackers.heroes);
  8208. fixBattle(r.progress[0].defenders.heroes);
  8209. endBattle(r, true);
  8210. }
  8211. /**
  8212. * End of the fight
  8213. *
  8214. * Завершение боя */
  8215. function endBattle(battleResult, isCancal) {
  8216. let calls = [{
  8217. name: nameFuncEndBattle,
  8218. args: {
  8219. result: battleResult.result,
  8220. progress: battleResult.progress
  8221. },
  8222. ident: "body"
  8223. }];
  8224.  
  8225. send(JSON.stringify({
  8226. calls
  8227. }), e => {
  8228. console.log(e);
  8229. if (isCancal) {
  8230. startBattle();
  8231. return;
  8232. }
  8233. scriptMenu.setStatus(`${I18N('SUCCESS')}!`);
  8234. setTimeout(() => {
  8235. scriptMenu.setStatus('');
  8236. }, 5000)
  8237. endAutoBattle(`${I18N('SUCCESS')}!`)
  8238. });
  8239. }
  8240. /**
  8241. * Completing a task
  8242. *
  8243. * Завершение задачи
  8244. */
  8245. function endAutoBattle(reason, info) {
  8246. isCancalBattle = true;
  8247. console.log(reason, info);
  8248. resolve();
  8249. }
  8250. }
  8251.  
  8252. function testDailyQuests() {
  8253. return new Promise((resolve, reject) => {
  8254. const quests = new dailyQuests(resolve, reject);
  8255. quests.init(questsInfo);
  8256. quests.start();
  8257. });
  8258. }
  8259.  
  8260. /**
  8261. * Automatic completion of daily quests
  8262. *
  8263. * Автоматическое выполнение ежедневных квестов
  8264. */
  8265. class dailyQuests {
  8266. /**
  8267. * Send(' {"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}').then(e => console.log(e))
  8268. * Send(' {"calls":[{"name":"heroGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  8269. * Send(' {"calls":[{"name":"titanGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  8270. * Send(' {"calls":[{"name":"inventoryGet","args":{},"ident":"body"}]}').then(e => console.log(e))
  8271. * Send(' {"calls":[{"name":"questGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  8272. * Send(' {"calls":[{"name":"bossGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  8273. */
  8274. callsList = [
  8275. "userGetInfo",
  8276. "heroGetAll",
  8277. "titanGetAll",
  8278. "inventoryGet",
  8279. "questGetAll",
  8280. "bossGetAll",
  8281. ]
  8282.  
  8283. dataQuests = {
  8284. 10001: {
  8285. description: 'Улучши умения героев 3 раза', // ++++++++++++++++
  8286. doItCall: () => {
  8287. const upgradeSkills = this.getUpgradeSkills();
  8288. return upgradeSkills.map(({ heroId, skill }, index) => ({ name: "heroUpgradeSkill", args: { heroId, skill }, "ident": `heroUpgradeSkill_${index}` }));
  8289. },
  8290. isWeCanDo: () => {
  8291. const upgradeSkills = this.getUpgradeSkills();
  8292. let sumGold = 0;
  8293. for (const skill of upgradeSkills) {
  8294. sumGold += this.skillCost(skill.value);
  8295. if (!skill.heroId) {
  8296. return false;
  8297. }
  8298. }
  8299. return this.questInfo['userGetInfo'].gold > sumGold;
  8300. },
  8301. },
  8302. 10002: {
  8303. description: 'Пройди 10 миссий', // --------------
  8304. isWeCanDo: () => false,
  8305. },
  8306. 10003: {
  8307. description: 'Пройди 3 героические миссии', // --------------
  8308. isWeCanDo: () => false,
  8309. },
  8310. 10004: {
  8311. description: 'Сразись 3 раза на Арене или Гранд Арене', // --------------
  8312. isWeCanDo: () => false,
  8313. },
  8314. 10006: {
  8315. description: 'Используй обмен изумрудов 1 раз', // ++++++++++++++++
  8316. doItCall: () => [{
  8317. name: "refillableAlchemyUse",
  8318. args: { multi: false },
  8319. ident: "refillableAlchemyUse"
  8320. }],
  8321. isWeCanDo: () => {
  8322. const starMoney = this.questInfo['userGetInfo'].starMoney;
  8323. return starMoney >= 20;
  8324. },
  8325. },
  8326. 10007: {
  8327. description: 'Соверши 1 призыв в Атриуме Душ', // ++++++++++++++++
  8328. doItCall: () => [{ name: "gacha_open", args: { ident: "heroGacha", free: true, pack: false }, ident: "gacha_open" }],
  8329. isWeCanDo: () => {
  8330. const soulCrystal = this.questInfo['inventoryGet'].coin[38];
  8331. return soulCrystal > 0;
  8332. },
  8333. },
  8334. 10016: {
  8335. description: 'Отправь подарки согильдийцам', // ++++++++++++++++
  8336. doItCall: () => [{ name: "clanSendDailyGifts", args: {}, ident: "clanSendDailyGifts" }],
  8337. isWeCanDo: () => true,
  8338. },
  8339. 10018: {
  8340. description: 'Используй зелье опыта', // ++++++++++++++++
  8341. doItCall: () => {
  8342. const expHero = this.getExpHero();
  8343. return [{
  8344. name: "consumableUseHeroXp",
  8345. args: {
  8346. heroId: expHero.heroId,
  8347. libId: expHero.libId,
  8348. amount: 1
  8349. },
  8350. ident: "consumableUseHeroXp"
  8351. }];
  8352. },
  8353. isWeCanDo: () => {
  8354. const expHero = this.getExpHero();
  8355. return expHero.heroId && expHero.libId;
  8356. },
  8357. },
  8358. 10019: {
  8359. description: 'Открой 1 сундук в Башне',
  8360. doItFunc: testTower,
  8361. isWeCanDo: () => false,
  8362. },
  8363. 10020: {
  8364. description: 'Открой 3 сундука в Запределье', // Готово
  8365. doItCall: () => {
  8366. return this.getOutlandChest();
  8367. },
  8368. isWeCanDo: () => {
  8369. const outlandChest = this.getOutlandChest();
  8370. return outlandChest.length > 0;
  8371. },
  8372. },
  8373. 10021: {
  8374. description: 'Собери 75 Титанита в Подземелье Гильдии',
  8375. isWeCanDo: () => false,
  8376. },
  8377. 10022: {
  8378. description: 'Собери 150 Титанита в Подземелье Гильдии',
  8379. doItFunc: testDungeon,
  8380. isWeCanDo: () => false,
  8381. },
  8382. 10023: {
  8383. description: 'Прокачай Дар Стихий на 1 уровень', // Готово
  8384. doItCall: () => {
  8385. const heroId = this.getHeroIdTitanGift();
  8386. return [
  8387. { name: "heroTitanGiftLevelUp", args: { heroId }, ident: "heroTitanGiftLevelUp" },
  8388. { name: "heroTitanGiftDrop", args: { heroId }, ident: "heroTitanGiftDrop" }
  8389. ]
  8390. },
  8391. isWeCanDo: () => {
  8392. const heroId = this.getHeroIdTitanGift();
  8393. return heroId;
  8394. },
  8395. },
  8396. 10024: {
  8397. description: 'Повысь уровень любого артефакта один раз', // Готово
  8398. doItCall: () => {
  8399. const upArtifact = this.getUpgradeArtifact();
  8400. return [
  8401. {
  8402. name: "heroArtifactLevelUp",
  8403. args: {
  8404. heroId: upArtifact.heroId,
  8405. slotId: upArtifact.slotId
  8406. },
  8407. ident: `heroArtifactLevelUp`
  8408. }
  8409. ];
  8410. },
  8411. isWeCanDo: () => {
  8412. const upgradeArtifact = this.getUpgradeArtifact();
  8413. return upgradeArtifact.heroId;
  8414. },
  8415. },
  8416. 10025: {
  8417. description: 'Начни 1 Экспедицию',
  8418. doItFunc: checkExpedition,
  8419. isWeCanDo: () => false,
  8420. },
  8421. 10026: {
  8422. description: 'Начни 4 Экспедиции', // --------------
  8423. doItFunc: checkExpedition,
  8424. isWeCanDo: () => false,
  8425. },
  8426. 10027: {
  8427. description: 'Победи в 1 бою Турнира Стихий',
  8428. doItFunc: testTitanArena,
  8429. isWeCanDo: () => false,
  8430. },
  8431. 10028: {
  8432. description: 'Повысь уровень любого артефакта титанов', // Готово
  8433. doItCall: () => {
  8434. const upTitanArtifact = this.getUpgradeTitanArtifact();
  8435. return [
  8436. {
  8437. name: "titanArtifactLevelUp",
  8438. args: {
  8439. titanId: upTitanArtifact.titanId,
  8440. slotId: upTitanArtifact.slotId
  8441. },
  8442. ident: `titanArtifactLevelUp`
  8443. }
  8444. ];
  8445. },
  8446. isWeCanDo: () => {
  8447. const upgradeTitanArtifact = this.getUpgradeTitanArtifact();
  8448. return upgradeTitanArtifact.titanId;
  8449. },
  8450. },
  8451. 10029: {
  8452. description: 'Открой сферу артефактов титанов', // ++++++++++++++++
  8453. doItCall: () => [{ name: "titanArtifactChestOpen", args: { amount: 1, free: true }, ident: "titanArtifactChestOpen" }],
  8454. isWeCanDo: () => {
  8455. return this.questInfo['inventoryGet']?.consumable[55] > 0
  8456. },
  8457. },
  8458. 10030: {
  8459. description: 'Улучши облик любого героя 1 раз', // Готово
  8460. doItCall: () => {
  8461. const upSkin = this.getUpgradeSkin();
  8462. return [
  8463. {
  8464. name: "heroSkinUpgrade",
  8465. args: {
  8466. heroId: upSkin.heroId,
  8467. skinId: upSkin.skinId
  8468. },
  8469. ident: `heroSkinUpgrade`
  8470. }
  8471. ];
  8472. },
  8473. isWeCanDo: () => {
  8474. const upgradeSkin = this.getUpgradeSkin();
  8475. return upgradeSkin.heroId;
  8476. },
  8477. },
  8478. 10031: {
  8479. description: 'Победи в 6 боях Турнира Стихий', // --------------
  8480. doItFunc: testTitanArena,
  8481. isWeCanDo: () => false,
  8482. },
  8483. 10043: {
  8484. description: 'Начни или присоеденись к Приключению', // --------------
  8485. isWeCanDo: () => false,
  8486. },
  8487. 10044: {
  8488. description: 'Воспользуйся призывом питомцев 1 раз', // ++++++++++++++++
  8489. doItCall: () => [{ name: "pet_chestOpen", args: { amount: 1, paid: false }, ident: "pet_chestOpen" }],
  8490. isWeCanDo: () => {
  8491. return this.questInfo['inventoryGet']?.consumable[90] > 0
  8492. },
  8493. },
  8494. 10046: {
  8495. /**
  8496. * TODO: Watch Adventure
  8497. * TODO: Смотреть приключение
  8498. */
  8499. description: 'Открой 3 сундука в Приключениях',
  8500. isWeCanDo: () => false,
  8501. },
  8502. 10047: {
  8503. description: 'Набери 150 очков активности в Гильдии', // Готово
  8504. doItCall: () => {
  8505. const enchantRune = this.getEnchantRune();
  8506. return [
  8507. {
  8508. name: "heroEnchantRune",
  8509. args: {
  8510. heroId: enchantRune.heroId,
  8511. tier: enchantRune.tier,
  8512. items: {
  8513. consumable: { [enchantRune.itemId]: 1 }
  8514. }
  8515. },
  8516. ident: `heroEnchantRune`
  8517. }
  8518. ];
  8519. },
  8520. isWeCanDo: () => {
  8521. const userInfo = this.questInfo['userGetInfo'];
  8522. const enchantRune = this.getEnchantRune();
  8523. return enchantRune.heroId && userInfo.gold > 1e3;
  8524. },
  8525. },
  8526. };
  8527.  
  8528. constructor(resolve, reject, questInfo) {
  8529. this.resolve = resolve;
  8530. this.reject = reject;
  8531. }
  8532.  
  8533. init(questInfo) {
  8534. this.questInfo = questInfo;
  8535. this.isAuto = false;
  8536. }
  8537.  
  8538. async autoInit(isAuto) {
  8539. this.isAuto = isAuto || false;
  8540. const quests = {};
  8541. const calls = this.callsList.map(name => ({
  8542. name, args: {}, ident: name
  8543. }))
  8544. const result = await Send(JSON.stringify({ calls })).then(e => e.results);
  8545. for (const call of result) {
  8546. quests[call.ident] = call.result.response;
  8547. }
  8548. this.questInfo = quests;
  8549. }
  8550.  
  8551. async start() {
  8552. /**
  8553. * TODO may not be needed
  8554. *
  8555. * TODO возожно не нужна
  8556. */
  8557. let countQuest = 0;
  8558. const weCanDo = [];
  8559. const selectedActions = getSaveVal('selectedActions', {});
  8560. for (let quest of this.questInfo['questGetAll']) {
  8561. if (quest.id in this.dataQuests && quest.state == 1) {
  8562. if (!selectedActions[quest.id]) {
  8563. selectedActions[quest.id] = {
  8564. checked: false
  8565. }
  8566. }
  8567.  
  8568. const isWeCanDo = this.dataQuests[quest.id].isWeCanDo;
  8569. if (!isWeCanDo.call(this)) {
  8570. continue;
  8571. }
  8572.  
  8573. weCanDo.push({
  8574. name: quest.id,
  8575. label: I18N(`QUEST_${quest.id}`),
  8576. checked: selectedActions[quest.id].checked
  8577. });
  8578. countQuest++;
  8579. }
  8580. }
  8581.  
  8582. if (!weCanDo.length) {
  8583. this.end(I18N('NOTHING_TO_DO'));
  8584. return;
  8585. }
  8586.  
  8587. console.log(weCanDo);
  8588. let taskList = [];
  8589. if (this.isAuto) {
  8590. taskList = weCanDo;
  8591. } else {
  8592. const answer = await popup.confirm(`${I18N('YOU_CAN_COMPLETE') }:`, [
  8593. { msg: I18N('BTN_DO_IT'), result: true },
  8594. { msg: I18N('BTN_CANCEL'), result: false },
  8595. ], weCanDo);
  8596. if (!answer) {
  8597. this.end('');
  8598. return;
  8599. }
  8600. taskList = popup.getCheckBoxes();
  8601. taskList.forEach(e => {
  8602. selectedActions[e.name].checked = e.checked;
  8603. });
  8604. setSaveVal('selectedActions', selectedActions);
  8605. }
  8606.  
  8607. const calls = [];
  8608. let countChecked = 0;
  8609. for (const task of taskList) {
  8610. if (task.checked) {
  8611. countChecked++;
  8612. const quest = this.dataQuests[task.name]
  8613. console.log(quest.description);
  8614.  
  8615. if (quest.doItCall) {
  8616. const doItCall = quest.doItCall.call(this);
  8617. calls.push(...doItCall);
  8618. }
  8619. }
  8620. }
  8621.  
  8622. if (!countChecked) {
  8623. this.end(I18N('NOT_QUEST_COMPLETED'));
  8624. return;
  8625. }
  8626.  
  8627. const result = await Send(JSON.stringify({ calls }));
  8628. if (result.error) {
  8629. console.error(result.error, result.error.call)
  8630. }
  8631. this.end(`${I18N('COMPLETED_QUESTS')}: ${countChecked}`);
  8632. }
  8633.  
  8634. errorHandling(error) {
  8635. //console.error(error);
  8636. let errorInfo = error.toString() + '\n';
  8637. try {
  8638. const errorStack = error.stack.split('\n');
  8639. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testDoYourBest");
  8640. errorInfo += errorStack.slice(0, endStack).join('\n');
  8641. } catch (e) {
  8642. errorInfo += error.stack;
  8643. }
  8644. copyText(errorInfo);
  8645. }
  8646.  
  8647. skillCost(lvl) {
  8648. return 573 * lvl ** 0.9 + lvl ** 2.379;
  8649. }
  8650.  
  8651. getUpgradeSkills() {
  8652. const heroes = Object.values(this.questInfo['heroGetAll']);
  8653. const upgradeSkills = [
  8654. { heroId: 0, slotId: 0, value: 130 },
  8655. { heroId: 0, slotId: 0, value: 130 },
  8656. { heroId: 0, slotId: 0, value: 130 },
  8657. ];
  8658. const skillLib = lib.getData('skill');
  8659. /**
  8660. * color - 1 (белый) открывает 1 навык
  8661. * color - 2 (зеленый) открывает 2 навык
  8662. * color - 4 (синий) открывает 3 навык
  8663. * color - 7 (фиолетовый) открывает 4 навык
  8664. */
  8665. const colors = [1, 2, 4, 7];
  8666. for (const hero of heroes) {
  8667. const level = hero.level;
  8668. const color = hero.color;
  8669. for (let skillId in hero.skills) {
  8670. const tier = skillLib[skillId].tier;
  8671. const sVal = hero.skills[skillId];
  8672. if (color < colors[tier] || tier < 1 || tier > 4) {
  8673. continue;
  8674. }
  8675. for (let upSkill of upgradeSkills) {
  8676. if (sVal < upSkill.value && sVal < level) {
  8677. upSkill.value = sVal;
  8678. upSkill.heroId = hero.id;
  8679. upSkill.skill = tier;
  8680. break;
  8681. }
  8682. }
  8683. }
  8684. }
  8685. return upgradeSkills;
  8686. }
  8687.  
  8688. getUpgradeArtifact() {
  8689. const heroes = Object.values(this.questInfo['heroGetAll']);
  8690. const inventory = this.questInfo['inventoryGet'];
  8691. const upArt = { heroId: 0, slotId: 0, level: 100 };
  8692.  
  8693. const heroLib = lib.getData('hero');
  8694. const artifactLib = lib.getData('artifact');
  8695.  
  8696. for (const hero of heroes) {
  8697. const heroInfo = heroLib[hero.id];
  8698. const level = hero.level
  8699. if (level < 20) {
  8700. continue;
  8701. }
  8702.  
  8703. for (let slotId in hero.artifacts) {
  8704. const art = hero.artifacts[slotId];
  8705. /* Текущая звезданость арта */
  8706. const star = art.star;
  8707. if (!star) {
  8708. continue;
  8709. }
  8710. /* Текущий уровень арта */
  8711. const level = art.level;
  8712. if (level >= 100) {
  8713. continue;
  8714. }
  8715. /* Идентификатор арта в библиотеке */
  8716. const artifactId = heroInfo.artifacts[slotId];
  8717. const artInfo = artifactLib.id[artifactId];
  8718. const costNextLevel = artifactLib.type[artInfo.type].levels[level + 1].cost;
  8719.  
  8720. const costСurrency = Object.keys(costNextLevel).pop();
  8721. const costValues = Object.entries(costNextLevel[costСurrency]).pop();
  8722. const costId = costValues[0];
  8723. const costValue = +costValues[1];
  8724.  
  8725. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  8726. if (level < upArt.level && inventory[costСurrency][costId] >= costValue) {
  8727. upArt.level = level;
  8728. upArt.heroId = hero.id;
  8729. upArt.slotId = slotId;
  8730. }
  8731. }
  8732. }
  8733. return upArt;
  8734. }
  8735.  
  8736. getUpgradeSkin() {
  8737. const heroes = Object.values(this.questInfo['heroGetAll']);
  8738. const inventory = this.questInfo['inventoryGet'];
  8739. const upSkin = { heroId: 0, skinId: 0, level: 60, cost: 1500 };
  8740.  
  8741. const skinLib = lib.getData('skin');
  8742.  
  8743. for (const hero of heroes) {
  8744. const level = hero.level
  8745. if (level < 20) {
  8746. continue;
  8747. }
  8748.  
  8749. for (let skinId in hero.skins) {
  8750. /* Текущий уровень скина */
  8751. const level = hero.skins[skinId];
  8752. if (level >= 60) {
  8753. continue;
  8754. }
  8755. /* Идентификатор скина в библиотеке */
  8756. const skinInfo = skinLib[skinId];
  8757. const costNextLevel = skinInfo.statData.levels[level + 1].cost;
  8758.  
  8759. const costСurrency = Object.keys(costNextLevel).pop();
  8760. const costСurrencyId = Object.keys(costNextLevel[costСurrency]).pop();
  8761. const costValue = +costNextLevel[costСurrency][costСurrencyId];
  8762.  
  8763. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  8764. if (level < upSkin.level &&
  8765. costValue < upSkin.cost &&
  8766. inventory[costСurrency][costСurrencyId] >= costValue) {
  8767. upSkin.cost = costValue;
  8768. upSkin.level = level;
  8769. upSkin.heroId = hero.id;
  8770. upSkin.skinId = skinId;
  8771. }
  8772. }
  8773. }
  8774. return upSkin;
  8775. }
  8776.  
  8777. getUpgradeTitanArtifact() {
  8778. const titans = Object.values(this.questInfo['titanGetAll']);
  8779. const inventory = this.questInfo['inventoryGet'];
  8780. const userInfo = this.questInfo['userGetInfo'];
  8781. const upArt = { titanId: 0, slotId: 0, level: 120 };
  8782.  
  8783. const titanLib = lib.getData('titan');
  8784. const artTitanLib = lib.getData('titanArtifact');
  8785.  
  8786. for (const titan of titans) {
  8787. const titanInfo = titanLib[titan.id];
  8788. // const level = titan.level
  8789. // if (level < 20) {
  8790. // continue;
  8791. // }
  8792.  
  8793. for (let slotId in titan.artifacts) {
  8794. const art = titan.artifacts[slotId];
  8795. /* Текущая звезданость арта */
  8796. const star = art.star;
  8797. if (!star) {
  8798. continue;
  8799. }
  8800. /* Текущий уровень арта */
  8801. const level = art.level;
  8802. if (level >= 120) {
  8803. continue;
  8804. }
  8805. /* Идентификатор арта в библиотеке */
  8806. const artifactId = titanInfo.artifacts[slotId];
  8807. const artInfo = artTitanLib.id[artifactId];
  8808. const costNextLevel = artTitanLib.type[artInfo.type].levels[level + 1].cost;
  8809.  
  8810. const costСurrency = Object.keys(costNextLevel).pop();
  8811. let costValue = 0;
  8812. let currentValue = 0;
  8813. if (costСurrency == 'gold') {
  8814. costValue = costNextLevel[costСurrency];
  8815. currentValue = userInfo.gold;
  8816. } else {
  8817. const costValues = Object.entries(costNextLevel[costСurrency]).pop();
  8818. const costId = costValues[0];
  8819. costValue = +costValues[1];
  8820. currentValue = inventory[costСurrency][costId];
  8821. }
  8822.  
  8823. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  8824. if (level < upArt.level && currentValue >= costValue) {
  8825. upArt.level = level;
  8826. upArt.titanId = titan.id;
  8827. upArt.slotId = slotId;
  8828. break;
  8829. }
  8830. }
  8831. }
  8832. return upArt;
  8833. }
  8834.  
  8835. getEnchantRune() {
  8836. const heroes = Object.values(this.questInfo['heroGetAll']);
  8837. const inventory = this.questInfo['inventoryGet'];
  8838. const enchRune = { heroId: 0, tier: 0, exp: 43750, itemId: 0 };
  8839. for (let i = 1; i <= 4; i++) {
  8840. if (inventory.consumable[i] > 0) {
  8841. enchRune.itemId = i;
  8842. break;
  8843. }
  8844. return enchRune;
  8845. }
  8846.  
  8847. const runeLib = lib.getData('rune');
  8848. const runeLvls = Object.values(runeLib.level);
  8849. /**
  8850. * color - 4 (синий) открывает 1 и 2 символ
  8851. * color - 7 (фиолетовый) открывает 3 символ
  8852. * color - 8 (фиолетовый +1) открывает 4 символ
  8853. * color - 9 (фиолетовый +2) открывает 5 символ
  8854. */
  8855. // TODO: кажется надо учесть уровень команды
  8856. const colors = [4, 4, 7, 8, 9];
  8857. for (const hero of heroes) {
  8858. const color = hero.color;
  8859.  
  8860.  
  8861. for (let runeTier in hero.runes) {
  8862. /* Проверка на доступность руны */
  8863. if (color < colors[runeTier]) {
  8864. continue;
  8865. }
  8866. /* Текущий опыт руны */
  8867. const exp = hero.runes[runeTier];
  8868. if (exp >= 43750) {
  8869. continue;
  8870. }
  8871.  
  8872. let level = 0;
  8873. if (exp) {
  8874. for (let lvl of runeLvls) {
  8875. if (exp >= lvl.enchantValue) {
  8876. level = lvl.level;
  8877. } else {
  8878. break;
  8879. }
  8880. }
  8881. }
  8882. /** Уровень героя необходимый для уровня руны */
  8883. const heroLevel = runeLib.level[level].heroLevel;
  8884. if (hero.level < heroLevel) {
  8885. continue;
  8886. }
  8887.  
  8888. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  8889. if (exp < enchRune.exp) {
  8890. enchRune.exp = exp;
  8891. enchRune.heroId = hero.id;
  8892. enchRune.tier = runeTier;
  8893. break;
  8894. }
  8895. }
  8896. }
  8897. return enchRune;
  8898. }
  8899.  
  8900. getOutlandChest() {
  8901. const bosses = this.questInfo['bossGetAll'];
  8902.  
  8903. const calls = [];
  8904.  
  8905. for (let boss of bosses) {
  8906. if (boss.mayRaid) {
  8907. calls.push({
  8908. name: "bossRaid",
  8909. args: {
  8910. bossId: boss.id
  8911. },
  8912. ident: "bossRaid_" + boss.id
  8913. });
  8914. calls.push({
  8915. name: "bossOpenChest",
  8916. args: {
  8917. bossId: boss.id,
  8918. amount: 1,
  8919. starmoney: 0
  8920. },
  8921. ident: "bossOpenChest_" + boss.id
  8922. });
  8923. } else if (boss.chestId == 1) {
  8924. calls.push({
  8925. name: "bossOpenChest",
  8926. args: {
  8927. bossId: boss.id,
  8928. amount: 1,
  8929. starmoney: 0
  8930. },
  8931. ident: "bossOpenChest_" + boss.id
  8932. });
  8933. }
  8934. }
  8935.  
  8936. return calls;
  8937. }
  8938.  
  8939. getExpHero() {
  8940. const heroes = Object.values(this.questInfo['heroGetAll']);
  8941. const inventory = this.questInfo['inventoryGet'];
  8942. const expHero = { heroId: 0, exp: 3625195, libId: 0 };
  8943. /** зелья опыта (consumable 9, 10, 11, 12) */
  8944. for (let i = 9; i <= 12; i++) {
  8945. if (inventory.consumable[i]) {
  8946. expHero.libId = i;
  8947. break;
  8948. }
  8949. }
  8950.  
  8951. for (const hero of heroes) {
  8952. const exp = hero.xp;
  8953. if (exp < expHero.exp) {
  8954. expHero.heroId = hero.id;
  8955. }
  8956. }
  8957. return expHero;
  8958. }
  8959.  
  8960. getHeroIdTitanGift() {
  8961. const heroes = Object.values(this.questInfo['heroGetAll']);
  8962. const inventory = this.questInfo['inventoryGet'];
  8963. const user = this.questInfo['userGetInfo'];
  8964. const titanGiftLib = lib.getData('titanGift');
  8965. /** Искры */
  8966. const titanGift = inventory.consumable[24];
  8967. let heroId = 0;
  8968. let minLevel = 30;
  8969.  
  8970. if (titanGift < 250 || user.gold < 7000) {
  8971. return 0;
  8972. }
  8973.  
  8974. for (const hero of heroes) {
  8975. if (hero.titanGiftLevel >= 30) {
  8976. continue;
  8977. }
  8978.  
  8979. if (!hero.titanGiftLevel) {
  8980. return hero.id;
  8981. }
  8982.  
  8983. const cost = titanGiftLib[hero.titanGiftLevel].cost;
  8984. if (minLevel > hero.titanGiftLevel &&
  8985. titanGift >= cost.consumable[24] &&
  8986. user.gold >= cost.gold
  8987. ) {
  8988. minLevel = hero.titanGiftLevel;
  8989. heroId = hero.id;
  8990. }
  8991. }
  8992.  
  8993. return heroId;
  8994. }
  8995.  
  8996. end(status) {
  8997. setProgress(status, true);
  8998. this.resolve();
  8999. }
  9000. }
  9001.  
  9002. this.questRun = dailyQuests;
  9003.  
  9004. function testDoYourBest() {
  9005. return new Promise((resolve, reject) => {
  9006. const doIt = new doYourBest(resolve, reject);
  9007. doIt.start();
  9008. });
  9009. }
  9010.  
  9011. /**
  9012. * Do everything button
  9013. *
  9014. * Кнопка сделать все
  9015. */
  9016. class doYourBest {
  9017.  
  9018. funcList = [
  9019. //собрать запределье
  9020. {
  9021. name: 'getOutland',
  9022. label: I18N('ASSEMBLE_OUTLAND'),
  9023. checked: false
  9024. },
  9025. //пройти башню
  9026. {
  9027. name: 'testTower',
  9028. label: I18N('PASS_THE_TOWER'),
  9029. checked: false
  9030. },
  9031. //экспедиции
  9032. {
  9033. name: 'checkExpedition',
  9034. label: I18N('CHECK_EXPEDITIONS'),
  9035. checked: false
  9036. },
  9037. //турнир стихий
  9038. {
  9039. name: 'testTitanArena',
  9040. label: I18N('COMPLETE_TOE'),
  9041. checked: false
  9042. },
  9043. //собрать почту
  9044. {
  9045. name: 'mailGetAll',
  9046. label: I18N('COLLECT_MAIL'),
  9047. checked: false
  9048. },
  9049. //Собрать всякую херню
  9050. {
  9051. name: 'collectAllStuff',
  9052. label: I18N('COLLECT_MISC'),
  9053. title: I18N('COLLECT_MISC_TITLE'),
  9054. checked: false
  9055. },
  9056. //ежедневная награда
  9057. {
  9058. name: 'getDailyBonus',
  9059. label: I18N('DAILY_BONUS'),
  9060. checked: false
  9061. },
  9062. //ежедневные квесты удалить наверно
  9063. /*
  9064. {
  9065. name: 'dailyQuests',
  9066. label: I18N('DO_DAILY_QUESTS'),
  9067. checked: false
  9068. },
  9069. */
  9070. //собрать награды за квесты
  9071. {
  9072. name: 'questAllFarm',
  9073. label: I18N('COLLECT_QUEST_REWARDS'),
  9074. checked: false
  9075. },
  9076. // тест отправь подарки согильдийцам
  9077. {
  9078. name: 'testclanSendDailyGifts',
  9079. label: I18N('QUEST_10016'),
  9080. checked: false
  9081. },
  9082. // тест сферу титанов
  9083. {
  9084. name: 'testtitanArtifactChestOpen',
  9085. label: I18N('QUEST_10029'),
  9086. checked: false
  9087. },
  9088. // тест призыв петов
  9089. {
  9090. name: 'testpet_chestOpen',
  9091. label: I18N('QUEST_10044'),
  9092. checked: false
  9093. },
  9094. //пройти подземелье обычное
  9095. {
  9096. name: 'testDungeon',
  9097. label: I18N('COMPLETE_DUNGEON'),
  9098. checked: false
  9099. },
  9100. //синхронизация
  9101. {
  9102. name: 'synchronization',
  9103. label: I18N('MAKE_A_SYNC'),
  9104. checked: false
  9105. },
  9106. //перезагрузка
  9107. {
  9108. name: 'reloadGame',
  9109. label: I18N('RELOAD_GAME'),
  9110. checked: false
  9111. },
  9112. ];
  9113.  
  9114. functions = {
  9115. getOutland,//собрать запределье
  9116. testTower,//прохождение башни
  9117. checkExpedition,//автоэкспедиции
  9118. testTitanArena,//Автопрохождение Турнира Стихий
  9119. mailGetAll,//Собрать всю почту, кроме писем с энергией и зарядами портала
  9120. //Собрать пасхалки, камни облика, ключи, монеты арены и Хрусталь души
  9121. collectAllStuff: async () => {
  9122. await offerFarmAllReward();
  9123. 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"}]}');
  9124. },
  9125. //Выполнять ежедневные квесты
  9126. dailyQuests: async function () {
  9127. const quests = new dailyQuests(() => { }, () => { });
  9128. await quests.autoInit(true);
  9129. await quests.start();
  9130. },
  9131. getDailyBonus,//ежедневная награда
  9132. questAllFarm,//Собрать все награды за задания
  9133. testclanSendDailyGifts, //отправить подарки
  9134. testtitanArtifactChestOpen, //открой сферу титанов
  9135. testpet_chestOpen, //Воспользуйся призывом питомцев 1 раз
  9136. testDungeon,//подземка обычная
  9137. synchronization: async () => {
  9138. cheats.refreshGame();
  9139. },
  9140. reloadGame: async () => {
  9141. location.reload();
  9142. }
  9143. }
  9144.  
  9145. constructor(resolve, reject, questInfo) {
  9146. this.resolve = resolve;
  9147. this.reject = reject;
  9148. this.questInfo = questInfo
  9149. }
  9150.  
  9151. async start() {
  9152. const selectedDoIt = getSaveVal('selectedDoIt', {});
  9153.  
  9154. this.funcList.forEach(task => {
  9155. if (!selectedDoIt[task.name]) {
  9156. selectedDoIt[task.name] = {
  9157. checked: task.checked
  9158. }
  9159. } else {
  9160. task.checked = selectedDoIt[task.name].checked
  9161. }
  9162. });
  9163.  
  9164. const answer = await popup.confirm(I18N('RUN_FUNCTION'), [
  9165. { msg: I18N('BTN_CANCEL'), result: false },
  9166. { msg: I18N('BTN_GO'), result: true },
  9167. ], this.funcList);
  9168.  
  9169. if (!answer) {
  9170. this.end('');
  9171. return;
  9172. }
  9173.  
  9174. const taskList = popup.getCheckBoxes();
  9175. taskList.forEach(task => {
  9176. selectedDoIt[task.name].checked = task.checked;
  9177. });
  9178. setSaveVal('selectedDoIt', selectedDoIt);
  9179. for (const task of popup.getCheckBoxes()) {
  9180. if (task.checked) {
  9181. try {
  9182. setProgress(`${task.label} <br>${I18N('PERFORMED')}!`);
  9183. await this.functions[task.name]();
  9184. setProgress(`${task.label} <br>${I18N('DONE')}!`);
  9185. } catch (error) {
  9186. if (await popup.confirm(`${I18N('ERRORS_OCCURRES')}:<br> ${task.label} <br>${I18N('COPY_ERROR')}?`, [
  9187. { msg: I18N('BTN_NO'), result: false },
  9188. { msg: I18N('BTN_YES'), result: true },
  9189. ])) {
  9190. this.errorHandling(error);
  9191. }
  9192. }
  9193. }
  9194. }
  9195. setTimeout((msg) => {
  9196. this.end(msg);
  9197. }, 2000, I18N('ALL_TASK_COMPLETED'));
  9198. return;
  9199. }
  9200.  
  9201. errorHandling(error) {
  9202. //console.error(error);
  9203. let errorInfo = error.toString() + '\n';
  9204. try {
  9205. const errorStack = error.stack.split('\n');
  9206. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testDoYourBest");
  9207. errorInfo += errorStack.slice(0, endStack).join('\n');
  9208. } catch (e) {
  9209. errorInfo += error.stack;
  9210. }
  9211. copyText(errorInfo);
  9212. }
  9213.  
  9214. end(status) {
  9215. setProgress(status, true);
  9216. this.resolve();
  9217. }
  9218. }
  9219.  
  9220. /**
  9221. * Passing the adventure along the specified route
  9222. *
  9223. * Прохождение приключения по указанному маршруту
  9224. */
  9225. function testAdventure(type) {
  9226. return new Promise((resolve, reject) => {
  9227. const bossBattle = new executeAdventure(resolve, reject);
  9228. bossBattle.start(type);
  9229. });
  9230. }
  9231.  
  9232. /**
  9233. * Passing the adventure along the specified route
  9234. *
  9235. * Прохождение приключения по указанному маршруту
  9236. */
  9237. class executeAdventure {
  9238.  
  9239. type = 'default';
  9240.  
  9241. actions = {
  9242. default: {
  9243. getInfo: "adventure_getInfo",
  9244. startBattle: 'adventure_turnStartBattle',
  9245. endBattle: 'adventure_endBattle',
  9246. collectBuff: 'adventure_turnCollectBuff'
  9247. },
  9248. solo: {
  9249. getInfo: "adventureSolo_getInfo",
  9250. startBattle: 'adventureSolo_turnStartBattle',
  9251. endBattle: 'adventureSolo_endBattle',
  9252. collectBuff: 'adventureSolo_turnCollectBuff'
  9253. }
  9254. }
  9255.  
  9256. terminatеReason = I18N('UNKNOWN');
  9257. callAdventureInfo = {
  9258. name: "adventure_getInfo",
  9259. args: {},
  9260. ident: "adventure_getInfo"
  9261. }
  9262. callTeamGetAll = {
  9263. name: "teamGetAll",
  9264. args: {},
  9265. ident: "teamGetAll"
  9266. }
  9267. callTeamGetFavor = {
  9268. name: "teamGetFavor",
  9269. args: {},
  9270. ident: "teamGetFavor"
  9271. }
  9272. //тест прикла
  9273. defaultWays = {
  9274. //Галахад, 1-я
  9275. "adv_strongford_2pl_easy": {
  9276. first: '1,2,3,5,6',
  9277. second: '1,2,4,7,6',
  9278. third: '1,2,3,5,6'
  9279. },
  9280. //Джинджер, 2-я
  9281. "adv_valley_3pl_easy": {
  9282. first: '1,2,5,8,9,11',
  9283. second: '1,3,6,9,11',
  9284. third: '1,4,7,10,9,11'
  9285. },
  9286. //Орион, 3-я
  9287. "adv_ghirwil_3pl_easy": {
  9288. first: '1,5,6,9,11',
  9289. second: '1,4,12,13,11',
  9290. third: '1,2,3,7,10,11'
  9291. },
  9292. //Тесак, 4-я
  9293. "adv_angels_3pl_easy_fire": {
  9294. first: '1,2,4,7,18,8,12,19,22,23',
  9295. second: '1,3,6,11,17,10,16,21,22,23',
  9296. third: '1,5,24,25,9,14,15,20,22,23'
  9297. },
  9298. //Галахад, 5-я
  9299. "adv_strongford_3pl_normal_2": {
  9300. first: '1,2,7,8,12,16,23,26,25,21,24',
  9301. second: '1,4,6,10,11,15,22,15,19,18,24',
  9302. third: '1,5,9,10,14,17,20,27,25,21,24'
  9303. },
  9304. //Джинджер, 6-я
  9305. "adv_valley_3pl_normal": {
  9306. first: '1,2,4,7,10,13,16,19,24,22,25',
  9307. second: '1,3,6,9,12,15,18,21,26,23,25',
  9308. third: '1,5,7,8,11,14,17,20,22,25'
  9309. },
  9310. //Орион, 7-я
  9311. "adv_ghirwil_3pl_normal_2": {
  9312. first: '1,11,10,11,12,15,12,11,21,25,27',
  9313. second: '1,7,3,4,3,6,13,19,20,24,27',
  9314. third: '1,8,5,9,16,23,22,26,27'
  9315. },
  9316. //Тесак, 8-я
  9317. "adv_angels_3pl_normal": {
  9318. first: '1,3,4,8,7,9,10,13,17,16,20,22,23,31,32',
  9319. second: '1,3,5,7,8,11,14,18,20,22,24,27,30,26,32',
  9320. third: '1,3,2,6,7,9,11,15,19,20,22,21,28,29,25'
  9321. },
  9322. //Галахад, 9-я
  9323. "adv_strongford_3pl_hard_2": {
  9324. first: '1,2,6,10,15,7,16,17,23,22,27,32,35,37,40,45',
  9325. second: '1,3,8,12,11,18,19,28,34,33,38,41,43,46,45',
  9326. third: '1,2,5,9,14,20,26,21,30,36,39,42,44,45'
  9327. },
  9328. //Джинджер, 10-я
  9329. "adv_valley_3pl_hard": {
  9330. first: '1,3,2,6,11,17,25,30,35,34,29,24,21,17,12,7',
  9331. second: '1,4,8,13,18,22,26,31,36,40,45,44,43,38,33,28',
  9332. third: '1,5,9,14,19,23,27,32,37,42,48,51,50,49,46,52'
  9333. },
  9334. //Орион, 11-я
  9335. "adv_ghirwil_3pl_hard": {
  9336. first: '1,2,3,6,8,12,11,15,21,27,36,34,33,35,37',
  9337. second: '1,2,4,6,9,13,18,17,16,22,28,29,30,31,25,19',
  9338. third: '1,2,5,6,10,13,14,20,26,32,38,41,40,39,37'
  9339. },
  9340. //Тесак, 12-я
  9341. "adv_angels_3pl_hard": {
  9342. first: '1,2,8,11,7,4,7,16,23,32,33,25,34,29,35,36',
  9343. second: '1,3,9,13,10,6,10,22,31,30,21,30,15,28,20,27',
  9344. third: '1,5,12,14,24,17,24,25,26,18,19,20,27'
  9345. },
  9346. //Тесак, 13-я
  9347. "adv_angels_3pl_hell": {
  9348. first: '1,2,4,6,16,23,33,34,25,32,29,28,20,27',
  9349. second: '1,7,11,17,24,14,26,18,19,20,27,20,12,8',
  9350. third: '1,9,3,5,10,22,31,36,31,30,15,28,29,30,21,13'
  9351. },
  9352. //Галахад, 13-я
  9353. "adv_strongford_3pl_hell": {
  9354. first: '1,2,5,11,14,20,26,21,30,35,38,41,43,44',
  9355. second: '1,2,6,12,15,7,16,17,23,22,27,42,34,36,39,44',
  9356. third: '1,3,8,9,13,18,19,28,0,33,37,40,32,45,44'
  9357. },
  9358. //Орион, 13-я
  9359. "adv_ghirwil_3pl_hell": {
  9360. first: '1,2,3,6,8,12,11,15,21,27,36,34,33,35,37',
  9361. second: '1,2,4,6,9,13,18,17,16,22,28,29,30,31,25,19',
  9362. third: '1,2,5,6,10,13,14,20,26,32,38,41,40,39,37'
  9363. },
  9364. //Джинджер, 13-я
  9365. "adv_valley_3pl_hell": {
  9366. first: '1,3,2,6,11,17,25,30,35,34,29,24,21,17,12,7',
  9367. second: '1,4,8,13,18,22,26,31,36,40,45,44,43,38,33,28',
  9368. third: '1,5,9,14,19,23,27,32,37,42,48,51,50,49,46,52'
  9369. }
  9370. }
  9371. callStartBattle = {
  9372. name: "adventure_turnStartBattle",
  9373. args: {},
  9374. ident: "body"
  9375. }
  9376. callEndBattle = {
  9377. name: "adventure_endBattle",
  9378. args: {
  9379. result: {},
  9380. progress: {},
  9381. },
  9382. ident: "body"
  9383. }
  9384. callCollectBuff = {
  9385. name: "adventure_turnCollectBuff",
  9386. args: {},
  9387. ident: "body"
  9388. }
  9389.  
  9390. constructor(resolve, reject) {
  9391. this.resolve = resolve;
  9392. this.reject = reject;
  9393. }
  9394.  
  9395. async start(type) {
  9396. /*this.type = type || this.type;
  9397. this.path = await this.getPath();
  9398. if (!this.path) {
  9399. this.end();
  9400. return;
  9401. }
  9402. this.callAdventureInfo.name = this.actions[this.type].getInfo;
  9403. */
  9404. const data = await Send(JSON.stringify({
  9405. calls: [
  9406. this.callAdventureInfo,
  9407. this.callTeamGetAll,
  9408. this.callTeamGetFavor
  9409. ]
  9410. }));
  9411. //тест прикла1
  9412. this.path = await this.getPath(data.results[0].result.response.mapIdent);
  9413. if (!this.path) {
  9414. this.end();
  9415. return;
  9416. }
  9417. return this.checkAdventureInfo(data.results);
  9418. }
  9419.  
  9420. async getPath(mapId) {
  9421. //const answer = await popup.confirm(I18N('ENTER_THE_PATH'), [
  9422. /*{
  9423. msg: I18N('START_ADVENTURE'),
  9424. placeholder: '1,2,3,4,5,6',
  9425. isInput: true,
  9426. default: getSaveVal('adventurePath', '')
  9427. },*/
  9428. //тест
  9429. const answer = await popup.confirm('Введите путь приключения через запятые', [
  9430. {
  9431. msg: 'Начать приключение по этому пути!',
  9432. placeholder: '1,2,3,4,5,6,7',
  9433. isInput: true,
  9434. default: getSaveVal('adventurePath', '')
  9435. },
  9436. {
  9437. msg: ' Начать по пути №1! ',
  9438. placeholder: '1,2,3',
  9439. isInput: true,
  9440. default: this.defaultWays[mapId]?.first
  9441. },
  9442. {
  9443. msg: ' Начать по пути №2! ',
  9444. placeholder: '1,2,3',
  9445. isInput: true,
  9446. default: this.defaultWays[mapId]?.second
  9447. },
  9448. {
  9449. msg: ' Начать по пути №3! ',
  9450. placeholder: '1,2,3',
  9451. isInput: true,
  9452. default: this.defaultWays[mapId]?.third
  9453. },
  9454. {
  9455. msg: I18N('BTN_CANCEL'),
  9456. result: false
  9457. },
  9458. ]);
  9459. if (!answer) {
  9460. this.terminatеReason = I18N('BTN_CANCELED');
  9461. return false;
  9462. }
  9463. //тест запятые или дефисы
  9464. let path = answer.split(',');
  9465. if (path.length < 2) {
  9466. path = answer.split('-');
  9467. }
  9468. if (path.length < 2) {
  9469. this.terminatеReason = I18N('MUST_TWO_POINTS');
  9470. return false;
  9471. }
  9472.  
  9473. for (let p in path) {
  9474. path[p] = +path[p].trim()
  9475. if (Number.isNaN(path[p])) {
  9476. this.terminatеReason = I18N('MUST_ONLY_NUMBERS');
  9477. return false;
  9478. }
  9479. }
  9480. setSaveVal('adventurePath', answer);
  9481. return path;
  9482. }
  9483.  
  9484. checkAdventureInfo(data) {
  9485. this.advInfo = data[0].result.response;
  9486. if (!this.advInfo) {
  9487. this.terminatеReason = I18N('NOT_ON_AN_ADVENTURE') ;
  9488. return this.end();
  9489. }
  9490. const heroesTeam = data[1].result.response.adventure_hero;
  9491. const favor = data[2]?.result.response.adventure_hero;
  9492. const heroes = heroesTeam.slice(0, 5);
  9493. const pet = heroesTeam[5];
  9494. this.args = {
  9495. pet,
  9496. heroes,
  9497. favor,
  9498. path: [],
  9499. broadcast: false
  9500. }
  9501. const advUserInfo = this.advInfo.users[userInfo.id];
  9502. this.turnsLeft = advUserInfo.turnsLeft;
  9503. this.currentNode = advUserInfo.currentNode;
  9504. this.nodes = this.advInfo.nodes;
  9505.  
  9506. if (this.currentNode == 1 && this.path[0] != 1) {
  9507. this.path.unshift(1);
  9508. }
  9509.  
  9510. return this.loop();
  9511. }
  9512.  
  9513. async loop() {
  9514. const position = this.path.indexOf(+this.currentNode);
  9515. if (!(~position)) {
  9516. this.terminatеReason = I18N('YOU_IN_NOT_ON_THE_WAY');
  9517. return this.end();
  9518. }
  9519. this.path = this.path.slice(position);
  9520. if ((this.path.length - 1) > this.turnsLeft &&
  9521. await popup.confirm(I18N('ATTEMPTS_NOT_ENOUGH'), [
  9522. { msg: I18N('YES_CONTINUE'), result: false },
  9523. { msg: I18N('BTN_NO'), result: true },
  9524. ])) {
  9525. this.terminatеReason = I18N('NOT_ENOUGH_AP');
  9526. return this.end();
  9527. }
  9528. const toPath = [];
  9529. for (const nodeId of this.path) {
  9530. if (!this.turnsLeft) {
  9531. this.terminatеReason = I18N('ATTEMPTS_ARE_OVER');
  9532. return this.end();
  9533. }
  9534. toPath.push(nodeId);
  9535. console.log(toPath);
  9536. if (toPath.length > 1) {
  9537. setProgress(toPath.join(' > ') + ` ${I18N('MOVES')}: ` + this.turnsLeft);
  9538. }
  9539. if (nodeId == this.currentNode) {
  9540. continue;
  9541. }
  9542.  
  9543. const nodeInfo = this.getNodeInfo(nodeId);
  9544. if (nodeInfo.type == 'TYPE_COMBAT') {
  9545. if (nodeInfo.state == 'empty') {
  9546. this.turnsLeft--;
  9547. continue;
  9548. }
  9549.  
  9550. /**
  9551. * Disable regular battle cancellation
  9552. *
  9553. * Отключаем штатную отменую боя
  9554. */
  9555. isCancalBattle = false;
  9556. if (await this.battle(toPath)) {
  9557. this.turnsLeft--;
  9558. toPath.splice(0, toPath.indexOf(nodeId));
  9559. nodeInfo.state = 'empty';
  9560. isCancalBattle = true;
  9561. continue;
  9562. }
  9563. isCancalBattle = true;
  9564. return this.end()
  9565. }
  9566.  
  9567. if (nodeInfo.type == 'TYPE_PLAYERBUFF') {
  9568. const buff = this.checkBuff(nodeInfo);
  9569. if (buff == null) {
  9570. continue;
  9571. }
  9572.  
  9573. if (await this.collectBuff(buff, toPath)) {
  9574. this.turnsLeft--;
  9575. toPath.splice(0, toPath.indexOf(nodeId));
  9576. continue;
  9577. }
  9578. this.terminatеReason = I18N('BUFF_GET_ERROR');
  9579. return this.end();
  9580. }
  9581. }
  9582. this.terminatеReason = I18N('SUCCESS');
  9583. return this.end();
  9584. }
  9585.  
  9586. /**
  9587. * Carrying out a fight
  9588. *
  9589. * Проведение боя
  9590. */
  9591. async battle(path, preCalc = true) {
  9592. const data = await this.startBattle(path);
  9593. try {
  9594. const battle = data.results[0].result.response.battle;
  9595. const result = await Calc(battle);
  9596. if (result.result.win) {
  9597. const info = await this.endBattle(result);
  9598. if (info.results[0].result.response?.error) {
  9599. this.terminatеReason = I18N('BATTLE_END_ERROR');
  9600. return false;
  9601. }
  9602. } else {
  9603. await this.cancelBattle(result);
  9604.  
  9605. if (preCalc && await this.preCalcBattle(battle)) {
  9606. path = path.slice(-2);
  9607. for (let i = 1; i <= getInput('countAutoBattle'); i++) {
  9608. setProgress(`${I18N('AUTOBOT')}: ${i}/${getInput('countAutoBattle')}`);
  9609. const result = await this.battle(path, false);
  9610. if (result) {
  9611. setProgress(I18N('VICTORY'));
  9612. return true;
  9613. }
  9614. }
  9615. this.terminatеReason = I18N('FAILED_TO_WIN_AUTO');
  9616. return false;
  9617. }
  9618. return false;
  9619. }
  9620. } catch (error) {
  9621. console.error(error);
  9622. if (await popup.confirm(I18N('ERROR_OF_THE_BATTLE_COPY'), [
  9623. { msg: I18N('BTN_NO'), result: false },
  9624. { msg: I18N('BTN_YES'), result: true },
  9625. ])) {
  9626. this.errorHandling(error, data);
  9627. }
  9628. this.terminatеReason = I18N('ERROR_DURING_THE_BATTLE');
  9629. return false;
  9630. }
  9631. return true;
  9632. }
  9633.  
  9634. /**
  9635. * Recalculate battles
  9636. *
  9637. * Прерасчтет битвы
  9638. */
  9639. async preCalcBattle(battle) {
  9640. const countTestBattle = getInput('countTestBattle');
  9641. for (let i = 0; i < countTestBattle; i++) {
  9642. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  9643. const result = await Calc(battle);
  9644. if (result.result.win) {
  9645. console.log(i, countTestBattle);
  9646. return true;
  9647. }
  9648. }
  9649. this.terminatеReason = I18N('NO_CHANCE_WIN') + countTestBattle;
  9650. return false;
  9651. }
  9652. /**
  9653. * Starts a fight
  9654. *
  9655. * Начинает бой
  9656. */
  9657. startBattle(path) {
  9658. this.args.path = path;
  9659. this.callStartBattle.name = this.actions[this.type].startBattle;
  9660. this.callStartBattle.args = this.args
  9661. const calls = [this.callStartBattle];
  9662. return Send(JSON.stringify({ calls }));
  9663. }
  9664.  
  9665. cancelBattle(battle) {
  9666. const fixBattle = function (heroes) {
  9667. for (const ids in heroes) {
  9668. const hero = heroes[ids];
  9669. hero.energy = random(1, 999);
  9670. if (hero.hp > 0) {
  9671. hero.hp = random(1, hero.hp);
  9672. }
  9673. }
  9674. }
  9675. fixBattle(battle.progress[0].attackers.heroes);
  9676. fixBattle(battle.progress[0].defenders.heroes);
  9677. return this.endBattle(battle);
  9678. }
  9679.  
  9680. /**
  9681. * Ends the fight
  9682. *
  9683. * Заканчивает бой
  9684. */
  9685. endBattle(battle) {
  9686. this.callEndBattle.name = this.actions[this.type].endBattle;
  9687. this.callEndBattle.args.result = battle.result
  9688. this.callEndBattle.args.progress = battle.progress
  9689. const calls = [this.callEndBattle];
  9690. return Send(JSON.stringify({ calls }));
  9691. }
  9692.  
  9693. /**
  9694. * Checks if you can get a buff
  9695. *
  9696. * Проверяет можно ли получить баф
  9697. */
  9698. checkBuff(nodeInfo) {
  9699. let id = null;
  9700. let value = 0;
  9701. for (const buffId in nodeInfo.buffs) {
  9702. const buff = nodeInfo.buffs[buffId];
  9703. if (buff.owner == null && buff.value > value) {
  9704. id = buffId;
  9705. value = buff.value;
  9706. }
  9707. }
  9708. nodeInfo.buffs[id].owner = 'Я';
  9709. return id;
  9710. }
  9711.  
  9712. /**
  9713. * Collects a buff
  9714. *
  9715. * Собирает баф
  9716. */
  9717. async collectBuff(buff, path) {
  9718. this.callCollectBuff.name = this.actions[this.type].collectBuff;
  9719. this.callCollectBuff.args = { buff, path };
  9720. const calls = [this.callCollectBuff];
  9721. return Send(JSON.stringify({ calls }));
  9722. }
  9723.  
  9724. getNodeInfo(nodeId) {
  9725. return this.nodes.find(node => node.id == nodeId);
  9726. }
  9727.  
  9728. errorHandling(error, data) {
  9729. //console.error(error);
  9730. let errorInfo = error.toString() + '\n';
  9731. try {
  9732. const errorStack = error.stack.split('\n');
  9733. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testAdventure");
  9734. errorInfo += errorStack.slice(0, endStack).join('\n');
  9735. } catch (e) {
  9736. errorInfo += error.stack;
  9737. }
  9738. if (data) {
  9739. errorInfo += '\nData: ' + JSON.stringify(data);
  9740. }
  9741. copyText(errorInfo);
  9742. }
  9743.  
  9744. end() {
  9745. isCancalBattle = true;
  9746. setProgress(this.terminatеReason, true);
  9747. console.log(this.terminatеReason);
  9748. this.resolve();
  9749. }
  9750. }
  9751.  
  9752. /**
  9753. * Passage of brawls
  9754. *
  9755. * Прохождение потасовок
  9756. */
  9757. function testBrawls() {
  9758. return new Promise((resolve, reject) => {
  9759. const brawls = new executeBrawls(resolve, reject);
  9760. brawls.start(brawlsPack);
  9761. });
  9762. }
  9763. /**
  9764. * Passage of brawls
  9765. *
  9766. * Прохождение потасовок
  9767. */
  9768. class executeBrawls {
  9769. callBrawlQuestGetInfo = {
  9770. name: "brawl_questGetInfo",
  9771. args: {},
  9772. ident: "brawl_questGetInfo"
  9773. }
  9774. callBrawlFindEnemies = {
  9775. name: "brawl_findEnemies",
  9776. args: {},
  9777. ident: "brawl_findEnemies"
  9778. }
  9779. callBrawlQuestFarm = {
  9780. name: "brawl_questFarm",
  9781. args: {},
  9782. ident: "brawl_questFarm"
  9783. }
  9784. callUserGetInfo = {
  9785. name: "userGetInfo",
  9786. args: {},
  9787. ident: "userGetInfo"
  9788. }
  9789.  
  9790. stats = {
  9791. win: 0,
  9792. loss: 0,
  9793. count: 0,
  9794. }
  9795.  
  9796. stage = {
  9797. '3': 1,
  9798. '7': 2,
  9799. '12': 3,
  9800. }
  9801.  
  9802. attempts = 0;
  9803.  
  9804. constructor(resolve, reject) {
  9805. this.resolve = resolve;
  9806. this.reject = reject;
  9807. }
  9808.  
  9809. async start(args) {
  9810. this.args = args;
  9811. isCancalBattle = false;
  9812. this.brawlInfo = await this.getBrawlInfo();
  9813. this.attempts = this.brawlInfo.attempts;
  9814.  
  9815. if (!this.attempts) {
  9816. this.end(I18N('DONT_HAVE_LIVES'))
  9817. return;
  9818. }
  9819.  
  9820. while (1) {
  9821. if (!isBrawlsAutoStart) {
  9822. this.end(I18N('BTN_CANCELED'))
  9823. return;
  9824. }
  9825.  
  9826. const maxStage = this.brawlInfo.questInfo.stage;
  9827. const stage = this.stage[maxStage];
  9828. const progress = this.brawlInfo.questInfo.progress;
  9829.  
  9830. 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 () {
  9831. isBrawlsAutoStart = false;
  9832. });
  9833.  
  9834. if (this.brawlInfo.questInfo.canFarm) {
  9835. const result = await this.questFarm();
  9836. console.log(result);
  9837. }
  9838.  
  9839. if (this.brawlInfo.questInfo.stage == 12 && this.brawlInfo.questInfo.progress == 12) {
  9840. this.end(I18N('SUCCESS'))
  9841. return;
  9842. }
  9843.  
  9844. if (!this.attempts) {
  9845. this.end(I18N('DONT_HAVE_LIVES'))
  9846. return;
  9847. }
  9848.  
  9849. const enemie = Object.values(this.brawlInfo.findEnemies).shift();
  9850.  
  9851. const result = await this.battle(enemie.userId);
  9852. this.brawlInfo = {
  9853. questInfo: result[1].result.response,
  9854. findEnemies: result[2].result.response,
  9855. }
  9856. }
  9857. }
  9858.  
  9859. async questFarm() {
  9860. const calls = [this.callBrawlQuestFarm];
  9861. const result = await Send(JSON.stringify({ calls }));
  9862. return result.results[0].result.response;
  9863. }
  9864.  
  9865. async getBrawlInfo() {
  9866. const data = await Send(JSON.stringify({
  9867. calls: [
  9868. this.callUserGetInfo,
  9869. this.callBrawlQuestGetInfo,
  9870. this.callBrawlFindEnemies,
  9871. ]
  9872. }));
  9873.  
  9874. let attempts = data.results[0].result.response.refillable.find(n => n.id == 48);
  9875. return {
  9876. attempts: attempts.amount,
  9877. questInfo: data.results[1].result.response,
  9878. findEnemies: data.results[2].result.response,
  9879. }
  9880. }
  9881.  
  9882. /**
  9883. * Carrying out a fight
  9884. *
  9885. * Проведение боя
  9886. */
  9887. async battle(userId) {
  9888. this.stats.count++;
  9889. const battle = await this.startBattle(userId, this.args);
  9890. const result = await Calc(battle);
  9891. console.log(result.result);
  9892. if (result.result.win) {
  9893. this.stats.win++;
  9894. } else {
  9895. this.stats.loss++;
  9896. this.attempts--;
  9897. }
  9898. return await this.endBattle(result);
  9899. // return await this.cancelBattle(result);
  9900. }
  9901.  
  9902. /**
  9903. * Starts a fight
  9904. *
  9905. * Начинает бой
  9906. */
  9907. async startBattle(userId, args) {
  9908. const call = {
  9909. name: "brawl_startBattle",
  9910. args,
  9911. ident: "brawl_startBattle"
  9912. }
  9913. call.args.userId = userId;
  9914. const calls = [call];
  9915. const result = await Send(JSON.stringify({ calls }));
  9916. return result.results[0].result.response;
  9917. }
  9918.  
  9919. cancelBattle(battle) {
  9920. const fixBattle = function (heroes) {
  9921. for (const ids in heroes) {
  9922. const hero = heroes[ids];
  9923. hero.energy = random(1, 999);
  9924. if (hero.hp > 0) {
  9925. hero.hp = random(1, hero.hp);
  9926. }
  9927. }
  9928. }
  9929. fixBattle(battle.progress[0].attackers.heroes);
  9930. fixBattle(battle.progress[0].defenders.heroes);
  9931. return this.endBattle(battle);
  9932. }
  9933.  
  9934. /**
  9935. * Ends the fight
  9936. *
  9937. * Заканчивает бой
  9938. */
  9939. async endBattle(battle) {
  9940. battle.progress[0].attackers.input = ['auto', 0, 0, 'auto', 0, 0];
  9941. const calls = [{
  9942. name: "brawl_endBattle",
  9943. args: {
  9944. result: battle.result,
  9945. progress: battle.progress
  9946. },
  9947. ident: "brawl_endBattle"
  9948. },
  9949. this.callBrawlQuestGetInfo,
  9950. this.callBrawlFindEnemies,
  9951. ];
  9952. const result = await Send(JSON.stringify({ calls }));
  9953. return result.results;
  9954. }
  9955.  
  9956. end(endReason) {
  9957. isCancalBattle = true;
  9958. isBrawlsAutoStart = false;
  9959. setProgress(endReason, true);
  9960. console.log(endReason);
  9961. this.resolve();
  9962. }
  9963. }
  9964. // подземку вконце впихнул
  9965. function DungeonFull() {
  9966. return new Promise((resolve, reject) => {
  9967. const dung = new executeDungeon2(resolve, reject);
  9968. const titanit = getInput('countTitanit');
  9969. dung.start(titanit);
  9970. });
  9971. }
  9972. /** Прохождение подземелья */
  9973. function executeDungeon2(resolve, reject) {
  9974. let dungeonActivity = 0;
  9975. let startDungeonActivity = 0;
  9976. let maxDungeonActivity = 150;
  9977. let limitDungeonActivity = 30180;
  9978. let countShowStats = 1;
  9979. //let fastMode = isChecked('fastMode');
  9980. let end = false;
  9981.  
  9982. let countTeam = [];
  9983. let timeDungeon = {
  9984. all: new Date().getTime(),
  9985. findAttack: 0,
  9986. attackNeutral: 0,
  9987. attackEarthOrFire: 0
  9988. }
  9989.  
  9990. let titansStates = {};
  9991. let bestBattle = {};
  9992.  
  9993. let teams = {
  9994. neutral: [],
  9995. water: [],
  9996. earth: [],
  9997. fire: [],
  9998. hero: []
  9999. }
  10000.  
  10001. let callsExecuteDungeon = {
  10002. calls: [{
  10003. name: "dungeonGetInfo",
  10004. args: {},
  10005. ident: "dungeonGetInfo"
  10006. }, {
  10007. name: "teamGetAll",
  10008. args: {},
  10009. ident: "teamGetAll"
  10010. }, {
  10011. name: "teamGetFavor",
  10012. args: {},
  10013. ident: "teamGetFavor"
  10014. }, {
  10015. name: "clanGetInfo",
  10016. args: {},
  10017. ident: "clanGetInfo"
  10018. }]
  10019. }
  10020.  
  10021. this.start = async function(titanit) {
  10022. //maxDungeonActivity = titanit > limitDungeonActivity ? limitDungeonActivity : titanit;
  10023. maxDungeonActivity = titanit || getInput('countTitanit');
  10024. send(JSON.stringify(callsExecuteDungeon), startDungeon);
  10025. }
  10026.  
  10027. /** Получаем данные по подземелью */
  10028. function startDungeon(e) {
  10029. stopDung = false; // стоп подземка
  10030. let res = e.results;
  10031. let dungeonGetInfo = res[0].result.response;
  10032. if (!dungeonGetInfo) {
  10033. endDungeon('noDungeon', res);
  10034. return;
  10035. }
  10036. console.log("Начинаем копать на фулл: ", new Date());
  10037. let teamGetAll = res[1].result.response;
  10038. let teamGetFavor = res[2].result.response;
  10039. dungeonActivity = res[3].result.response.stat.todayDungeonActivity;
  10040. startDungeonActivity = res[3].result.response.stat.todayDungeonActivity;
  10041. titansStates = dungeonGetInfo.states.titans;
  10042.  
  10043. teams.hero = {
  10044. favor: teamGetFavor.dungeon_hero,
  10045. heroes: teamGetAll.dungeon_hero.filter(id => id < 6000),
  10046. teamNum: 0,
  10047. }
  10048. let heroPet = teamGetAll.dungeon_hero.filter(id => id >= 6000).pop();
  10049. if (heroPet) {
  10050. teams.hero.pet = heroPet;
  10051. }
  10052. teams.neutral = getTitanTeam('neutral');
  10053. teams.water = {
  10054. favor: {},
  10055. heroes: getTitanTeam('water'),
  10056. teamNum: 0,
  10057. };
  10058. teams.earth = {
  10059. favor: {},
  10060. heroes: getTitanTeam('earth'),
  10061. teamNum: 0,
  10062. };
  10063. teams.fire = {
  10064. favor: {},
  10065. heroes: getTitanTeam('fire'),
  10066. teamNum: 0,
  10067. };
  10068.  
  10069. checkFloor(dungeonGetInfo);
  10070. }
  10071.  
  10072. function getTitanTeam(type) {
  10073. switch (type) {
  10074. case 'neutral':
  10075. return [4023, 4022, 4012, 4021, 4011, 4010, 4020];
  10076. case 'water':
  10077. return [4000, 4001, 4002, 4003]
  10078. .filter(e => !titansStates[e]?.isDead);
  10079. case 'earth':
  10080. return [4020, 4022, 4021, 4023]
  10081. .filter(e => !titansStates[e]?.isDead);
  10082. case 'fire':
  10083. return [4010, 4011, 4012, 4013]
  10084. .filter(e => !titansStates[e]?.isDead);
  10085. }
  10086. }
  10087.  
  10088. /** Создать копию объекта */
  10089. function clone(a) {
  10090. return JSON.parse(JSON.stringify(a));
  10091. }
  10092.  
  10093. /** Находит стихию на этаже */
  10094. function findElement(floor, element) {
  10095. for (let i in floor) {
  10096. if (floor[i].attackerType === element) {
  10097. return i;
  10098. }
  10099. }
  10100. return undefined;
  10101. }
  10102.  
  10103. /** Проверяем этаж */
  10104. async function checkFloor(dungeonInfo) {
  10105. if (!('floor' in dungeonInfo) || dungeonInfo.floor?.state == 2) {
  10106. saveProgress();
  10107. return;
  10108. }
  10109. // console.log(dungeonInfo, dungeonActivity);
  10110. setProgress(`${I18N('DUNGEON2')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity}`);
  10111. //setProgress('Dungeon: Титанит ' + dungeonActivity + '/' + maxDungeonActivity);
  10112. if (dungeonActivity >= maxDungeonActivity) {
  10113. endDungeon('Стоп подземка,', 'набрано титанита: ' + dungeonActivity + '/' + maxDungeonActivity);
  10114. return;
  10115. }
  10116. let activity = dungeonActivity - startDungeonActivity;
  10117. titansStates = dungeonInfo.states.titans;
  10118. if (stopDung){
  10119. endDungeon('Стоп подземка,', 'набрано титанита: ' + dungeonActivity + '/' + maxDungeonActivity);
  10120. return;
  10121. }
  10122. /*if (activity / 1000 > countShowStats) {
  10123. countShowStats++;
  10124. showStats();
  10125. }*/
  10126. bestBattle = {};
  10127. let floorChoices = dungeonInfo.floor.userData;
  10128. if (floorChoices.length > 1) {
  10129. for (let element in teams) {
  10130. let teamNum = findElement(floorChoices, element);
  10131. if (!!teamNum) {
  10132. if (element == 'earth') {
  10133. teamNum = await chooseEarthOrFire(floorChoices);
  10134. if (teamNum < 0) {
  10135. endDungeon('Невозможно победить без потери Титана!', dungeonInfo);
  10136. return;
  10137. }
  10138. }
  10139. chooseElement(floorChoices[teamNum].attackerType, teamNum);
  10140. return;
  10141. }
  10142. }
  10143. } else {
  10144. chooseElement(floorChoices[0].attackerType, 0);
  10145. }
  10146. }
  10147.  
  10148. /** Выбираем огнем или землей атаковать */
  10149. async function chooseEarthOrFire(floorChoices) {
  10150. bestBattle.recovery = -11;
  10151. let selectedTeamNum = -1;
  10152. for (let attempt = 0; selectedTeamNum < 0 && attempt < 4; attempt++) {
  10153. for (let teamNum in floorChoices) {
  10154. let attackerType = floorChoices[teamNum].attackerType;
  10155. selectedTeamNum = await attemptAttackEarthOrFire(teamNum, attackerType, attempt);
  10156. }
  10157. }
  10158. console.log("Выбор команды огня или земли: ", selectedTeamNum < 0 ? "не сделан" : floorChoices[selectedTeamNum].attackerType);
  10159. return selectedTeamNum;
  10160. }
  10161.  
  10162. /** Попытка атаки землей и огнем */
  10163. async function attemptAttackEarthOrFire(teamNum, attackerType, attempt) {
  10164. let start = new Date();
  10165. let team = clone(teams[attackerType]);
  10166. let startIndex = team.heroes.length + attempt - 4;
  10167. if (startIndex >= 0) {
  10168. team.heroes = team.heroes.slice(startIndex);
  10169. let recovery = await getBestRecovery(teamNum, attackerType, team, 25);
  10170. if (recovery > bestBattle.recovery) {
  10171. bestBattle.recovery = recovery;
  10172. bestBattle.selectedTeamNum = teamNum;
  10173. bestBattle.team = team;
  10174. }
  10175. }
  10176. let workTime = new Date().getTime() - start.getTime();
  10177. timeDungeon.attackEarthOrFire += workTime;
  10178. if (bestBattle.recovery < -10) {
  10179. return -1;
  10180. }
  10181. return bestBattle.selectedTeamNum;
  10182. }
  10183.  
  10184. /** Выбираем стихию для атаки */
  10185. async function chooseElement(attackerType, teamNum) {
  10186. let result;
  10187. switch (attackerType) {
  10188. case 'hero':
  10189. case 'water':
  10190. result = await startBattle(teamNum, attackerType, teams[attackerType]);
  10191. break;
  10192. case 'earth':
  10193. case 'fire':
  10194. result = await attackEarthOrFire(teamNum, attackerType);
  10195. break;
  10196. case 'neutral':
  10197. result = await attackNeutral(teamNum, attackerType);
  10198. }
  10199. if (!!result && attackerType != 'hero') {
  10200. let recovery = (!!!bestBattle.recovery ? 10 * getRecovery(result) : bestBattle.recovery) * 100;
  10201. let titans = result.progress[0].attackers.heroes;
  10202. console.log("Проведен бой: " + attackerType +
  10203. ", recovery = " + (recovery > 0 ? "+" : "") + Math.round(recovery) + "% \r\n", titans);
  10204. }
  10205. endBattle(result);
  10206. }
  10207.  
  10208. /** Атакуем Землей или Огнем */
  10209. async function attackEarthOrFire(teamNum, attackerType) {
  10210. if (!!!bestBattle.recovery) {
  10211. bestBattle.recovery = -11;
  10212. let selectedTeamNum = -1;
  10213. for (let attempt = 0; selectedTeamNum < 0 && attempt < 4; attempt++) {
  10214. selectedTeamNum = await attemptAttackEarthOrFire(teamNum, attackerType, attempt);
  10215. }
  10216. if (selectedTeamNum < 0) {
  10217. endDungeon('Невозможно победить без потери Титана!', attackerType);
  10218. return;
  10219. }
  10220. }
  10221. return findAttack(teamNum, attackerType, bestBattle.team);
  10222. }
  10223.  
  10224. /** Находим подходящий результат для атаки */
  10225. async function findAttack(teamNum, attackerType, team) {
  10226. let start = new Date();
  10227. let recovery = -1000;
  10228. let iterations = 0;
  10229. let result;
  10230. let correction = 0.01;
  10231. for (let needRecovery = bestBattle.recovery; recovery < needRecovery; needRecovery -= correction, iterations++) {
  10232. result = await startBattle(teamNum, attackerType, team);
  10233. recovery = getRecovery(result);
  10234. }
  10235. bestBattle.recovery = recovery;
  10236. let workTime = new Date().getTime() - start.getTime();
  10237. timeDungeon.findAttack += workTime;
  10238. return result;
  10239. }
  10240.  
  10241. /** Атакуем Нейтральной командой */
  10242. async function attackNeutral(teamNum, attackerType) {
  10243. let start = new Date();
  10244. let factors = calcFactor();
  10245. bestBattle.recovery = -0.2;
  10246. await findBestBattleNeutral(teamNum, attackerType, factors, true)
  10247. if (bestBattle.recovery < 0 || (bestBattle.recovery < 0.2 && factors[0].value < 0.5)) {
  10248. let recovery = 100 * bestBattle.recovery;
  10249. console.log("Не удалось найти удачный бой в быстром режиме: " + attackerType +
  10250. ", recovery = " + (recovery > 0 ? "+" : "") + Math.round(recovery) + "% \r\n", bestBattle.attackers);
  10251. await findBestBattleNeutral(teamNum, attackerType, factors, false)
  10252. }
  10253. let workTime = new Date().getTime() - start.getTime();
  10254. timeDungeon.attackNeutral += workTime;
  10255. if (!!bestBattle.attackers) {
  10256. let team = getTeam(bestBattle.attackers);
  10257. return findAttack(teamNum, attackerType, team);
  10258. }
  10259. endDungeon('Не удалось найти удачный бой!', attackerType);
  10260. return undefined;
  10261. }
  10262.  
  10263. /** Находит лучшую нейтральную команду */
  10264. async function findBestBattleNeutral(teamNum, attackerType, factors, mode) {
  10265. let countFactors = factors.length < 4 ? factors.length : 4;
  10266. let aradgi = !titansStates['4013']?.isDead;
  10267. let edem = !titansStates['4023']?.isDead;
  10268. let dark = [4032, 4033].filter(e => !titansStates[e]?.isDead);
  10269. let light = [4042].filter(e => !titansStates[e]?.isDead);
  10270. let actions = [];
  10271. if (mode) {
  10272. for (let i = 0; i < countFactors; i++) {
  10273. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(factors[i].id)));
  10274. }
  10275. if (countFactors > 1) {
  10276. let firstId = factors[0].id;
  10277. let secondId = factors[1].id;
  10278. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4001, secondId)));
  10279. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4002, secondId)));
  10280. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4003, secondId)));
  10281. }
  10282. if (aradgi) {
  10283. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(4013)));
  10284. if (countFactors > 0) {
  10285. let firstId = factors[0].id;
  10286. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4000, 4013)));
  10287. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4001, 4013)));
  10288. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4002, 4013)));
  10289. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4003, 4013)));
  10290. }
  10291. if (edem) {
  10292. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(4023, 4000, 4013)));
  10293. }
  10294. }
  10295. } else {
  10296. if (mode) {
  10297. for (let i = 0; i < factors.length; i++) {
  10298. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(factors[i].id)));
  10299. }
  10300. } else {
  10301. countFactors = factors.length < 2 ? factors.length : 2;
  10302. }
  10303. for (let i = 0; i < countFactors; i++) {
  10304. let mainId = factors[i].id;
  10305. if (aradgi && (mode || i > 0)) {
  10306. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4000, 4013)));
  10307. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4001, 4013)));
  10308. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4002, 4013)));
  10309. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4003, 4013)));
  10310. }
  10311. for (let i = 0; i < dark.length; i++) {
  10312. let darkId = dark[i];
  10313. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4001, darkId)));
  10314. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4002, darkId)));
  10315. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4003, darkId)));
  10316. }
  10317. for (let i = 0; i < light.length; i++) {
  10318. let lightId = light[i];
  10319. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4001, lightId)));
  10320. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4002, lightId)));
  10321. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4003, lightId)));
  10322. }
  10323. let isFull = mode || i > 0;
  10324. for (let j = isFull ? i + 1 : 2; j < factors.length; j++) {
  10325. let extraId = factors[j].id;
  10326. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4000, extraId)));
  10327. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4001, extraId)));
  10328. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4002, extraId)));
  10329. }
  10330. }
  10331. if (aradgi) {
  10332. if (mode) {
  10333. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(4013)));
  10334. }
  10335. for (let i = 0; i < dark.length; i++) {
  10336. let darkId = dark[i];
  10337. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(darkId, 4001, 4013)));
  10338. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(darkId, 4002, 4013)));
  10339. }
  10340. for (let i = 0; i < light.length; i++) {
  10341. let lightId = light[i];
  10342. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(lightId, 4001, 4013)));
  10343. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(lightId, 4002, 4013)));
  10344. }
  10345. }
  10346. for (let i = 0; i < dark.length; i++) {
  10347. let firstId = dark[i];
  10348. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId)));
  10349. for (let j = i + 1; j < dark.length; j++) {
  10350. let secondId = dark[j];
  10351. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4001, secondId)));
  10352. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4002, secondId)));
  10353. }
  10354. }
  10355. for (let i = 0; i < light.length; i++) {
  10356. let firstId = light[i];
  10357. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId)));
  10358. for (let j = i + 1; j < light.length; j++) {
  10359. let secondId = light[j];
  10360. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4001, secondId)));
  10361. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4002, secondId)));
  10362. }
  10363. }
  10364. }
  10365. for (let result of await Promise.all(actions)) {
  10366. let recovery = getRecovery(result);
  10367. if (recovery > bestBattle.recovery) {
  10368. bestBattle.recovery = recovery;
  10369. bestBattle.attackers = result.progress[0].attackers.heroes;
  10370. }
  10371. }
  10372. }
  10373.  
  10374. /** Получаем нейтральную команду */
  10375. function getNeutralTeam(id, swapId, addId) {
  10376. let neutralTeam = clone(teams.water);
  10377. let neutral = neutralTeam.heroes;
  10378. if (neutral.length == 4) {
  10379. if (!!swapId) {
  10380. for (let i in neutral) {
  10381. if (neutral[i] == swapId) {
  10382. neutral[i] = addId;
  10383. }
  10384. }
  10385. }
  10386. } else if (!!addId) {
  10387. neutral.push(addId);
  10388. }
  10389. neutral.push(id);
  10390. return neutralTeam;
  10391. }
  10392.  
  10393. /** Получить команду титанов */
  10394. function getTeam(titans) {
  10395. return {
  10396. favor: {},
  10397. heroes: Object.keys(titans).map(id => parseInt(id)),
  10398. teamNum: 0,
  10399. };
  10400. }
  10401.  
  10402. /** Вычисляем фактор боеготовности титанов */
  10403. function calcFactor() {
  10404. let neutral = teams.neutral;
  10405. let factors = [];
  10406. for (let i in neutral) {
  10407. let titanId = neutral[i];
  10408. let titan = titansStates[titanId];
  10409. let factor = !!titan ? titan.hp / titan.maxHp + titan.energy / 10000.0 : 1;
  10410. if (factor > 0) {
  10411. factors.push({id: titanId, value: factor});
  10412. }
  10413. }
  10414. factors.sort(function(a, b) {
  10415. return a.value - b.value;
  10416. });
  10417. return factors;
  10418. }
  10419.  
  10420. /** Возвращает наилучший результат из нескольких боев */
  10421. async function getBestRecovery(teamNum, attackerType, team, countBattle) {
  10422. let bestRecovery = -1000;
  10423. let actions = [];
  10424. for (let i = 0; i < countBattle; i++) {
  10425. actions.push(startBattle(teamNum, attackerType, team));
  10426. }
  10427. for (let result of await Promise.all(actions)) {
  10428. let recovery = getRecovery(result);
  10429. if (recovery > bestRecovery) {
  10430. bestRecovery = recovery;
  10431. }
  10432. }
  10433. return bestRecovery;
  10434. }
  10435.  
  10436. /** Возвращает разницу в здоровье атакующей команды после и до битвы и проверяет здоровье титанов на необходимый минимум*/
  10437. function getRecovery(result) {
  10438. if (result.result.stars < 3) {
  10439. return -100;
  10440. }
  10441. let beforeSumFactor = 0;
  10442. let afterSumFactor = 0;
  10443. let beforeTitans = result.battleData.attackers;
  10444. let afterTitans = result.progress[0].attackers.heroes;
  10445. for (let i in afterTitans) {
  10446. let titan = afterTitans[i];
  10447. let percentHP = titan.hp / beforeTitans[i].hp;
  10448. let energy = titan.energy;
  10449. let factor = checkTitan(i, energy, percentHP) ? getFactor(i, energy, percentHP) : -100;
  10450. afterSumFactor += factor;
  10451. }
  10452. for (let i in beforeTitans) {
  10453. let titan = beforeTitans[i];
  10454. let state = titan.state;
  10455. beforeSumFactor += !!state ? getFactor(i, state.energy, state.hp / titan.hp) : 1;
  10456. }
  10457. return afterSumFactor - beforeSumFactor;
  10458. }
  10459.  
  10460. /** Возвращает состояние титана*/
  10461. function getFactor(id, energy, percentHP) {
  10462. let elemantId = id.slice(2, 3);
  10463. let isEarthOrFire = elemantId == '1' || elemantId == '2';
  10464. let energyBonus = id == '4020' && energy == 1000 ? 0.1 : energy / 20000.0;
  10465. let factor = percentHP + energyBonus;
  10466. return isEarthOrFire ? factor : factor / 10;
  10467. }
  10468.  
  10469. /** Проверяет состояние титана*/
  10470. function checkTitan(id, energy, percentHP) {
  10471. switch (id) {
  10472. case '4020':
  10473. return percentHP > 0.25 || (energy == 1000 && percentHP > 0.05);
  10474. break;
  10475. case '4010':
  10476. return percentHP + energy / 2000.0 > 0.63;
  10477. break;
  10478. case '4000':
  10479. return percentHP > 0.62 || (energy < 1000 && (
  10480. (percentHP > 0.45 && energy >= 400) ||
  10481. (percentHP > 0.3 && energy >= 670)));
  10482. }
  10483. return true;
  10484. }
  10485.  
  10486.  
  10487. /** Начинаем бой */
  10488. function startBattle(teamNum, attackerType, args) {
  10489. return new Promise(function (resolve, reject) {
  10490. args.teamNum = teamNum;
  10491. let startBattleCall = {
  10492. calls: [{
  10493. name: "dungeonStartBattle",
  10494. args,
  10495. ident: "body"
  10496. }]
  10497. }
  10498. send(JSON.stringify(startBattleCall), resultBattle, {
  10499. resolve,
  10500. teamNum,
  10501. attackerType
  10502. });
  10503. });
  10504. }
  10505.  
  10506. /** Возращает результат боя в промис */
  10507. /*function resultBattle(resultBattles, args) {
  10508. if (!!resultBattles && !!resultBattles.results) {
  10509. let battleData = resultBattles.results[0].result.response;
  10510. let battleType = "get_tower";
  10511. if (battleData.type == "dungeon_titan") {
  10512. battleType = "get_titan";
  10513. }
  10514. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];//тест подземка правки
  10515. BattleCalc(battleData, battleType, function (result) {
  10516. result.teamNum = args.teamNum;
  10517. result.attackerType = args.attackerType;
  10518. args.resolve(result);
  10519. });
  10520. } else {
  10521. endDungeon('Потеряна связь с сервером игры!', 'break');
  10522. }
  10523. }*/
  10524. function resultBattle(resultBattles, args) {
  10525. battleData = resultBattles.results[0].result.response;
  10526. battleType = "get_tower";
  10527. if (battleData.type == "dungeon_titan") {
  10528. battleType = "get_titan";
  10529. }
  10530. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  10531. BattleCalc(battleData, battleType, function (result) {
  10532. result.teamNum = args.teamNum;
  10533. result.attackerType = args.attackerType;
  10534. args.resolve(result);
  10535. });
  10536. }
  10537.  
  10538. /** Заканчиваем бой */
  10539.  
  10540. ////
  10541. async function endBattle(battleInfo) {
  10542. if (!!battleInfo) {
  10543. const args = {
  10544. result: battleInfo.result,
  10545. progress: battleInfo.progress,
  10546. }
  10547. if (battleInfo.result.stars < 3) {
  10548. endDungeon('Герой или Титан мог погибнуть в бою!', battleInfo);
  10549. return;
  10550. }
  10551. if (countPredictionCard > 0) {
  10552. args.isRaid = true;
  10553. } else {
  10554. const timer = getTimer(battleInfo.battleTime);
  10555. console.log(timer);
  10556. await countdownTimer(timer, `${I18N('DUNGEON2')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity}`);
  10557. }
  10558. const calls = [{
  10559. name: "dungeonEndBattle",
  10560. args,
  10561. ident: "body"
  10562. }];
  10563. lastDungeonBattleData = null;
  10564. send(JSON.stringify({ calls }), resultEndBattle);
  10565. } else {
  10566. endDungeon('dungeonEndBattle win: false\n', battleInfo);
  10567. }
  10568. }
  10569. /** Получаем и обрабатываем результаты боя */
  10570. function resultEndBattle(e) {
  10571. if (!!e && !!e.results) {
  10572. let battleResult = e.results[0].result.response;
  10573. if ('error' in battleResult) {
  10574. endDungeon('errorBattleResult', battleResult);
  10575. return;
  10576. }
  10577. let dungeonGetInfo = battleResult.dungeon ?? battleResult;
  10578. dungeonActivity += battleResult.reward.dungeonActivity ?? 0;
  10579. checkFloor(dungeonGetInfo);
  10580. } else {
  10581. endDungeon('Потеряна связь с сервером игры!', 'break');
  10582. }
  10583. }
  10584.  
  10585. /** Добавить команду титанов в общий список команд */
  10586. function addTeam(team) {
  10587. for (let i in countTeam) {
  10588. if (equalsTeam(countTeam[i].team, team)) {
  10589. countTeam[i].count++;
  10590. return;
  10591. }
  10592. }
  10593. countTeam.push({team: team, count: 1});
  10594. }
  10595.  
  10596. /** Сравнить команды на равенство */
  10597. function equalsTeam(team1, team2) {
  10598. if (team1.length == team2.length) {
  10599. for (let i in team1) {
  10600. if (team1[i] != team2[i]) {
  10601. return false;
  10602. }
  10603. }
  10604. return true;
  10605. }
  10606. return false;
  10607. }
  10608.  
  10609. function saveProgress() {
  10610. let saveProgressCall = {
  10611. calls: [{
  10612. name: "dungeonSaveProgress",
  10613. args: {},
  10614. ident: "body"
  10615. }]
  10616. }
  10617. send(JSON.stringify(saveProgressCall), resultEndBattle);
  10618. }
  10619.  
  10620.  
  10621. /** Выводит статистику прохождения подземелья */
  10622. function showStats() {
  10623. let activity = dungeonActivity - startDungeonActivity;
  10624. let workTime = clone(timeDungeon);
  10625. workTime.all = new Date().getTime() - workTime.all;
  10626. for (let i in workTime) {
  10627. workTime[i] = (workTime[i] / 1000).round(0);
  10628. }
  10629. countTeam.sort(function(a, b) {
  10630. return b.count - a.count;
  10631. });
  10632. console.log(titansStates);
  10633. console.log("Собрано титанита: ", activity);
  10634. console.log("Скорость сбора: " + (3600 * activity / workTime.all).round(0) + " титанита/час");
  10635. console.log("Время раскопок: ");
  10636. for (let i in workTime) {
  10637. let timeNow = workTime[i];
  10638. console.log(i + ": ", (timeNow / 3600).round(0) + " ч. " + (timeNow % 3600 / 60).round(0) + " мин. " + timeNow % 60 + " сек.");
  10639. }
  10640. console.log("Частота использования команд: ");
  10641. for (let i in countTeam) {
  10642. let teams = countTeam[i];
  10643. console.log(teams.team + ": ", teams.count);
  10644. }
  10645. }
  10646.  
  10647. /** Заканчиваем копать подземелье */
  10648. function endDungeon(reason, info) {
  10649. if (!end) {
  10650. end = true;
  10651. console.log(reason, info);
  10652. showStats();
  10653. if (info == 'break') {
  10654. setProgress('Dungeon stoped: Титанит ' + dungeonActivity + '/' + maxDungeonActivity +
  10655. "\r\nПотеряна связь с сервером игры!", false, hideProgress);
  10656. } else {
  10657. setProgress('Dungeon completed: Титанит ' + dungeonActivity + '/' + maxDungeonActivity, false, hideProgress);
  10658. }
  10659. setTimeout(cheats.refreshGame, 1000);
  10660. resolve();
  10661. }
  10662. }
  10663. }
  10664. })();
  10665.  
  10666. /**
  10667. * TODO:
  10668. * Получение всех уровней при сборе всех наград (квест на титанит и на энку)++
  10669. * Добавить проверку правильности пути для приключения
  10670. * Добивание на арене титанов
  10671. * Кнопку Турнир стихий красить в красный цвет если не дошел до 7 этапа
  10672. * Закрытие окошек по Esc
  10673. * Починить работу скрипта на уровне команды ниже 10++
  10674. * Автоматическое подключение библиотеки нужной версии
  10675. */