HeroWarsDungeon

Automation of actions for the game Hero Wars

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

  1. // ==UserScript==
  2. // @name HeroWarsDungeon
  3. // @name:en HeroWarsDungeon
  4. // @name:ru HeroWarsDungeon
  5. // @namespace HeroWarsDungeon
  6. // @version 2.247.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 https://zingery.ru/scripts/HeroWarsHelper.user.js
  13. // @icon http://ilovemycomp.narod.ru/VaultBoyIco16.ico
  14. // @icon64 http://ilovemycomp.narod.ru/VaultBoyIco64.png
  15. // @match https://www.hero-wars.com/*
  16. // @match https://apps-1701433570146040.apps.fbsbx.com/*
  17. // @run-at document-start
  18. // ==/UserScript==
  19.  
  20. // сделал ApuoH
  21. (function() {
  22. /**
  23. * Start script
  24. *
  25. * Стартуем скрипт
  26. */
  27. console.log('%cStart ' + GM_info.script.name + ', v' + GM_info.script.version, 'color: red');
  28. /**
  29. * Script info
  30. *
  31. * Информация о скрипте
  32. */
  33. const scriptInfo = (({name, version, author, homepage, lastModified}, updateUrl, source) =>
  34. ({name, version, author, homepage, lastModified, updateUrl, source}))
  35. (GM_info.script, GM_info.scriptUpdateURL, arguments.callee.toString());
  36. /**
  37. * Information for completing daily quests
  38. *
  39. * Информация для выполнения ежендевных квестов
  40. */
  41. const questsInfo = {};
  42. /**
  43. * Is the game data loaded
  44. *
  45. * Загружены ли данные игры
  46. */
  47. let isLoadGame = false;
  48. /**
  49. * Headers of the last request
  50. *
  51. * Заголовки последнего запроса
  52. */
  53. let lastHeaders = {};
  54. /**
  55. * Information about sent gifts
  56. *
  57. * Информация об отправленных подарках
  58. */
  59. let freebieCheckInfo = null;
  60. /**
  61. * missionTimer
  62. *
  63. * missionTimer
  64. */
  65. let missionBattle = null;
  66. /** Пачки для тестов в чате*/ //тест сохранка
  67. let repleyBattle = {
  68. defenders: {},
  69. attackers: {},
  70. effects: {},
  71. state: {},
  72. seed: undefined
  73. }
  74. /**
  75. * User data
  76. *
  77. * Данные пользователя
  78. */
  79. let userInfo;
  80. /**
  81. * Original methods for working with AJAX
  82. *
  83. * Оригинальные методы для работы с AJAX
  84. */
  85. const original = {
  86. open: XMLHttpRequest.prototype.open,
  87. send: XMLHttpRequest.prototype.send,
  88. setRequestHeader: XMLHttpRequest.prototype.setRequestHeader,
  89. SendWebSocket: WebSocket.prototype.send,
  90. };
  91. /**
  92. * Decoder for converting byte data to JSON string
  93. *
  94. * Декодер для перобразования байтовых данных в JSON строку
  95. */
  96. const decoder = new TextDecoder("utf-8");
  97. /**
  98. * Stores a history of requests
  99. *
  100. * Хранит историю запросов
  101. */
  102. let requestHistory = {};
  103. /**
  104. * URL for API requests
  105. *
  106. * URL для запросов к API
  107. */
  108. let apiUrl = '';
  109.  
  110. /**
  111. * Connecting to the game code
  112. *
  113. * Подключение к коду игры
  114. */
  115. this.cheats = new hackGame();
  116. /**
  117. * The function of calculating the results of the battle
  118. *
  119. * Функция расчета результатов боя
  120. */
  121. this.BattleCalc = cheats.BattleCalc;
  122. /**
  123. * Sending a request available through the console
  124. *
  125. * Отправка запроса доступная через консоль
  126. */
  127. this.SendRequest = send;
  128. /**
  129. * Simple combat calculation available through the console
  130. *
  131. * Простой расчет боя доступный через консоль
  132. */
  133. this.Calc = function (data) {
  134. const type = getBattleType(data?.type);
  135. return new Promise((resolve, reject) => {
  136. try {
  137. BattleCalc(data, type, resolve);
  138. } catch (e) {
  139. reject(e);
  140. }
  141. })
  142. }
  143. //тест остановка подземки
  144. let stopDung = false;
  145. /**
  146. * Short asynchronous request
  147. * Usage example (returns information about a character):
  148. * const userInfo = await Send('{"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}')
  149. *
  150. * Короткий асинхронный запрос
  151. * Пример использования (возвращает информацию о персонаже):
  152. * const userInfo = await Send('{"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}')
  153. */
  154. this.Send = function (json, pr) {
  155. return new Promise((resolve, reject) => {
  156. try {
  157. send(json, resolve, pr);
  158. } catch (e) {
  159. reject(e);
  160. }
  161. })
  162. }
  163.  
  164. this.xyz = (({ name, version, author }) => ({ name, version, author }))(GM_info.script);
  165. const i18nLangData = {
  166. /* English translation by BaBa */
  167. en: {
  168. /* Checkboxes */
  169. SKIP_FIGHTS: 'Skip battle',
  170. SKIP_FIGHTS_TITLE: 'Skip battle in Outland and the arena of the titans, auto-pass in the tower and campaign',
  171. ENDLESS_CARDS: 'Infinite cards',
  172. ENDLESS_CARDS_TITLE: 'Disable Divination Cards wasting',
  173. AUTO_EXPEDITION: 'Auto Expedition',
  174. AUTO_EXPEDITION_TITLE: 'Auto-sending expeditions',
  175. CANCEL_FIGHT: 'Cancel battle',
  176. CANCEL_FIGHT_TITLE: 'Ability to cancel manual combat on GW, CoW and Asgard',
  177. GIFTS: 'Gifts',
  178. GIFTS_TITLE: 'Collect gifts automatically',
  179. BATTLE_RECALCULATION: 'Battle recalculation',
  180. BATTLE_RECALCULATION_TITLE: 'Preliminary calculation of the battle',
  181. BATTLE_FISHING: 'Finishing',
  182. BATTLE_FISHING_TITLE: 'Finishing off the team from the last replay in the chat',
  183. BATTLE_TRENING: 'Workout',
  184. BATTLE_TRENING_TITLE: 'A training battle in the chat against the team from the last replay',
  185. QUANTITY_CONTROL: 'Quantity control',
  186. QUANTITY_CONTROL_TITLE: 'Ability to specify the number of opened "lootboxes"',
  187. REPEAT_CAMPAIGN: 'Repeat missions',
  188. REPEAT_CAMPAIGN_TITLE: 'Auto-repeat battles in the campaign',
  189. DISABLE_DONAT: 'Disable donation',
  190. DISABLE_DONAT_TITLE: 'Removes all donation offers',
  191. DAILY_QUESTS: 'Quests',
  192. DAILY_QUESTS_TITLE: 'Complete daily quests',
  193. AUTO_QUIZ: 'AutoQuiz',
  194. AUTO_QUIZ_TITLE: 'Automatically receive correct answers to quiz questions',
  195. SECRET_WEALTH_CHECKBOX: 'Automatic purchase in the store "Secret Wealth" when entering the game',
  196. HIDE_SERVERS: 'Collapse servers',
  197. HIDE_SERVERS_TITLE: 'Hide unused servers',
  198. /* Input fields */
  199. HOW_MUCH_TITANITE: 'How much titanite to farm',
  200. COMBAT_SPEED: 'Combat Speed Multiplier',
  201. HOW_REPEAT_CAMPAIGN: 'how many mission replays', //тест добавил
  202. NUMBER_OF_TEST: 'Number of test fights',
  203. NUMBER_OF_AUTO_BATTLE: 'Number of auto-battle attempts',
  204. USER_ID_TITLE: 'Enter the player ID',
  205. AMOUNT: 'Gift number, 1 - hero development, 2 - pets, 3 - light, 4 - darkness, 5 - ascension, 6 - appearance',
  206. GIFT_NUM: 'Number of gifts to be sent',
  207. /* Buttons */
  208. RUN_SCRIPT: 'Run the',
  209. STOP_SCRIPT: 'Stop the',
  210. TO_DO_EVERYTHING: 'Do All',
  211. TO_DO_EVERYTHING_TITLE: 'Perform multiple actions of your choice',
  212. OUTLAND: 'Outland',
  213. OUTLAND_TITLE: 'Collect Outland',
  214. TITAN_ARENA: 'ToE',
  215. TITAN_ARENA_TITLE: 'Complete the titan arena',
  216. DUNGEON: 'Dungeon',
  217. DUNGEON_TITLE: 'Go through the dungeon',
  218. DUNGEON2: 'Dungeon full',
  219. DUNGEON_FULL_TITLE: 'Dungeon for Full Titans',
  220. STOP_DUNGEON: 'Stop Dungeon',
  221. STOP_DUNGEON_TITLE: 'Stop digging the dungeon',
  222. SEER: 'Seer',
  223. SEER_TITLE: 'Roll the Seer',
  224. TOWER: 'Tower',
  225. TOWER_TITLE: 'Pass the tower',
  226. EXPEDITIONS: 'Expeditions',
  227. EXPEDITIONS_TITLE: 'Sending and collecting expeditions',
  228. SYNC: 'Sync',
  229. SYNC_TITLE: 'Partial synchronization of game data without reloading the page',
  230. ARCHDEMON: 'Archdemon',
  231. ARCHDEMON_TITLE: 'Hitting kills and collecting rewards',
  232. CRUCIBLE_SOULS: 'Crucible',
  233. CRUCIBLE_SOULS_TITLE: 'Fill the kilos in the crucible of souls',
  234. ESTER_EGGS: 'Easter eggs',
  235. ESTER_EGGS_TITLE: 'Collect all Easter eggs or rewards',
  236. REWARDS: 'Rewards',
  237. REWARDS_TITLE: 'Collect all quest rewards',
  238. MAIL: 'Mail',
  239. MAIL_TITLE: 'Collect all mail, except letters with energy and charges of the portal',
  240. MINIONS: 'Minions',
  241. MINIONS_TITLE: 'Attack minions with saved packs',
  242. ADVENTURE: 'Adventure',
  243. ADVENTURE_TITLE: 'Passes the adventure along the specified route',
  244. STORM: 'Storm',
  245. STORM_TITLE: 'Passes the Storm along the specified route',
  246. SANCTUARY: 'Sanctuary',
  247. SANCTUARY_TITLE: 'Fast travel to Sanctuary',
  248. GUILD_WAR: 'Guild War',
  249. GUILD_WAR_TITLE: 'Fast travel to Guild War',
  250. SECRET_WEALTH: 'Secret Wealth',
  251. SECRET_WEALTH_TITLE: 'Buy something in the store "Secret Wealth"',
  252. /* Misc */
  253. BOTTOM_URLS: '<a href="https://t.me/+0oMwICyV1aQ1MDAy" target="_blank" title="Telegram"><svg width="20" height="20" style="margin:2px" viewBox="0 0 1e3 1e3" xmlns="http://www.w3.org/2000/svg"><defs><linearGradient id="a" x1="50%" x2="50%" y2="99.258%"><stop stop-color="#2AABEE" offset="0"/><stop stop-color="#229ED9" offset="1"/></linearGradient></defs><g fill-rule="evenodd"><circle cx="500" cy="500" r="500" fill="url(#a)"/><path d="m226.33 494.72c145.76-63.505 242.96-105.37 291.59-125.6 138.86-57.755 167.71-67.787 186.51-68.119 4.1362-0.072862 13.384 0.95221 19.375 5.8132 5.0584 4.1045 6.4501 9.6491 7.1161 13.541 0.666 3.8915 1.4953 12.756 0.83608 19.683-7.5246 79.062-40.084 270.92-56.648 359.47-7.0089 37.469-20.81 50.032-34.17 51.262-29.036 2.6719-51.085-19.189-79.207-37.624-44.007-28.847-68.867-46.804-111.58-74.953-49.366-32.531-17.364-50.411 10.769-79.631 7.3626-7.6471 135.3-124.01 137.77-134.57 0.30968-1.3202 0.59708-6.2414-2.3265-8.8399s-7.2385-1.7099-10.352-1.0032c-4.4137 1.0017-74.715 47.468-210.9 139.4-19.955 13.702-38.029 20.379-54.223 20.029-17.853-0.3857-52.194-10.094-77.723-18.393-31.313-10.178-56.199-15.56-54.032-32.846 1.1287-9.0037 13.528-18.212 37.197-27.624z" fill="#fff"/></g></svg></a>',
  254. GIFTS_SENT: 'Gifts sent!',
  255. DO_YOU_WANT: 'Do you really want to do this?',
  256. BTN_RUN: 'Run',
  257. BTN_CANCEL: 'Cancel',
  258. BTN_OK: 'OK',
  259. MSG_HAVE_BEEN_DEFEATED: 'You have been defeated!',
  260. BTN_AUTO: 'Auto',
  261. MSG_YOU_APPLIED: 'You applied',
  262. MSG_DAMAGE: 'damage',
  263. MSG_CANCEL_AND_STAT: 'Auto (F5) and show statistic',
  264. MSG_REPEAT_MISSION: 'Repeat the mission?',
  265. BTN_REPEAT: 'Repeat',
  266. BTN_NO: 'No',
  267. MSG_SPECIFY_QUANT: 'Specify Quantity:',
  268. BTN_OPEN: 'Open',
  269. QUESTION_COPY: 'Question copied to clipboard',
  270. ANSWER_KNOWN: 'The answer is known',
  271. ANSWER_NOT_KNOWN: 'ATTENTION THE ANSWER IS NOT KNOWN',
  272. BEING_RECALC: 'The battle is being recalculated',
  273. THIS_TIME: 'This time',
  274. VICTORY: '<span style="color:green;">VICTORY</span>',
  275. DEFEAT: '<span style="color:red;">DEFEAT</span>',
  276. CHANCE_TO_WIN: 'Chance to win <span style="color: red;">based on pre-calculation</span>',
  277. OPEN_DOLLS: 'nesting dolls recursively',
  278. SENT_QUESTION: 'Question sent',
  279. SETTINGS: 'Settings',
  280. MSG_BAN_ATTENTION: '<p style="color:red;">Using this feature may result in a ban.</p> Continue?',
  281. BTN_YES_I_AGREE: 'Yes, I understand the risks!',
  282. BTN_NO_I_AM_AGAINST: 'No, I refuse it!',
  283. VALUES: 'Values',
  284. SAVING: 'Saving',
  285. USER_ID: 'User Id',
  286. SEND_GIFT: 'The gift has been sent',
  287. EXPEDITIONS_SENT: 'Expeditions sent',
  288. TITANIT: 'Titanit',
  289. COMPLETED: 'completed',
  290. FLOOR: 'Floor',
  291. LEVEL: 'Level',
  292. BATTLES: 'battles',
  293. EVENT: 'Event',
  294. NOT_AVAILABLE: 'not available',
  295. NO_HEROES: 'No heroes',
  296. DAMAGE_AMOUNT: 'Damage amount',
  297. NOTHING_TO_COLLECT: 'Nothing to collect',
  298. COLLECTED: 'Collected',
  299. REWARD: 'rewards',
  300. REMAINING_ATTEMPTS: 'Remaining attempts',
  301. BATTLES_CANCELED: 'Battles canceled',
  302. MINION_RAID: 'Minion Raid',
  303. STOPPED: 'Stopped',
  304. REPETITIONS: 'Repetitions',
  305. MISSIONS_PASSED: 'Missions passed',
  306. STOP: 'stop',
  307. TOTAL_OPEN: 'Total open',
  308. OPEN: 'Open',
  309. ROUND_STAT: 'Damage statistics for ',
  310. BATTLE: 'battles',
  311. MINIMUM: 'Minimum',
  312. MAXIMUM: 'Maximum',
  313. AVERAGE: 'Average',
  314. NOT_THIS_TIME: 'Not this time',
  315. RETRY_LIMIT_EXCEEDED: 'Retry limit exceeded',
  316. SUCCESS: 'Success',
  317. RECEIVED: 'Received',
  318. LETTERS: 'letters',
  319. PORTALS: 'portals',
  320. ATTEMPTS: 'attempts',
  321. /* Quests */
  322. QUEST_10001: 'Upgrade the skills of heroes 3 times',
  323. QUEST_10002: 'Complete 10 missions',
  324. QUEST_10003: 'Complete 3 heroic missions',
  325. QUEST_10004: 'Fight 3 times in the Arena or Grand Arena',
  326. QUEST_10006: 'Use the exchange of emeralds 1 time',
  327. QUEST_10007: 'Perform 1 summon in the Solu Atrium',
  328. QUEST_10016: 'Send gifts to guildmates',
  329. QUEST_10018: 'Use an experience potion',
  330. QUEST_10019: 'Open 1 chest in the Tower',
  331. QUEST_10020: 'Open 3 chests in Outland',
  332. QUEST_10021: 'Collect 75 Titanite in the Guild Dungeon',
  333. QUEST_10021: 'Collect 150 Titanite in the Guild Dungeon',
  334. QUEST_10023: 'Upgrade Gift of the Elements by 1 level',
  335. QUEST_10024: 'Level up any artifact once',
  336. QUEST_10025: 'Start Expedition 1',
  337. QUEST_10026: 'Start 4 Expeditions',
  338. QUEST_10027: 'Win 1 battle of the Tournament of Elements',
  339. QUEST_10028: 'Level up any titan artifact',
  340. QUEST_10029: 'Unlock the Orb of Titan Artifacts',
  341. QUEST_10030: 'Upgrade any Skin of any hero 1 time',
  342. QUEST_10031: 'Win 6 battles of the Tournament of Elements',
  343. QUEST_10043: 'Start or Join an Adventure',
  344. QUEST_10044: 'Use Summon Pets 1 time',
  345. QUEST_10046: 'Open 3 chests in Adventure',
  346. QUEST_10047: 'Get 150 Guild Activity Points',
  347. NOTHING_TO_DO: 'Nothing to do',
  348. YOU_CAN_COMPLETE: 'You can complete quests',
  349. BTN_DO_IT: 'Do it',
  350. NOT_QUEST_COMPLETED: 'Not a single quest completed',
  351. COMPLETED_QUESTS: 'Completed quests',
  352. /* everything button */
  353. ASSEMBLE_OUTLAND: 'Assemble Outland',
  354. PASS_THE_TOWER: 'Pass the tower',
  355. CHECK_EXPEDITIONS: 'Check Expeditions',
  356. COMPLETE_TOE: 'Complete ToE',
  357. COMPLETE_DUNGEON: 'Complete the dungeon',
  358. COMPLETE_DUNGEON_FULL: 'Complete the dungeon for Full Titans',
  359. COLLECT_MAIL: 'Collect mail',
  360. COLLECT_MISC: 'Collect some bullshit',
  361. COLLECT_MISC_TITLE: 'Collect Easter Eggs, Skin Gems, Keys, Arena Coins and Soul Crystal',
  362. COLLECT_QUEST_REWARDS: 'Collect quest rewards',
  363. MAKE_A_SYNC: 'Make a sync',
  364.  
  365. RUN_FUNCTION: 'Run the following functions?',
  366. BTN_GO: 'Go!',
  367. PERFORMED: 'Performed',
  368. DONE: 'Done',
  369. ERRORS_OCCURRES: 'Errors occurred while executing',
  370. COPY_ERROR: 'Copy error information to clipboard',
  371. BTN_YES: 'Yes',
  372. ALL_TASK_COMPLETED: 'All tasks completed',
  373.  
  374. UNKNOWN: 'unknown',
  375. ENTER_THE_PATH: 'Enter the path of adventure using commas or dashes',
  376. START_ADVENTURE: 'Start your adventure along this path!',
  377. INCORRECT_WAY: 'Incorrect path in adventure: {from} -> {to}',
  378. BTN_CANCELED: 'Canceled',
  379. MUST_TWO_POINTS: 'The path must contain at least 2 points.',
  380. MUST_ONLY_NUMBERS: 'The path must contain only numbers and commas',
  381. NOT_ON_AN_ADVENTURE: 'You are not on an adventure',
  382. YOU_IN_NOT_ON_THE_WAY: 'Your location is not on the way',
  383. ATTEMPTS_NOT_ENOUGH: 'Your attempts are not enough to complete the path, continue?',
  384. YES_CONTINUE: 'Yes, continue!',
  385. NOT_ENOUGH_AP: 'Not enough action points',
  386. ATTEMPTS_ARE_OVER: 'The attempts are over',
  387. MOVES: 'Moves',
  388. BUFF_GET_ERROR: 'Buff getting error',
  389. BATTLE_END_ERROR: 'Battle end error',
  390. AUTOBOT: 'Autobot',
  391. FAILED_TO_WIN_AUTO: 'Failed to win the auto battle',
  392. ERROR_OF_THE_BATTLE_COPY: 'An error occurred during the passage of the battle<br>Copy the error to the clipboard?',
  393. ERROR_DURING_THE_BATTLE: 'Error during the battle',
  394. NO_CHANCE_WIN: 'No chance of winning this fight: 0/',
  395. LOST_HEROES: 'You have won, but you have lost one or several heroes',
  396. VICTORY_IMPOSSIBLE: 'Is victory impossible, should we focus on the result?',
  397. FIND_COEFF: 'Find the coefficient greater than',
  398. BTN_PASS: 'PASS',
  399. BRAWLS: 'Brawls',
  400. BRAWLS_TITLE: 'Activates the ability to auto-brawl',
  401. START_AUTO_BRAWLS: 'Start Auto Brawls?',
  402. LOSSES: 'Losses',
  403. WINS: 'Wins',
  404. FIGHTS: 'Fights',
  405. STAGE: 'Stage',
  406. DONT_HAVE_LIVES: "You don't have lives",
  407. LIVES: 'Lives',
  408. SECRET_WEALTH_ALREADY: 'Item for Pet Potions already purchased',
  409. SECRET_WEALTH_NOT_ENOUGH: 'Not Enough Pet Potion, You Have {available}, Need {need}',
  410. SECRET_WEALTH_UPGRADE_NEW_PET: 'After purchasing the Pet Potion, it will not be enough to upgrade a new pet',
  411. SECRET_WEALTH_PURCHASED: 'Purchased {count} {name}',
  412. SECRET_WEALTH_CANCELED: 'Secret Wealth: Purchase Canceled',
  413. SECRET_WEALTH_BUY: 'You have {available} Pet Potion.<br>Do you want to buy {countBuy} {name} for {price} Pet Potion?',
  414. DAILY_BONUS: 'Daily bonus',
  415. DO_DAILY_QUESTS: 'Do daily quests',
  416. ACTIONS: 'Actions',
  417. ACTIONS_TITLE: 'Dialog box with various actions',
  418. OTHERS: 'Others',
  419. OTHERS_TITLE: 'Others',
  420. CHOOSE_ACTION: 'Choose an action',
  421. OPEN_LOOTBOX: 'You have {lootBox} boxes, should we open them?',
  422. STAMINA: 'Energy',
  423. BOXES_OVER: 'The boxes are over',
  424. NO_BOXES: 'No boxes',
  425. NO_MORE_ACTIVITY: 'No more activity for items today',
  426. EXCHANGE_ITEMS: 'Exchange items for activity points (max {maxActive})?',
  427. GET_ACTIVITY: 'Get Activity',
  428. NOT_ENOUGH_ITEMS: 'Not enough items',
  429. ACTIVITY_RECEIVED: 'Activity received',
  430. NO_PURCHASABLE_HERO_SOULS: 'No purchasable Hero Souls',
  431. PURCHASED_HERO_SOULS: 'Purchased {countHeroSouls} Hero Souls',
  432. NOT_ENOUGH_EMERALDS_540: 'Not enough emeralds, you need 540 you have {currentStarMoney}',
  433. CHESTS_NOT_AVAILABLE: 'Chests not available',
  434. OUTLAND_CHESTS_RECEIVED: 'Outland chests received',
  435. RAID_NOT_AVAILABLE: 'The raid is not available or there are no spheres',
  436. RAID_ADVENTURE: 'Raid {adventureId} adventure!',
  437. SOMETHING_WENT_WRONG: 'Something went wrong',
  438. ADVENTURE_COMPLETED: 'Adventure {adventureId} completed {times} times',
  439. CLAN_STAT_COPY: 'Clan statistics copied to clipboard',
  440. GET_ENERGY: 'Get Energy',
  441. GET_ENERGY_TITLE: 'Opens platinum boxes one at a time until you get 250 energy',
  442. ITEM_EXCHANGE: 'Item Exchange',
  443. ITEM_EXCHANGE_TITLE: 'Exchanges items for the specified amount of activity',
  444. BUY_SOULS: 'Buy souls',
  445. BUY_SOULS_TITLE: 'Buy hero souls from all available shops',
  446. BUY_OUTLAND: 'Buy Outland',
  447. BUY_OUTLAND_TITLE: 'Buy 9 chests in Outland for 540 emeralds',
  448. RAID: 'Raid',
  449. AUTO_RAID_ADVENTURE: 'Raid adventure',
  450. AUTO_RAID_ADVENTURE_TITLE: 'Raid adventure set number of times',
  451. CLAN_STAT: 'Clan statistics',
  452. CLAN_STAT_TITLE: 'Copies clan statistics to the clipboard',
  453. BTN_AUTO_F5: 'Auto (F5)',
  454. BOSS_DAMAGE: 'Boss Damage: ',
  455. NOTHING_BUY: 'Nothing to buy',
  456. LOTS_BOUGHT: '{countBuy} lots bought for gold',
  457. BUY_FOR_GOLD: 'Buy for gold',
  458. BUY_FOR_GOLD_TITLE: 'Buy items for gold in the Town Shop and in the Pet Soul Stone Shop',
  459. REWARDS_AND_MAIL: 'Rewars and Mail',
  460. REWARDS_AND_MAIL_TITLE: 'Collects rewards and mail',
  461. New_Year_Clan: 'a gift for a friend',
  462. New_Year_Clan_TITLE: 'New Year gifts to friends',
  463. COLLECT_REWARDS_AND_MAIL: 'Collected {countQuests} rewards and {countMail} letters',
  464. TIMER_ALREADY: 'Timer already started {time}',
  465. NO_ATTEMPTS_TIMER_START: 'No attempts, timer started {time}',
  466. EPIC_BRAWL_RESULT: 'Wins: {wins}/{attempts}, Coins: {coins}, Streak: {progress}/{nextStage} [Close]{end}',
  467. ATTEMPT_ENDED: '<br>Attempts ended, timer started {time}',
  468. EPIC_BRAWL: 'Cosmic Battle',
  469. EPIC_BRAWL_TITLE: 'Spends attempts in the Cosmic Battle',
  470. RELOAD_GAME: 'Reload game',
  471. TIMER: 'Timer:',
  472. SHOW_ERRORS: 'Show errors',
  473. SHOW_ERRORS_TITLE: 'Show server request errors',
  474. ERROR_MSG: 'Error: {name}<br>{description}',
  475. EVENT_AUTO_BOSS: 'Maximum number of battles for calculation:</br>{length} ∗ {countTestBattle} = {maxCalcBattle}</br>If you have a weak computer, it may take a long time for this, click on the cross to cancel.</br>Should I search for the best pack from all or the first suitable one?',
  476. BEST_SLOW: 'Best (slower)',
  477. FIRST_FAST: 'First (faster)',
  478. FREEZE_INTERFACE: 'Calculating... <br>The interface may freeze.',
  479. ERROR_F12: 'Error, details in the console (F12)',
  480. FAILED_FIND_WIN_PACK: 'Failed to find a winning pack',
  481. BEST_PACK: 'Best pack:',
  482. BOSS_HAS_BEEN_DEF: 'Boss {bossLvl} has been defeated.',
  483. NOT_ENOUGH_ATTEMPTS_BOSS: 'Not enough attempts to defeat boss {bossLvl}, retry?',
  484. BOSS_VICTORY_IMPOSSIBLE: 'Based on the recalculation of {battles} battles, victory has not been achieved. Would you like to continue the search for a winning battle in real battles?',
  485. BOSS_HAS_BEEN_DEF_TEXT: 'Boss {bossLvl} defeated in<br>{countBattle}/{countMaxBattle} attempts<br>(Please synchronize or restart the game to update the data)',
  486. MAP: 'Map: ',
  487. PLAYER_POS: 'Player positions:',
  488. NY_GIFTS: 'Gifts',
  489. NY_GIFTS_TITLE: "Open all New Year's gifts",
  490. NY_NO_GIFTS: 'No gifts not received',
  491. NY_GIFTS_COLLECTED: '{count} gifts collected',
  492. CHANGE_MAP: 'Island map',
  493. CHANGE_MAP_TITLE: 'Change island map',
  494. SELECT_ISLAND_MAP: 'Select an island map:',
  495. FIRST_MAP: 'First map',
  496. SECOND_MAP: 'Second map',
  497. THIRD_MAP: 'Third card',
  498. SECRET_WEALTH_SHOP: 'Secret Wealth {name}: ',
  499. SHOPS: 'Shops',
  500. SHOPS_DEFAULT: 'Default',
  501. SHOPS_DEFAULT_TITLE: 'Default stores',
  502. SHOPS_LIST: 'Shops {number}',
  503. SHOPS_LIST_TITLE: 'List of shops {number}',
  504. SHOPS_WARNING: 'Stores<br><span style="color:red">If you buy brawl store coins for emeralds, you must use them immediately, otherwise they will disappear after restarting the game!</span>',
  505. MINIONS_WARNING: 'The hero packs for attacking minions are incomplete, should I continue?',
  506. FAST_SEASON: 'Fast season',
  507. FAST_SEASON_TITLE: 'Skip the map selection screen in a season',
  508. SET_NUMBER_LEVELS: 'Specify the number of levels:',
  509. POSSIBLE_IMPROVE_LEVELS: 'It is possible to improve only {count} levels.<br>Improving?',
  510. NOT_ENOUGH_RESOURECES: 'Not enough resources',
  511. IMPROVED_LEVELS: 'Improved levels: {count}',
  512. ARTIFACTS_UPGRADE: 'Artifacts Upgrade',
  513. ARTIFACTS_UPGRADE_TITLE: 'Upgrades the specified amount of the cheapest hero artifacts',
  514. SKINS_UPGRADE: 'Skins Upgrade',
  515. SKINS_UPGRADE_TITLE: 'Upgrades the specified amount of the cheapest hero skins',
  516. HINT: '<br>Hint: ',
  517. PICTURE: '<br>Picture: ',
  518. ANSWER: '<br>Answer: ',
  519. NO_HEROES_PACK: 'Fight at least one battle to save the attacking team',
  520. },
  521. ru: {
  522. /* Чекбоксы */
  523. SKIP_FIGHTS: 'Пропуск боев',
  524. SKIP_FIGHTS_TITLE: 'Пропуск боев в запределье и арене титанов, автопропуск в башне и кампании',
  525. ENDLESS_CARDS: 'Бесконечные карты',
  526. ENDLESS_CARDS_TITLE: 'Отключить трату карт предсказаний',
  527. AUTO_EXPEDITION: 'АвтоЭкспедиции',
  528. AUTO_EXPEDITION_TITLE: 'Автоотправка экспедиций',
  529. CANCEL_FIGHT: 'Отмена боя',
  530. CANCEL_FIGHT_TITLE: 'Возможность отмены ручного боя на ВГ, СМ и в Асгарде',
  531. GIFTS: 'Подарки',
  532. GIFTS_TITLE: 'Собирать подарки автоматически',
  533. BATTLE_RECALCULATION: 'Прерасчет боя',
  534. BATTLE_RECALCULATION_TITLE: 'Предварительный расчет боя',
  535. BATTLE_FISHING: 'Добивание',
  536. BATTLE_FISHING_TITLE: 'Добивание в чате команды из последнего реплея',
  537. BATTLE_TRENING: 'Тренировка',
  538. BATTLE_TRENING_TITLE: 'Тренировочный бой в чате против команды из последнего реплея',
  539. QUANTITY_CONTROL: 'Контроль кол-ва',
  540. QUANTITY_CONTROL_TITLE: 'Возможность указывать количество открываемых "лутбоксов"',
  541. REPEAT_CAMPAIGN: 'Повтор в компании',
  542. REPEAT_CAMPAIGN_TITLE: 'Автоповтор боев в кампании',
  543. DISABLE_DONAT: 'Отключить донат',
  544. DISABLE_DONAT_TITLE: 'Убирает все предложения доната',
  545. DAILY_QUESTS: 'Квесты',
  546. DAILY_QUESTS_TITLE: 'Выполнять ежедневные квесты',
  547. AUTO_QUIZ: 'АвтоВикторина',
  548. AUTO_QUIZ_TITLE: 'Автоматическое получение правильных ответов на вопросы викторины',
  549. SECRET_WEALTH_CHECKBOX: 'Автоматическая покупка в магазине "Тайное Богатство" при заходе в игру',
  550. HIDE_SERVERS: 'Свернуть сервера',
  551. HIDE_SERVERS_TITLE: 'Скрывать неиспользуемые сервера',
  552. /* Поля ввода */
  553. HOW_MUCH_TITANITE: 'Сколько фармим титанита',
  554. COMBAT_SPEED: 'Множитель ускорения боя',
  555. HOW_REPEAT_CAMPAIGN: 'Сколько повторов миссий', //тест добавил
  556. NUMBER_OF_TEST: 'Количество тестовых боев',
  557. NUMBER_OF_AUTO_BATTLE: 'Количество попыток автобоев',
  558. USER_ID_TITLE: 'Введите айди игрока',
  559. AMOUNT: 'Количество отправляемых подарков',
  560. GIFT_NUM: 'Номер подарка, 1 - развитие героев, 2 - питомцы, 3 - света, 4 - тьмы, 5 - вознесения, 6 - облик',
  561. /* Кнопки */
  562. RUN_SCRIPT: 'Запустить скрипт',
  563. STOP_SCRIPT: 'Остановить скрипт',
  564. TO_DO_EVERYTHING: 'Сделать все',
  565. TO_DO_EVERYTHING_TITLE: 'Выполнить несколько действий',
  566. OUTLAND: 'Запределье',
  567. OUTLAND_TITLE: 'Собрать Запределье',
  568. TITAN_ARENA: 'Турнир Стихий',
  569. TITAN_ARENA_TITLE: 'Автопрохождение Турнира Стихий',
  570. DUNGEON: 'Подземелье',
  571. DUNGEON_TITLE: 'Автопрохождение подземелья',
  572. DUNGEON2: 'Подземелье фулл',
  573. DUNGEON_FULL_TITLE: 'Подземелье для фуловых титанов',
  574. STOP_DUNGEON: 'Стоп подземка',
  575. STOP_DUNGEON_TITLE: 'Остановить копание подземелья',
  576. SEER: 'Провидец',
  577. SEER_TITLE: 'Покрутить Провидца',
  578. TOWER: 'Башня',
  579. TOWER_TITLE: 'Автопрохождение башни',
  580. EXPEDITIONS: 'Экспедиции',
  581. EXPEDITIONS_TITLE: 'Отправка и сбор экспедиций',
  582. SYNC: 'Синхронизация',
  583. SYNC_TITLE: 'Частичная синхронизация данных игры без перезагрузки сатраницы',
  584. ARCHDEMON: 'Архидемон',
  585. ARCHDEMON_TITLE: 'Набивает килы и собирает награду',
  586. CRUCIBLE_SOULS: 'Горнило душ',
  587. CRUCIBLE_SOULS_TITLE:'Набить килов в горниле душ',
  588. ESTER_EGGS: 'Пасхалки',
  589. ESTER_EGGS_TITLE: 'Собрать все пасхалки или награды',
  590. REWARDS: 'Награды',
  591. REWARDS_TITLE: 'Собрать все награды за задания',
  592. MAIL: 'Почта',
  593. MAIL_TITLE: 'Собрать всю почту, кроме писем с энергией и зарядами портала',
  594. MINIONS: 'Прислужники',
  595. MINIONS_TITLE: 'Атакует прислужников сохраннеными пачками',
  596. ADVENTURE: 'Приключение',
  597. ADVENTURE_TITLE: 'Проходит приключение по указанному маршруту',
  598. STORM: 'Буря',
  599. STORM_TITLE: 'Проходит бурю по указанному маршруту',
  600. SANCTUARY: 'Святилище',
  601. SANCTUARY_TITLE: 'Быстрый переход к Святилищу',
  602. GUILD_WAR: 'Война гильдий',
  603. GUILD_WAR_TITLE: 'Быстрый переход к Войне гильдий',
  604. SECRET_WEALTH: 'Тайное богатство',
  605. SECRET_WEALTH_TITLE: 'Купить что-то в магазине "Тайное богатство"',
  606. /* Разное */
  607. BOTTOM_URLS: '<a href="https://t.me/+q6gAGCRpwyFkNTYy" target="_blank" title="Telegram"><svg width="20" height="20" style="margin:2px" viewBox="0 0 1e3 1e3" xmlns="http://www.w3.org/2000/svg"><defs><linearGradient id="a" x1="50%" x2="50%" y2="99.258%"><stop stop-color="#2AABEE" offset="0"/><stop stop-color="#229ED9" offset="1"/></linearGradient></defs><g fill-rule="evenodd"><circle cx="500" cy="500" r="500" fill="url(#a)"/><path d="m226.33 494.72c145.76-63.505 242.96-105.37 291.59-125.6 138.86-57.755 167.71-67.787 186.51-68.119 4.1362-0.072862 13.384 0.95221 19.375 5.8132 5.0584 4.1045 6.4501 9.6491 7.1161 13.541 0.666 3.8915 1.4953 12.756 0.83608 19.683-7.5246 79.062-40.084 270.92-56.648 359.47-7.0089 37.469-20.81 50.032-34.17 51.262-29.036 2.6719-51.085-19.189-79.207-37.624-44.007-28.847-68.867-46.804-111.58-74.953-49.366-32.531-17.364-50.411 10.769-79.631 7.3626-7.6471 135.3-124.01 137.77-134.57 0.30968-1.3202 0.59708-6.2414-2.3265-8.8399s-7.2385-1.7099-10.352-1.0032c-4.4137 1.0017-74.715 47.468-210.9 139.4-19.955 13.702-38.029 20.379-54.223 20.029-17.853-0.3857-52.194-10.094-77.723-18.393-31.313-10.178-56.199-15.56-54.032-32.846 1.1287-9.0037 13.528-18.212 37.197-27.624z" fill="#fff"/></g></svg></a><a href="https://vk.com/invite/YNPxKGX" target="_blank" title="Вконтакте"><svg width="20" height="20" style="margin:2px" viewBox="0 0 101 100" xmlns="http://www.w3.org/2000/svg"><g clip-path="url(#a)"><path d="M0.5 48C0.5 25.3726 0.5 14.0589 7.52944 7.02944C14.5589 0 25.8726 0 48.5 0H52.5C75.1274 0 86.4411 0 93.4706 7.02944C100.5 14.0589 100.5 25.3726 100.5 48V52C100.5 74.6274 100.5 85.9411 93.4706 92.9706C86.4411 100 75.1274 100 52.5 100H48.5C25.8726 100 14.5589 100 7.52944 92.9706C0.5 85.9411 0.5 74.6274 0.5 52V48Z" fill="#07f"/><path d="m53.708 72.042c-22.792 0-35.792-15.625-36.333-41.625h11.417c0.375 19.083 8.7915 27.167 15.458 28.833v-28.833h10.75v16.458c6.5833-0.7083 13.499-8.2082 15.832-16.458h10.75c-1.7917 10.167-9.2917 17.667-14.625 20.75 5.3333 2.5 13.875 9.0417 17.125 20.875h-11.834c-2.5417-7.9167-8.8745-14.042-17.25-14.875v14.875h-1.2919z" fill="#fff"/></g><defs><clipPath id="a"><rect transform="translate(.5)" width="100" height="100" fill="#fff"/></clipPath></defs></svg></a>',
  608. GIFTS_SENT: 'Подарки отправлены!',
  609. DO_YOU_WANT: 'Вы действительно хотите это сделать?',
  610. BTN_RUN: 'Запускай',
  611. BTN_CANCEL: 'Отмена',
  612. BTN_OK: 'Ок',
  613. MSG_HAVE_BEEN_DEFEATED: 'Вы потерпели поражение!',
  614. BTN_AUTO: 'Авто',
  615. MSG_YOU_APPLIED: 'Вы нанесли',
  616. MSG_DAMAGE: 'урона',
  617. MSG_CANCEL_AND_STAT: 'Авто (F5) и показать Статистику',
  618. MSG_REPEAT_MISSION: 'Повторить миссию?',
  619. BTN_REPEAT: 'Повторить',
  620. BTN_NO: 'Нет',
  621. MSG_SPECIFY_QUANT: 'Указать количество:',
  622. BTN_OPEN: 'Открыть',
  623. QUESTION_COPY: 'Вопрос скопирован в буфер обмена',
  624. ANSWER_KNOWN: 'Ответ известен',
  625. ANSWER_NOT_KNOWN: 'ВНИМАНИЕ ОТВЕТ НЕ ИЗВЕСТЕН',
  626. BEING_RECALC: 'Идет прерасчет боя',
  627. THIS_TIME: 'На этот раз',
  628. VICTORY: '<span style="color:green;">ПОБЕДА</span>',
  629. DEFEAT: '<span style="color:red;">ПОРАЖЕНИЕ</span>',
  630. CHANCE_TO_WIN: 'Шансы на победу <span style="color:red;">на основе прерасчета</span>',
  631. OPEN_DOLLS: 'матрешек рекурсивно',
  632. SENT_QUESTION: 'Вопрос отправлен',
  633. SETTINGS: 'Настройки',
  634. MSG_BAN_ATTENTION: '<p style="color:red;">Использование этой функции может привести к бану.</p> Продолжить?',
  635. BTN_YES_I_AGREE: 'Да, я беру на себя все риски!',
  636. BTN_NO_I_AM_AGAINST: 'Нет, я отказываюсь от этого!',
  637. VALUES: 'Значения',
  638. SAVING: 'Сохранка',
  639. USER_ID: 'айди пользователя',
  640. SEND_GIFT: 'Подарок отправлен',
  641. EXPEDITIONS_SENT: 'Экспедиции:<br>Собрано: {countGet}<br>Отправлено: {countSend}',
  642. EXPEDITIONS_NOTHING: 'Нечего собирать/отправлять',
  643. TITANIT: 'Титанит',
  644. COMPLETED: 'завершено',
  645. FLOOR: 'Этаж',
  646. LEVEL: 'Уровень',
  647. BATTLES: 'бои',
  648. EVENT: 'Эвент',
  649. NOT_AVAILABLE: 'недоступен',
  650. NO_HEROES: 'Нет героев',
  651. DAMAGE_AMOUNT: 'Количество урона',
  652. NOTHING_TO_COLLECT: 'Нечего собирать',
  653. COLLECTED: 'Собрано',
  654. REWARD: 'наград',
  655. REMAINING_ATTEMPTS: 'Осталось попыток',
  656. BATTLES_CANCELED: 'Битв отменено',
  657. MINION_RAID: 'Рейд прислужников',
  658. STOPPED: 'Остановлено',
  659. REPETITIONS: 'Повторений',
  660. MISSIONS_PASSED: 'Миссий пройдено',
  661. STOP: 'остановить',
  662. TOTAL_OPEN: 'Всего открыто',
  663. OPEN: 'Открыто',
  664. ROUND_STAT: 'Статистика урона за',
  665. BATTLE: 'боев',
  666. MINIMUM: 'Минимальный',
  667. MAXIMUM: 'Максимальный',
  668. AVERAGE: 'Средний',
  669. NOT_THIS_TIME: 'Не в этот раз',
  670. RETRY_LIMIT_EXCEEDED: 'Превышен лимит попыток',
  671. SUCCESS: 'Успех',
  672. RECEIVED: 'Получено',
  673. LETTERS: 'писем',
  674. PORTALS: 'порталов',
  675. ATTEMPTS: 'попыток',
  676. QUEST_10001: 'Улучши умения героев 3 раза',
  677. QUEST_10002: 'Пройди 10 миссий',
  678. QUEST_10003: 'Пройди 3 героические миссии',
  679. QUEST_10004: 'Сразись 3 раза на Арене или Гранд Арене',
  680. QUEST_10006: 'Используй обмен изумрудов 1 раз',
  681. QUEST_10007: 'Соверши 1 призыв в Атриуме Душ',
  682. QUEST_10016: 'Отправь подарки согильдийцам',
  683. QUEST_10018: 'Используй зелье опыта',
  684. QUEST_10019: 'Открой 1 сундук в Башне',
  685. QUEST_10020: 'Открой 3 сундука в Запределье',
  686. QUEST_10021: 'Собери 75 Титанита в Подземелье Гильдии',
  687. QUEST_10021: 'Собери 150 Титанита в Подземелье Гильдии',
  688. QUEST_10023: 'Прокачай Дар Стихий на 1 уровень',
  689. QUEST_10024: 'Повысь уровень любого артефакта один раз',
  690. QUEST_10025: 'Начни 1 Экспедицию',
  691. QUEST_10026: 'Начни 4 Экспедиции',
  692. QUEST_10027: 'Победи в 1 бою Турнира Стихий',
  693. QUEST_10028: 'Повысь уровень любого артефакта титанов',
  694. QUEST_10029: 'Открой сферу артефактов титанов',
  695. QUEST_10030: 'Улучши облик любого героя 1 раз',
  696. QUEST_10031: 'Победи в 6 боях Турнира Стихий',
  697. QUEST_10043: 'Начни или присоеденись к Приключению',
  698. QUEST_10044: 'Воспользуйся призывом питомцев 1 раз',
  699. QUEST_10046: 'Открой 3 сундука в Приключениях',
  700. QUEST_10047: 'Набери 150 очков активности в Гильдии',
  701. NOTHING_TO_DO: 'Нечего выполнять',
  702. YOU_CAN_COMPLETE: 'Можно выполнить квесты',
  703. BTN_DO_IT: 'Выполняй',
  704. NOT_QUEST_COMPLETED: 'Ни одного квеста не выполенно',
  705. COMPLETED_QUESTS: 'Выполнено квестов',
  706. /* everything button */
  707. ASSEMBLE_OUTLAND: 'Собрать Запределье',
  708. PASS_THE_TOWER: 'Пройти башню',
  709. CHECK_EXPEDITIONS: 'Проверить экспедиции',
  710. COMPLETE_TOE: 'Пройти Турнир Стихий',
  711. COMPLETE_DUNGEON: 'Пройти подземелье',
  712. COMPLETE_DUNGEON_FULL: 'Пройти подземелье фулл',
  713. COLLECT_MAIL: 'Собрать почту',
  714. COLLECT_MISC: 'Собрать всякую херню',
  715. COLLECT_MISC_TITLE: 'Собрать пасхалки, камни облика, ключи, монеты арены и Хрусталь души',
  716. COLLECT_QUEST_REWARDS: 'Собрать награды за квесты',
  717. MAKE_A_SYNC: 'Сделать синхронизацию',
  718.  
  719. RUN_FUNCTION: 'Выполнить следующие функции?',
  720. BTN_GO: 'Погнали!',
  721. PERFORMED: 'Выполняется',
  722. DONE: 'Выполнено',
  723. ERRORS_OCCURRES: 'Призошли ошибки при выполнении',
  724. COPY_ERROR: 'Скопировать в буфер информацию об ошибке',
  725. BTN_YES: 'Да',
  726. ALL_TASK_COMPLETED: 'Все задачи выполнены',
  727.  
  728. UNKNOWN: 'Неизвестно',
  729. ENTER_THE_PATH: 'Введите путь приключения через запятые или дефисы',
  730. START_ADVENTURE: 'Начать приключение по этому пути!',
  731. INCORRECT_WAY: 'Неверный путь в приключении: {from} -> {to}',
  732. BTN_CANCELED: 'Отменено',
  733. MUST_TWO_POINTS: 'Путь должен состоять минимум из 2х точек',
  734. MUST_ONLY_NUMBERS: 'Путь должен содержать только цифры и запятые',
  735. NOT_ON_AN_ADVENTURE: 'Вы не в приключении',
  736. YOU_IN_NOT_ON_THE_WAY: 'Указанный путь должен включать точку вашего положения',
  737. ATTEMPTS_NOT_ENOUGH: 'Ваших попыток не достаточно для завершения пути, продолжить?',
  738. YES_CONTINUE: 'Да, продолжай!',
  739. NOT_ENOUGH_AP: 'Попыток не достаточно',
  740. ATTEMPTS_ARE_OVER: 'Попытки закончились',
  741. MOVES: 'Ходы',
  742. BUFF_GET_ERROR: 'Ошибка при получении бафа',
  743. BATTLE_END_ERROR: 'Ошибка завершения боя',
  744. AUTOBOT: 'АвтоБой',
  745. FAILED_TO_WIN_AUTO: 'Не удалось победить в автобою',
  746. ERROR_OF_THE_BATTLE_COPY: 'Призошли ошибка в процессе прохождения боя<br>Скопировать ошибку в буфер обмена?',
  747. ERROR_DURING_THE_BATTLE: 'Ошибка в процессе прохождения боя',
  748. NO_CHANCE_WIN: 'Нет шансов победить в этом бою: 0/',
  749. LOST_HEROES: 'Вы победили, но потеряли одного или несколько героев!',
  750. VICTORY_IMPOSSIBLE: 'Победа не возможна, бъем на результат?',
  751. FIND_COEFF: 'Поиск коэффициента больше чем',
  752. BTN_PASS: 'ПРОПУСК',
  753. BRAWLS: 'Потасовки',
  754. BRAWLS_TITLE: 'Включает возможность автопотасовок',
  755. START_AUTO_BRAWLS: 'Запустить Автопотасовки?',
  756. LOSSES: 'Поражений',
  757. WINS: 'Побед',
  758. FIGHTS: 'Боев',
  759. STAGE: 'Стадия',
  760. DONT_HAVE_LIVES: 'У Вас нет жизней',
  761. LIVES: 'Жизни',
  762. SECRET_WEALTH_ALREADY: 'товар за Зелья питомцев уже куплен',
  763. SECRET_WEALTH_NOT_ENOUGH: 'Не достаточно Зелье Питомца, у Вас {available}, нужно {need}',
  764. SECRET_WEALTH_UPGRADE_NEW_PET: 'После покупки Зелье Питомца будет не достаточно для прокачки нового питомца',
  765. SECRET_WEALTH_PURCHASED: 'Куплено {count} {name}',
  766. SECRET_WEALTH_CANCELED: 'Тайное богатство: покупка отменена',
  767. SECRET_WEALTH_BUY: 'У вас {available} Зелье Питомца.<br>Вы хотите купить {countBuy} {name} за {price} Зелье Питомца?',
  768. DAILY_BONUS: 'Ежедневная награда',
  769. DO_DAILY_QUESTS: 'Сделать ежедневные квесты',
  770. ACTIONS: 'Действия',
  771. ACTIONS_TITLE: 'Диалоговое окно с различными действиями',
  772. OTHERS: 'Разное',
  773. OTHERS_TITLE: 'Диалоговое окно с дополнительными различными действиями',
  774. CHOOSE_ACTION: 'Выберите действие',
  775. OPEN_LOOTBOX: 'У Вас {lootBox} ящиков, откываем?',
  776. STAMINA: 'Энергия',
  777. BOXES_OVER: 'Ящики закончились',
  778. NO_BOXES: 'Нет ящиков',
  779. NO_MORE_ACTIVITY: 'Больше активности за предметы сегодня не получить',
  780. EXCHANGE_ITEMS: 'Обменять предметы на очки активности (не более {maxActive})?',
  781. GET_ACTIVITY: 'Получить активность',
  782. NOT_ENOUGH_ITEMS: 'Предметов недостаточно',
  783. ACTIVITY_RECEIVED: 'Получено активности',
  784. NO_PURCHASABLE_HERO_SOULS: 'Нет доступных для покупки душ героев',
  785. PURCHASED_HERO_SOULS: 'Куплено {countHeroSouls} душ героев',
  786. NOT_ENOUGH_EMERALDS_540: 'Недостаточно изюма, нужно 540 у Вас {currentStarMoney}',
  787. CHESTS_NOT_AVAILABLE: 'Сундуки не доступны',
  788. OUTLAND_CHESTS_RECEIVED: 'Получено сундуков Запределья',
  789. RAID_NOT_AVAILABLE: 'Рейд не доступен или сфер нет',
  790. RAID_ADVENTURE: 'Рейд {adventureId} приключения!',
  791. SOMETHING_WENT_WRONG: 'Что-то пошло не так',
  792. ADVENTURE_COMPLETED: 'Приключение {adventureId} пройдено {times} раз',
  793. CLAN_STAT_COPY: 'Клановая статистика скопирована в буфер обмена',
  794. GET_ENERGY: 'Получить энергию',
  795. GET_ENERGY_TITLE: 'Открывает платиновые шкатулки по одной до получения 250 энергии',
  796. ITEM_EXCHANGE: 'Обмен предметов',
  797. ITEM_EXCHANGE_TITLE: 'Обменивает предметы на указанное количество активности',
  798. BUY_SOULS: 'Купить души',
  799. BUY_SOULS_TITLE: 'Купить души героев из всех доступных магазинов',
  800. BUY_OUTLAND: 'Купить Запределье',
  801. BUY_OUTLAND_TITLE: 'Купить 9 сундуков в Запределье за 540 изумрудов',
  802. RAID: 'Рейд',
  803. AUTO_RAID_ADVENTURE: 'Рейд приключения',
  804. AUTO_RAID_ADVENTURE_TITLE: 'Рейд приключения заданное количество раз',
  805. CLAN_STAT: 'Клановая статистика',
  806. CLAN_STAT_TITLE: 'Копирует клановую статистику в буфер обмена',
  807. BTN_AUTO_F5: 'Авто (F5)',
  808. BOSS_DAMAGE: 'Урон по боссу: ',
  809. NOTHING_BUY: 'Нечего покупать',
  810. LOTS_BOUGHT: 'За золото куплено {countBuy} лотов',
  811. BUY_FOR_GOLD: 'Скупить за золото',
  812. BUY_FOR_GOLD_TITLE: 'Скупить предметы за золото в Городской лавке и в магазине Камней Душ Питомцев',
  813. REWARDS_AND_MAIL: 'Награды и почта',
  814. REWARDS_AND_MAIL_TITLE: 'Собирает награды и почту',
  815. New_Year_Clan: 'подарок другу',
  816. New_Year_Clan_TITLE: 'Новогодние подарки друзьям',
  817. COLLECT_REWARDS_AND_MAIL: 'Собрано {countQuests} наград и {countMail} писем',
  818. TIMER_ALREADY: 'Таймер уже запущен {time}',
  819. NO_ATTEMPTS_TIMER_START: 'Попыток нет, запущен таймер {time}',
  820. EPIC_BRAWL_RESULT: '{i} Победы: {wins}/{attempts}, Монеты: {coins}, Серия: {progress}/{nextStage} [Закрыть]{end}',
  821. ATTEMPT_ENDED: '<br>Попытки закончились, запущен таймер {time}',
  822. EPIC_BRAWL: 'Вселенская битва',
  823. EPIC_BRAWL_TITLE: 'Тратит попытки во Вселенской битве',
  824. RELOAD_GAME: 'Перезагрузить игру',
  825. TIMER: 'Таймер:',
  826. SHOW_ERRORS: 'Отображать ошибки',
  827. SHOW_ERRORS_TITLE: 'Отображать ошибки запросов к серверу',
  828. ERROR_MSG: 'Ошибка: {name}<br>{description}',
  829. EVENT_AUTO_BOSS: 'Максимальное количество боев для расчета:</br>{length} * {countTestBattle} = {maxCalcBattle}</br>Если у Вас слабый компьютер на это может потребоваться много времени, нажмите крестик для отмены.</br>Искать лучший пак из всех или первый подходящий?',
  830. BEST_SLOW: 'Лучший (медленее)',
  831. FIRST_FAST: 'Первый (быстрее)',
  832. FREEZE_INTERFACE: 'Идет расчет... <br> Интерфейс может зависнуть.',
  833. ERROR_F12: 'Ошибка, подробности в консоли (F12)',
  834. FAILED_FIND_WIN_PACK: 'Победный пак найти не удалось',
  835. BEST_PACK: 'Наилучший пак: ',
  836. BOSS_HAS_BEEN_DEF: 'Босс {bossLvl} побежден',
  837. NOT_ENOUGH_ATTEMPTS_BOSS: 'Для победы босса ${bossLvl} не хватило попыток, повторить?',
  838. BOSS_VICTORY_IMPOSSIBLE: 'По результатам прерасчета {battles} боев победу получить не удалось. Вы хотите продолжить поиск победного боя на реальных боях?',
  839. BOSS_HAS_BEEN_DEF_TEXT: 'Босс {bossLvl} побежден за<br>{countBattle}/{countMaxBattle} попыток<br>(Сделайте синхронизацию или перезагрузите игру для обновления данных)',
  840. MAP: 'Карта: ',
  841. PLAYER_POS: 'Позиции игроков:',
  842. NY_GIFTS: 'Подарки',
  843. NY_GIFTS_TITLE: 'Открыть все новогодние подарки',
  844. NY_NO_GIFTS: 'Нет не полученных подарков',
  845. NY_GIFTS_COLLECTED: 'Собрано {count} подарков',
  846. CHANGE_MAP: 'Карта острова',
  847. CHANGE_MAP_TITLE: 'Сменить карту острова',
  848. SELECT_ISLAND_MAP: 'Выберите карту острова:',
  849. FIRST_MAP: 'Первая карта',
  850. SECOND_MAP: 'Вторая карта',
  851. THIRD_MAP: 'Третья карта',
  852. SECRET_WEALTH_SHOP: 'Тайное богатство {name}: ',
  853. SHOPS: 'Магазины',
  854. SHOPS_DEFAULT: 'Стандартные',
  855. SHOPS_DEFAULT_TITLE: 'Стандартные магазины',
  856. SHOPS_LIST: 'Магазины {number}',
  857. SHOPS_LIST_TITLE: 'Список магазинов {number}',
  858. SHOPS_WARNING: 'Магазины<br><span style="color:red">Если Вы купите монеты магазинов потасовок за изумруды, то их надо использовать сразу, иначе после перезагрузки игры они пропадут!</span>',
  859. MINIONS_WARNING: 'Пачки героев для атаки приспешников неполные, продолжить?',
  860. FAST_SEASON: 'Быстрый сезон',
  861. FAST_SEASON_TITLE: 'Пропуск экрана с выбором карты в сезоне',
  862. SET_NUMBER_LEVELS: 'Указать колличество уровней:',
  863. POSSIBLE_IMPROVE_LEVELS: 'Возможно улучшить только {count} уровней.<br>Улучшаем?',
  864. NOT_ENOUGH_RESOURECES: 'Не хватает ресурсов',
  865. IMPROVED_LEVELS: 'Улучшено уровней: {count}',
  866. ARTIFACTS_UPGRADE: 'Улучшение артефактов',
  867. ARTIFACTS_UPGRADE_TITLE: 'Улучшает указанное количество самых дешевых артефактов героев',
  868. SKINS_UPGRADE: 'Улучшение обликов',
  869. SKINS_UPGRADE_TITLE: 'Улучшает указанное количество самых дешевых обликов героев',
  870. HINT: '<br>Подсказка: ',
  871. PICTURE: '<br>На картинке: ',
  872. ANSWER: '<br>Ответ: ',
  873. NO_HEROES_PACK: 'Проведите хотя бы один бой для сохранения атакующей команды',
  874. },
  875. };
  876.  
  877. function getLang() {
  878. let lang = '';
  879. if (typeof NXFlashVars !== 'undefined') {
  880. lang = NXFlashVars.interface_lang
  881. }
  882. if (!lang) {
  883. lang = (navigator.language || navigator.userLanguage).substr(0, 2);
  884. }
  885. if (lang == 'ru') {
  886. return lang;
  887. }
  888. return 'en';
  889. }
  890.  
  891. this.I18N = function (constant, replace) {
  892. const selectLang = getLang();
  893. if (constant && constant in i18nLangData[selectLang]) {
  894. const result = i18nLangData[selectLang][constant];
  895. if (replace) {
  896. return result.sprintf(replace);
  897. }
  898. return result;
  899. }
  900. return `% ${constant} %`;
  901. };
  902.  
  903. String.prototype.sprintf = String.prototype.sprintf ||
  904. function () {
  905. "use strict";
  906. var str = this.toString();
  907. if (arguments.length) {
  908. var t = typeof arguments[0];
  909. var key;
  910. var args = ("string" === t || "number" === t) ?
  911. Array.prototype.slice.call(arguments)
  912. : arguments[0];
  913.  
  914. for (key in args) {
  915. str = str.replace(new RegExp("\\{" + key + "\\}", "gi"), args[key]);
  916. }
  917. }
  918.  
  919. return str;
  920. };
  921.  
  922. /**
  923. * Checkboxes
  924. *
  925. * Чекбоксы
  926. */
  927. const checkboxes = {
  928. passBattle: {
  929. label: I18N('SKIP_FIGHTS'),
  930. cbox: null,
  931. title: I18N('SKIP_FIGHTS_TITLE'),
  932. default: false
  933. },
  934. /*sendExpedition: {
  935. label: I18N('AUTO_EXPEDITION'),
  936. cbox: null,
  937. title: I18N('AUTO_EXPEDITION_TITLE'),
  938. default: false
  939. },*/ //тест сдедал экспедиции на авто в сделать все
  940. cancelBattle: {
  941. label: I18N('CANCEL_FIGHT'),
  942. cbox: null,
  943. title: I18N('CANCEL_FIGHT_TITLE'),
  944. default: false,
  945. },
  946. preCalcBattle: {
  947. label: I18N('BATTLE_RECALCULATION'),
  948. cbox: null,
  949. title: I18N('BATTLE_RECALCULATION_TITLE'),
  950. default: false
  951. },
  952. finishingBattle: {
  953. label: I18N('BATTLE_FISHING'),
  954. cbox: null,
  955. title: I18N('BATTLE_FISHING_TITLE'),
  956. default: false
  957. },
  958. treningBattle: {
  959. label: I18N('BATTLE_TRENING'),
  960. cbox: null,
  961. title: I18N('BATTLE_TRENING_TITLE'),
  962. default: false
  963. },
  964. countControl: {
  965. label: I18N('QUANTITY_CONTROL'),
  966. cbox: null,
  967. title: I18N('QUANTITY_CONTROL_TITLE'),
  968. default: true
  969. },
  970. repeatMission: {
  971. label: I18N('REPEAT_CAMPAIGN'),
  972. cbox: null,
  973. title: I18N('REPEAT_CAMPAIGN_TITLE'),
  974. default: false
  975. },
  976. noOfferDonat: {
  977. label: I18N('DISABLE_DONAT'),
  978. cbox: null,
  979. title: I18N('DISABLE_DONAT_TITLE'),
  980. /**
  981. * A crutch to get the field before getting the character id
  982. *
  983. * Костыль чтоб получать поле до получения id персонажа
  984. */
  985. default: (() => {
  986. $result = false;
  987. try {
  988. $result = JSON.parse(localStorage[GM_info.script.name + ':noOfferDonat'])
  989. } catch(e) {
  990. $result = false;
  991. }
  992. return $result || false;
  993. })(),
  994. },
  995. dailyQuests: {
  996. label: I18N('DAILY_QUESTS'),
  997. cbox: null,
  998. title: I18N('DAILY_QUESTS_TITLE'),
  999. default: false
  1000. },
  1001. // Потасовки
  1002. /*autoBrawls: {
  1003. label: I18N('BRAWLS'),
  1004. cbox: null,
  1005. title: I18N('BRAWLS_TITLE'),
  1006. default: (() => {
  1007. $result = false;
  1008. try {
  1009. $result = JSON.parse(localStorage[GM_info.script.name + ':autoBrawls'])
  1010. } catch (e) {
  1011. $result = false;
  1012. }
  1013. return $result || false;
  1014. })(),
  1015. hide: false,
  1016. },
  1017. getAnswer: {
  1018. label: I18N('AUTO_QUIZ'),
  1019. cbox: null,
  1020. title: I18N('AUTO_QUIZ_TITLE'),
  1021. default: false,
  1022. hide: true,
  1023. },
  1024. showErrors: {
  1025. label: I18N('SHOW_ERRORS'),
  1026. cbox: null,
  1027. title: I18N('SHOW_ERRORS_TITLE'),
  1028. default: true
  1029. },*/
  1030. buyForGold: {
  1031. label: I18N('BUY_FOR_GOLD'),
  1032. cbox: null,
  1033. title: I18N('BUY_FOR_GOLD_TITLE'),
  1034. default: false
  1035. },
  1036. hideServers: {
  1037. label: I18N('HIDE_SERVERS'),
  1038. cbox: null,
  1039. title: I18N('HIDE_SERVERS_TITLE'),
  1040. default: false
  1041. },
  1042. fastSeason: {
  1043. label: I18N('FAST_SEASON'),
  1044. cbox: null,
  1045. title: I18N('FAST_SEASON_TITLE'),
  1046. default: false
  1047. },
  1048. };
  1049. /**
  1050. * Get checkbox state
  1051. *
  1052. * Получить состояние чекбокса
  1053. */
  1054. function isChecked(checkBox) {
  1055. if (!(checkBox in checkboxes)) {
  1056. return false;
  1057. }
  1058. return checkboxes[checkBox].cbox?.checked;
  1059. }
  1060. /**
  1061. * Input fields
  1062. *
  1063. * Поля ввода
  1064. */
  1065. const inputs = {
  1066. countTitanit: {
  1067. input: null,
  1068. title: I18N('HOW_MUCH_TITANITE'),
  1069. default: 150,
  1070. },
  1071. speedBattle: {
  1072. input: null,
  1073. title: I18N('COMBAT_SPEED'),
  1074. default: 5,
  1075. },
  1076. //тест повтор компании
  1077. countRaid: {
  1078. input: null,
  1079. title: I18N('HOW_REPEAT_CAMPAIGN'),
  1080. default: 5,
  1081. },
  1082. countTestBattle: {
  1083. input: null,
  1084. title: I18N('NUMBER_OF_TEST'),
  1085. default: 10,
  1086. },
  1087. countAutoBattle: {
  1088. input: null,
  1089. title: I18N('NUMBER_OF_AUTO_BATTLE'),
  1090. default: 10,
  1091. },
  1092. /*FPS: {
  1093. input: null,
  1094. title: 'FPS',
  1095. default: 60,
  1096. }*/
  1097. }
  1098. //сохранка тест
  1099. const inputs2 = {
  1100. countBattle: {
  1101. input: null,
  1102. title: '-1 сохраняет защиту, -2 атаку противника с Replay',
  1103. default: 1,
  1104. },
  1105. needResource: {
  1106. input: null,
  1107. title: 'Мощь противника мин.(тыс.)/урона(млн.)',
  1108. default: 300,
  1109. },
  1110. needResource2: {
  1111. input: null,
  1112. title: 'Мощь противника макс./тип бафа',
  1113. default: 1500,
  1114. },
  1115. }
  1116. //новогодние подарки игрокам других гильдий
  1117. const inputs3 = {
  1118. userID: { // айди игрока посмотреть открыв его инфо
  1119. input: null,
  1120. title: I18N('USER_ID_TITLE'),
  1121. default: 111111,
  1122. },
  1123. GiftNum: { // номер подарка считаем слева направо от 1 до 6, под 1 это за 750 новогодних игрушек
  1124. input: null,
  1125. title: I18N('GIFT_NUM'),
  1126. default: 10,
  1127. },
  1128. AmontID: { // количество ресурсов от 1 до бесконечности
  1129. input: null,
  1130. title: I18N('AMOUNT'),
  1131. default: 1,
  1132. },
  1133. }
  1134. /**
  1135. * Checks the checkbox
  1136. *
  1137. * Поплучить данные поля ввода
  1138. */
  1139. /*function getInput(inputName) {
  1140. return inputs[inputName]?.input?.value;
  1141. }*/
  1142. function getInput(inputName) {
  1143. if (inputName in inputs){return inputs[inputName]?.input?.value;}
  1144. else if (inputName in inputs2){return inputs2[inputName]?.input?.value;}
  1145. //else if (inputName in inputs3){return inputs3[inputName]?.input?.value;}
  1146. else return null
  1147. }
  1148.  
  1149. //тест рейд
  1150. /** Автоповтор миссии */
  1151. let isRepeatMission = false;
  1152. /** Вкл/Выкл автоповтор миссии */
  1153. this.switchRepeatMission = function() {
  1154. isRepeatMission = !isRepeatMission;
  1155. console.log(isRepeatMission);
  1156. }
  1157.  
  1158. /**
  1159. * Control FPS
  1160. *
  1161. * Контроль FPS
  1162. */
  1163. let nextAnimationFrame = Date.now();
  1164. const oldRequestAnimationFrame = this.requestAnimationFrame;
  1165. this.requestAnimationFrame = async function (e) {
  1166. const FPS = Number(getInput('FPS')) || -1;
  1167. const now = Date.now();
  1168. const delay = nextAnimationFrame - now;
  1169. nextAnimationFrame = Math.max(now, nextAnimationFrame) + Math.min(1e3 / FPS, 1e3);
  1170. if (delay > 0) {
  1171. await new Promise((e) => setTimeout(e, delay));
  1172. }
  1173. oldRequestAnimationFrame(e);
  1174. };
  1175.  
  1176. /**
  1177. * Button List
  1178. *
  1179. * Список кнопочек
  1180. */
  1181. const buttons = {
  1182. getOutland: {
  1183. name: I18N('TO_DO_EVERYTHING'),
  1184. title: I18N('TO_DO_EVERYTHING_TITLE'),
  1185. func: testDoYourBest,
  1186. },
  1187. /*
  1188. doActions: {
  1189. name: I18N('ACTIONS'),
  1190. title: I18N('ACTIONS_TITLE'),
  1191. func: async function () {
  1192. const popupButtons = [
  1193. {
  1194. msg: I18N('OUTLAND'),
  1195. result: function () {
  1196. confShow(`${I18N('RUN_SCRIPT')} ${I18N('OUTLAND')}?`, getOutland);
  1197. },
  1198. title: I18N('OUTLAND_TITLE'),
  1199. },
  1200. {
  1201. msg: I18N('TOWER'),
  1202. result: function () {
  1203. confShow(`${I18N('RUN_SCRIPT')} ${I18N('TOWER')}?`, testTower);
  1204. },
  1205. title: I18N('TOWER_TITLE'),
  1206. },
  1207. {
  1208. msg: I18N('EXPEDITIONS'),
  1209. result: function () {
  1210. confShow(`${I18N('RUN_SCRIPT')} ${I18N('EXPEDITIONS')}?`, checkExpedition);
  1211. },
  1212. title: I18N('EXPEDITIONS_TITLE'),
  1213. },
  1214. {
  1215. msg: I18N('MINIONS'),
  1216. result: function () {
  1217. confShow(`${I18N('RUN_SCRIPT')} ${I18N('MINIONS')}?`, testRaidNodes);
  1218. },
  1219. title: I18N('MINIONS_TITLE'),
  1220. },
  1221. {
  1222. msg: I18N('ESTER_EGGS'),
  1223. result: function () {
  1224. confShow(`${I18N('RUN_SCRIPT')} ${I18N('ESTER_EGGS')}?`, offerFarmAllReward);
  1225. },
  1226. title: I18N('ESTER_EGGS_TITLE'),
  1227. },
  1228. {
  1229. msg: I18N('STORM'),
  1230. result: function () {
  1231. testAdventure('solo');
  1232. },
  1233. title: I18N('STORM_TITLE'),
  1234. },
  1235. {
  1236. msg: I18N('REWARDS'),
  1237. result: function () {
  1238. confShow(`${I18N('RUN_SCRIPT')} ${I18N('REWARDS')}?`, questAllFarm);
  1239. },
  1240. title: I18N('REWARDS_TITLE'),
  1241. },
  1242. {
  1243. msg: I18N('MAIL'),
  1244. result: function () {
  1245. confShow(`${I18N('RUN_SCRIPT')} ${I18N('MAIL')}?`, mailGetAll);
  1246. },
  1247. title: I18N('MAIL_TITLE'),
  1248. },
  1249. {
  1250. msg: I18N('SEER'),
  1251. result: function () {
  1252. confShow(`${I18N('RUN_SCRIPT')} ${I18N('SEER')}?`, rollAscension);
  1253. },
  1254. title: I18N('SEER_TITLE'),
  1255. },
  1256. {
  1257. msg: I18N('NY_GIFTS'),
  1258. result: getGiftNewYear,
  1259. title: I18N('NY_GIFTS_TITLE'),
  1260. },
  1261. ];
  1262. popupButtons.push({ result: false, isClose: true })
  1263. const answer = await popup.confirm(`${I18N('CHOOSE_ACTION')}:`, popupButtons);
  1264. if (typeof answer === 'function') {
  1265. answer();
  1266. }
  1267. }
  1268. },*/
  1269. doOthers: {
  1270. name: I18N('OTHERS'),
  1271. title: I18N('OTHERS_TITLE'),
  1272. func: async function () {
  1273. const popupButtons = [
  1274. /*
  1275. {
  1276. msg: I18N('GET_ENERGY'),
  1277. result: farmStamina,
  1278. title: I18N('GET_ENERGY_TITLE'),
  1279. },
  1280. {
  1281. msg: I18N('ITEM_EXCHANGE'),
  1282. result: fillActive,
  1283. title: I18N('ITEM_EXCHANGE_TITLE'),
  1284. },
  1285. {
  1286. msg: I18N('BUY_SOULS'),
  1287. result: function () {
  1288. confShow(`${I18N('RUN_SCRIPT')} ${I18N('BUY_SOULS')}?`, buyHeroFragments);
  1289. },
  1290. title: I18N('BUY_SOULS_TITLE'),
  1291. },
  1292. {
  1293. msg: I18N('BUY_FOR_GOLD'),
  1294. result: function () {
  1295. confShow(`${I18N('RUN_SCRIPT')} ${I18N('BUY_FOR_GOLD')}?`, buyInStoreForGold);
  1296. },
  1297. title: I18N('BUY_FOR_GOLD_TITLE'),
  1298. },
  1299. {
  1300. msg: I18N('BUY_OUTLAND'),
  1301. result: function () {
  1302. confShow(I18N('BUY_OUTLAND_TITLE') + '?', bossOpenChestPay);
  1303. },
  1304. title: I18N('BUY_OUTLAND_TITLE'),
  1305. },
  1306. {
  1307. msg: I18N('AUTO_RAID_ADVENTURE'),
  1308. result: autoRaidAdventure,
  1309. title: I18N('AUTO_RAID_ADVENTURE_TITLE'),
  1310. },
  1311. {
  1312. msg: I18N('CLAN_STAT'),
  1313. result: clanStatistic,
  1314. title: I18N('CLAN_STAT_TITLE'),
  1315. },
  1316. {
  1317. msg: I18N('EPIC_BRAWL'),
  1318. result: async function () {
  1319. confShow(`${I18N('RUN_SCRIPT')} ${I18N('EPIC_BRAWL')}?`, () => {
  1320. const brawl = new epicBrawl;
  1321. brawl.start();
  1322. });
  1323. },
  1324. title: I18N('EPIC_BRAWL_TITLE'),
  1325. },*/
  1326. {
  1327. msg: I18N('ARTIFACTS_UPGRADE'),
  1328. result: updateArtifacts,
  1329. title: I18N('ARTIFACTS_UPGRADE_TITLE'),
  1330. },
  1331. {
  1332. msg: I18N('SKINS_UPGRADE'),
  1333. result: updateSkins,
  1334. title: I18N('SKINS_UPGRADE_TITLE'),
  1335. },
  1336. {
  1337. msg: I18N('CHANGE_MAP'),
  1338. result: async function () {
  1339. const result = await popup.confirm(I18N('SELECT_ISLAND_MAP'), [
  1340. { msg: I18N('FIRST_MAP'), result: 1 },
  1341. { msg: I18N('SECOND_MAP'), result: 2 },
  1342. { msg: I18N('THIRD_MAP'), result: 3 },
  1343. { result: false, isClose: true },
  1344. ]);
  1345. if (result) {
  1346. cheats.changeIslandMap(result);
  1347. }
  1348. },
  1349. title: I18N('CHANGE_MAP_TITLE'),
  1350. },
  1351. {
  1352. msg: I18N('SHOPS'),
  1353. result: async function () {
  1354. const shopButtons = [{
  1355. msg: I18N('SHOPS_DEFAULT'),
  1356. result: function () {
  1357. cheats.goDefaultShops();
  1358. },
  1359. title: I18N('SHOPS_DEFAULT_TITLE'),
  1360. }, {
  1361. msg: I18N('SECRET_WEALTH'),
  1362. result: function () {
  1363. cheats.goSecretWealthShops();
  1364. },
  1365. title: I18N('SECRET_WEALTH'),
  1366. }];
  1367. for (let i = 0; i < 4; i++) {
  1368. const number = i + 1;
  1369. shopButtons.push({
  1370. msg: I18N('SHOPS_LIST', { number }),
  1371. result: function () {
  1372. cheats.goCustomShops(i);
  1373. },
  1374. title: I18N('SHOPS_LIST_TITLE', { number }),
  1375. })
  1376. }
  1377. shopButtons.push({ result: false, isClose: true })
  1378. const answer = await popup.confirm(I18N('SHOPS_WARNING'), shopButtons);
  1379. if (typeof answer === 'function') {
  1380. answer();
  1381. }
  1382. },
  1383. title: I18N('SHOPS'),
  1384. },
  1385. ];
  1386.  
  1387. popupButtons.push({ result: false, isClose: true })
  1388. const answer = await popup.confirm(`${I18N('CHOOSE_ACTION')}:`, popupButtons);
  1389. if (typeof answer === 'function') {
  1390. answer();
  1391. }
  1392. }
  1393. },
  1394. testTitanArena: {
  1395. name: I18N('TITAN_ARENA'),
  1396. title: I18N('TITAN_ARENA_TITLE'),
  1397. func: function () {
  1398. confShow(`${I18N('RUN_SCRIPT')} ${I18N('TITAN_ARENA')}?`, testTitanArena);
  1399. },
  1400. },
  1401. /* тест подземка есть в сделать все
  1402. testDungeon: {
  1403. name: I18N('DUNGEON'),
  1404. title: I18N('DUNGEON_TITLE'),
  1405. func: function () {
  1406. confShow(`${I18N('RUN_SCRIPT')} ${I18N('DUNGEON')}?`, testDungeon);
  1407. },
  1408. hide: true,
  1409. },*/
  1410. //тест подземка 2
  1411. DungeonFull: {
  1412. name: I18N('DUNGEON2'),
  1413. title: I18N('DUNGEON_FULL_TITLE'),
  1414. func: function () {
  1415. confShow(`${I18N('RUN_SCRIPT')} ${I18N('DUNGEON_FULL_TITLE')}?`, DungeonFull);
  1416. },
  1417. },
  1418. //остановить подземелье
  1419. stopDungeon: {
  1420. name: I18N('STOP_DUNGEON'),
  1421. title: I18N('STOP_DUNGEON_TITLE'),
  1422. func: function () {
  1423. confShow(`${I18N('STOP_SCRIPT')} ${I18N('STOP_DUNGEON_TITLE')}?`, stopDungeon);
  1424. },
  1425. },
  1426. // Архидемон
  1427. bossRatingEvent: {
  1428. name: I18N('ARCHDEMON'),
  1429. title: I18N('ARCHDEMON_TITLE'),
  1430. func: function () {
  1431. confShow(`${I18N('RUN_SCRIPT')} ${I18N('ARCHDEMON')}?`, bossRatingEvent);
  1432. },
  1433. hide: true,
  1434. },
  1435. /*
  1436. // Горнило душ
  1437. bossRatingEvent: {
  1438. name: I18N('CRUCIBLE_SOULS'),
  1439. title: I18N('CRUCIBLE_SOULS_TITLE'),
  1440. func: function () {
  1441. confShow(`${I18N('RUN_SCRIPT')} ${I18N('CRUCIBLE_SOULS')}?`, bossRatingEventSouls);
  1442. },
  1443. },*/
  1444. // Буря
  1445. /*testAdventure2: {
  1446. name: I18N('STORM'),
  1447. title: I18N('STORM_TITLE'),
  1448. func: () => {
  1449. testAdventure2('solo');
  1450. },
  1451. },*/
  1452. rewardsAndMailFarm: {
  1453. name: I18N('REWARDS_AND_MAIL'),
  1454. title: I18N('REWARDS_AND_MAIL_TITLE'),
  1455. func: function () {
  1456. confShow(`${I18N('RUN_SCRIPT')} ${I18N('REWARDS_AND_MAIL')}?`, rewardsAndMailFarm);
  1457. },
  1458. },
  1459. //тест прислужники
  1460. testRaidNodes: {
  1461. name: I18N('MINIONS'),
  1462. title: I18N('MINIONS_TITLE'),
  1463. func: function () {
  1464. confShow(`${I18N('RUN_SCRIPT')} ${I18N('MINIONS')}?`, testRaidNodes);
  1465. },
  1466. },
  1467. testAdventure: {
  1468. name: I18N('ADVENTURE'),
  1469. title: I18N('ADVENTURE_TITLE'),
  1470. func: () => {
  1471. testAdventure();
  1472. },
  1473. },
  1474. goToSanctuary: {
  1475. name: I18N('SANCTUARY'),
  1476. title: I18N('SANCTUARY_TITLE'),
  1477. func: cheats.goSanctuary,
  1478. },
  1479. goToClanWar: {
  1480. name: I18N('GUILD_WAR'),
  1481. title: I18N('GUILD_WAR_TITLE'),
  1482. func: cheats.goClanWar,
  1483. },
  1484. dailyQuests: {
  1485. name: I18N('DAILY_QUESTS'),
  1486. title: I18N('DAILY_QUESTS_TITLE'),
  1487. func: async function () {
  1488. const quests = new dailyQuests(() => { }, () => { });
  1489. await quests.autoInit();
  1490. quests.start();
  1491. },
  1492. },
  1493. //подарок др
  1494. /*NewYearGift_Clan: {
  1495. name: I18N('New_Year_Clan'),
  1496. title: I18N('New_Year_Clan_TITLE'),
  1497. func: function () {
  1498. confShow(`${I18N('RUN_SCRIPT')} ${I18N('New_Year_Clan_TITLE')}?`, NewYearGift_Clan);
  1499. },
  1500. },*/
  1501. newDay: {
  1502. name: I18N('SYNC'),
  1503. title: I18N('SYNC_TITLE'),
  1504. func: function () {
  1505. confShow(`${I18N('RUN_SCRIPT')} ${I18N('SYNC')}?`, cheats.refreshGame);
  1506. },
  1507. },
  1508. }
  1509. /**
  1510. * Display buttons
  1511. *
  1512. * Вывести кнопочки
  1513. */
  1514. function addControlButtons() {
  1515. for (let name in buttons) {
  1516. button = buttons[name];
  1517. if (button.hide) {
  1518. continue;
  1519. }
  1520. button['button'] = scriptMenu.addButton(button.name, button.func, button.title);
  1521. }
  1522. }
  1523. /**
  1524. * Adds links
  1525. *
  1526. * Добавляет ссылки
  1527. */
  1528. function addBottomUrls() {
  1529. scriptMenu.addHeader(I18N('BOTTOM_URLS'));
  1530. }
  1531. /**
  1532. * Stop repetition of the mission
  1533. *
  1534. * Остановить повтор миссии
  1535. */
  1536. let isStopSendMission = false;
  1537. /**
  1538. * There is a repetition of the mission
  1539. *
  1540. * Идет повтор миссии
  1541. */
  1542. let isSendsMission = false;
  1543. /**
  1544. * Data on the past mission
  1545. *
  1546. * Данные о прошедшей мисии
  1547. */
  1548. let lastMissionStart = {}
  1549. /**
  1550. * Start time of the last battle in the company
  1551. *
  1552. * Время начала последнего боя в кампании
  1553. */
  1554. let lastMissionBattleStart = 0;
  1555. /**
  1556. * Data on the past attack on the boss
  1557. *
  1558. * Данные о прошедшей атаке на босса
  1559. */
  1560. let lastBossBattle = {}
  1561. /**
  1562. * Data for calculating the last battle with the boss
  1563. *
  1564. * Данные для расчете последнего боя с боссом
  1565. */
  1566. let lastBossBattleInfo = null;
  1567. /**
  1568. * Ability to cancel the battle in Asgard
  1569. *
  1570. * Возможность отменить бой в Астгарде
  1571. */
  1572. let isCancalBossBattle = true;
  1573. /**
  1574. * Information about the last battle
  1575. *
  1576. * Данные о прошедшей битве
  1577. */
  1578. let lastBattleArg = {}
  1579. let lastBossBattleStart = null;
  1580. this.addBattleTimer = 4;
  1581. this.invasionTimer = 2500;
  1582. /**
  1583. * The name of the function of the beginning of the battle
  1584. *
  1585. * Имя функции начала боя
  1586. */
  1587. let nameFuncStartBattle = '';
  1588. /**
  1589. * The name of the function of the end of the battle
  1590. *
  1591. * Имя функции конца боя
  1592. */
  1593. let nameFuncEndBattle = '';
  1594. /**
  1595. * Data for calculating the last battle
  1596. *
  1597. * Данные для расчета последнего боя
  1598. */
  1599. let lastBattleInfo = null;
  1600. /**
  1601. * The ability to cancel the battle
  1602. *
  1603. * Возможность отменить бой
  1604. */
  1605. let isCancalBattle = true;
  1606.  
  1607. /**
  1608. * Certificator of the last open nesting doll
  1609. *
  1610. * Идетификатор последней открытой матрешки
  1611. */
  1612. let lastRussianDollId = null;
  1613. /**
  1614. * Cancel the training guide
  1615. *
  1616. * Отменить обучающее руководство
  1617. */
  1618. this.isCanceledTutorial = false;
  1619.  
  1620. /**
  1621. * Data from the last question of the quiz
  1622. *
  1623. * Данные последнего вопроса викторины
  1624. */
  1625. let lastQuestion = null;
  1626. /**
  1627. * Answer to the last question of the quiz
  1628. *
  1629. * Ответ на последний вопрос викторины
  1630. */
  1631. let lastAnswer = null;
  1632. /**
  1633. * Flag for opening keys or titan artifact spheres
  1634. *
  1635. * Флаг открытия ключей или сфер артефактов титанов
  1636. */
  1637. let artifactChestOpen = false;
  1638. /**
  1639. * The name of the function to open keys or orbs of titan artifacts
  1640. *
  1641. * Имя функции открытия ключей или сфер артефактов титанов
  1642. */
  1643. let artifactChestOpenCallName = '';
  1644. let correctShowOpenArtifact = 0;
  1645. /**
  1646. * Data for the last battle in the dungeon
  1647. * (Fix endless cards)
  1648. *
  1649. * Данные для последнего боя в подземке
  1650. * (Исправление бесконечных карт)
  1651. */
  1652. let lastDungeonBattleData = null;
  1653. /**
  1654. * Start time of the last battle in the dungeon
  1655. *
  1656. * Время начала последнего боя в подземелье
  1657. */
  1658. let lastDungeonBattleStart = 0;
  1659. /**
  1660. * Subscription end time
  1661. *
  1662. * Время окончания подписки
  1663. */
  1664. let subEndTime = 0;
  1665. /**
  1666. * Number of prediction cards
  1667. *
  1668. * Количество карт предсказаний
  1669. */
  1670. let countPredictionCard = 0;
  1671.  
  1672. /**
  1673. * Brawl pack
  1674. *
  1675. * Пачка для потасовок
  1676. */
  1677. let brawlsPack = null;
  1678. /**
  1679. * Autobrawl started
  1680. *
  1681. * Автопотасовка запущена
  1682. */
  1683. let isBrawlsAutoStart = false;
  1684. /**
  1685. * Copies the text to the clipboard
  1686. *
  1687. * Копирует тест в буфер обмена
  1688. * @param {*} text copied text // копируемый текст
  1689. */
  1690. function copyText(text) {
  1691. let copyTextarea = document.createElement("textarea");
  1692. copyTextarea.style.opacity = "0";
  1693. copyTextarea.textContent = text;
  1694. document.body.appendChild(copyTextarea);
  1695. copyTextarea.select();
  1696. document.execCommand("copy");
  1697. document.body.removeChild(copyTextarea);
  1698. delete copyTextarea;
  1699. }
  1700. /**
  1701. * Returns the history of requests
  1702. *
  1703. * Возвращает историю запросов
  1704. */
  1705. this.getRequestHistory = function() {
  1706. return requestHistory;
  1707. }
  1708. /**
  1709. * Generates a random integer from min to max
  1710. *
  1711. * Гененирует случайное целое число от min до max
  1712. */
  1713. const random = function (min, max) {
  1714. return Math.floor(Math.random() * (max - min + 1) + min);
  1715. }
  1716. /**
  1717. * Clearing the request history
  1718. *
  1719. * Очистка истоии запросов
  1720. */
  1721. setInterval(function () {
  1722. let now = Date.now();
  1723. for (let i in requestHistory) {
  1724. const time = +i.split('_')[0];
  1725. if (now - time > 300000) {
  1726. delete requestHistory[i];
  1727. }
  1728. }
  1729. }, 300000);
  1730. /**
  1731. * Displays the dialog box
  1732. *
  1733. * Отображает диалоговое окно
  1734. */
  1735. function confShow(message, yesCallback, noCallback) {
  1736. let buts = [];
  1737. message = message || I18N('DO_YOU_WANT');
  1738. noCallback = noCallback || (() => {});
  1739. if (yesCallback) {
  1740. buts = [
  1741. { msg: I18N('BTN_RUN'), result: true},
  1742. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true},
  1743. ]
  1744. } else {
  1745. yesCallback = () => {};
  1746. buts = [
  1747. { msg: I18N('BTN_OK'), result: true},
  1748. ];
  1749. }
  1750. popup.confirm(message, buts).then((e) => {
  1751. // dialogPromice = null;
  1752. if (e) {
  1753. yesCallback();
  1754. } else {
  1755. noCallback();
  1756. }
  1757. });
  1758. }
  1759. /**
  1760. * Override/proxy the method for creating a WS package send
  1761. *
  1762. * Переопределяем/проксируем метод создания отправки WS пакета
  1763. */
  1764. WebSocket.prototype.send = function (data) {
  1765. if (!this.isSetOnMessage) {
  1766. const oldOnmessage = this.onmessage;
  1767. this.onmessage = function (event) {
  1768. try {
  1769. const data = JSON.parse(event.data);
  1770. if (!this.isWebSocketLogin && data.result.type == "iframeEvent.login") {
  1771. this.isWebSocketLogin = true;
  1772. } else if (data.result.type == "iframeEvent.login") {
  1773. return;
  1774. }
  1775. } catch (e) { }
  1776. return oldOnmessage.apply(this, arguments);
  1777. }
  1778. this.isSetOnMessage = true;
  1779. }
  1780. original.SendWebSocket.call(this, data);
  1781. }
  1782. /**
  1783. * Overriding/Proxying the Ajax Request Creation Method
  1784. *
  1785. * Переопределяем/проксируем метод создания Ajax запроса
  1786. */
  1787. XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
  1788. this.uniqid = Date.now() + '_' + random(1000000, 10000000);
  1789. this.errorRequest = false;
  1790. if (method == 'POST' && url.includes('.nextersglobal.com/api/') && /api\/$/.test(url)) {
  1791. if (!apiUrl) {
  1792. apiUrl = url;
  1793. const socialInfo = /heroes-(.+?)\./.exec(apiUrl);
  1794. console.log(socialInfo);
  1795. }
  1796. requestHistory[this.uniqid] = {
  1797. method,
  1798. url,
  1799. error: [],
  1800. headers: {},
  1801. request: null,
  1802. response: null,
  1803. signature: [],
  1804. calls: {},
  1805. };
  1806. } else if (method == 'POST' && url.includes('error.nextersglobal.com/client/')) {
  1807. this.errorRequest = true;
  1808. }
  1809. return original.open.call(this, method, url, async, user, password);
  1810. };
  1811. /**
  1812. * Overriding/Proxying the header setting method for the AJAX request
  1813. *
  1814. * Переопределяем/проксируем метод установки заголовков для AJAX запроса
  1815. */
  1816. XMLHttpRequest.prototype.setRequestHeader = function (name, value, check) {
  1817. if (this.uniqid in requestHistory) {
  1818. requestHistory[this.uniqid].headers[name] = value;
  1819. } else {
  1820. check = true;
  1821. }
  1822.  
  1823. if (name == 'X-Auth-Signature') {
  1824. requestHistory[this.uniqid].signature.push(value);
  1825. if (!check) {
  1826. return;
  1827. }
  1828. }
  1829.  
  1830. return original.setRequestHeader.call(this, name, value);
  1831. };
  1832. /**
  1833. * Overriding/Proxying the AJAX Request Sending Method
  1834. *
  1835. * Переопределяем/проксируем метод отправки AJAX запроса
  1836. */
  1837. XMLHttpRequest.prototype.send = async function (sourceData) {
  1838. if (this.uniqid in requestHistory) {
  1839. let tempData = null;
  1840. if (getClass(sourceData) == "ArrayBuffer") {
  1841. tempData = decoder.decode(sourceData);
  1842. } else {
  1843. tempData = sourceData;
  1844. }
  1845. requestHistory[this.uniqid].request = tempData;
  1846. let headers = requestHistory[this.uniqid].headers;
  1847. lastHeaders = Object.assign({}, headers);
  1848. /**
  1849. * Game loading event
  1850. *
  1851. * Событие загрузки игры
  1852. */
  1853. if (headers["X-Request-Id"] > 2 && !isLoadGame) {
  1854. isLoadGame = true;
  1855. await lib.load();
  1856. addControls();
  1857. addControlButtons();
  1858. addBottomUrls();
  1859.  
  1860. //if (isChecked('sendExpedition')) {
  1861. checkExpedition(); //экспедиции на авто при входе в игру
  1862. //}
  1863.  
  1864. getAutoGifts();
  1865.  
  1866. cheats.activateHacks();
  1867.  
  1868. justInfo();
  1869. if (isChecked('dailyQuests')) {
  1870. testDailyQuests();
  1871. }
  1872.  
  1873. if (isChecked('buyForGold')) {
  1874. buyInStoreForGold();
  1875. }
  1876. }
  1877. /**
  1878. * Outgoing request data processing
  1879. *
  1880. * Обработка данных исходящего запроса
  1881. */
  1882. sourceData = await checkChangeSend.call(this, sourceData, tempData);
  1883. /**
  1884. * Handling incoming request data
  1885. *
  1886. * Обработка данных входящего запроса
  1887. */
  1888. const oldReady = this.onreadystatechange;
  1889. this.onreadystatechange = async function (e) {
  1890. if (this.errorRequest) {
  1891. return oldReady.apply(this, arguments);
  1892. }
  1893. if(this.readyState == 4 && this.status == 200) {
  1894. isTextResponse = this.responseType === "text" || this.responseType === "";
  1895. let response = isTextResponse ? this.responseText : this.response;
  1896. requestHistory[this.uniqid].response = response;
  1897. /**
  1898. * Replacing incoming request data
  1899. *
  1900. * Заменна данных входящего запроса
  1901. */
  1902. if (isTextResponse) {
  1903. await checkChangeResponse.call(this, response);
  1904. }
  1905. /**
  1906. * A function to run after the request is executed
  1907. *
  1908. * Функция запускаемая после выполения запроса
  1909. */
  1910. if (typeof this.onReadySuccess == 'function') {
  1911. setTimeout(this.onReadySuccess, 500);
  1912. }
  1913. /** Удаляем из истории запросов битвы с боссом */
  1914. if ('invasion_bossStart' in requestHistory[this.uniqid].calls) delete requestHistory[this.uniqid];
  1915. }
  1916. if (oldReady) {
  1917. return oldReady.apply(this, arguments);
  1918. }
  1919. }
  1920. }
  1921. if (this.errorRequest) {
  1922. const oldReady = this.onreadystatechange;
  1923. this.onreadystatechange = function () {
  1924. Object.defineProperty(this, 'status', {
  1925. writable: true
  1926. });
  1927. this.status = 200;
  1928. Object.defineProperty(this, 'readyState', {
  1929. writable: true
  1930. });
  1931. this.readyState = 4;
  1932. Object.defineProperty(this, 'responseText', {
  1933. writable: true
  1934. });
  1935. this.responseText = JSON.stringify({
  1936. "result": true
  1937. });
  1938. if (typeof this.onReadySuccess == 'function') {
  1939. setTimeout(this.onReadySuccess, 500);
  1940. }
  1941. return oldReady.apply(this, arguments);
  1942. }
  1943. this.onreadystatechange();
  1944. } else {
  1945. try {
  1946. return original.send.call(this, sourceData);
  1947. } catch(e) {
  1948. debugger;
  1949. }
  1950.  
  1951. }
  1952. };
  1953. /**
  1954. * Processing and substitution of outgoing data
  1955. *
  1956. * Обработка и подмена исходящих данных
  1957. */
  1958. async function checkChangeSend(sourceData, tempData) {
  1959. try {
  1960. /**
  1961. * A function that replaces battle data with incorrect ones to cancel combatя
  1962. *
  1963. * Функция заменяющая данные боя на неверные для отмены боя
  1964. */
  1965. const fixBattle = function (heroes) {
  1966. for (const ids in heroes) {
  1967. hero = heroes[ids];
  1968. hero.energy = random(1, 999);
  1969. if (hero.hp > 0) {
  1970. hero.hp = random(1, hero.hp);
  1971. }
  1972. }
  1973. }
  1974. /**
  1975. * Dialog window 2
  1976. *
  1977. * Диалоговое окно 2
  1978. */
  1979. const showMsg = async function (msg, ansF, ansS) {
  1980. if (typeof popup == 'object') {
  1981. return await popup.confirm(msg, [
  1982. {msg: ansF, result: false},
  1983. {msg: ansS, result: true},
  1984. ]);
  1985. } else {
  1986. return !confirm(`${msg}\n ${ansF} (${I18N('BTN_OK')})\n ${ansS} (${I18N('BTN_CANCEL')})`);
  1987. }
  1988. }
  1989. /**
  1990. * Dialog window 3
  1991. *
  1992. * Диалоговое окно 3
  1993. */
  1994. const showMsgs = async function (msg, ansF, ansS, ansT) {
  1995. return await popup.confirm(msg, [
  1996. {msg: ansF, result: 0},
  1997. {msg: ansS, result: 1},
  1998. {msg: ansT, result: 2},
  1999. ]);
  2000. }
  2001.  
  2002. let changeRequest = false;
  2003. testData = JSON.parse(tempData);
  2004. for (const call of testData.calls) {
  2005. if (!artifactChestOpen) {
  2006. requestHistory[this.uniqid].calls[call.name] = call.ident;
  2007. }
  2008. /**
  2009. * Cancellation of the battle in adventures, on VG and with minions of Asgard
  2010. * Отмена боя в приключениях, на ВГ и с прислужниками Асгарда
  2011. */
  2012. if ((call.name == 'adventure_endBattle' ||
  2013. call.name == 'adventureSolo_endBattle' ||
  2014. call.name == 'clanWarEndBattle' &&
  2015. isChecked('cancelBattle') ||
  2016. call.name == 'crossClanWar_endBattle' &&
  2017. isChecked('cancelBattle') ||
  2018. call.name == 'brawl_endBattle' ||
  2019. call.name == 'towerEndBattle' ||
  2020. call.name == 'invasion_bossEnd' ||
  2021. call.name == 'bossEndBattle' ||
  2022. call.name == 'clanRaid_endNodeBattle') &&
  2023. isCancalBattle) {
  2024. nameFuncEndBattle = call.name;
  2025. if (!call.args.result.win) {
  2026. let resultPopup = false;
  2027. if (call.name == 'adventure_endBattle' ||
  2028. call.name == 'invasion_bossEnd' ||
  2029. call.name == 'bossEndBattle' ||
  2030. call.name == 'adventureSolo_endBattle') {
  2031. resultPopup = await showMsgs(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_CANCEL'), I18N('BTN_AUTO'));
  2032. } else if (call.name == 'clanWarEndBattle' ||
  2033. call.name == 'crossClanWar_endBattle') {
  2034. resultPopup = await showMsg(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_AUTO_F5'));
  2035. } else {
  2036. resultPopup = await showMsg(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_CANCEL'));
  2037. }
  2038. if (resultPopup) {
  2039. if (call.name == 'invasion_bossEnd') {
  2040. this.errorRequest = true;
  2041. }
  2042. fixBattle(call.args.progress[0].attackers.heroes);
  2043. fixBattle(call.args.progress[0].defenders.heroes);
  2044. changeRequest = true;
  2045. if (resultPopup > 1) {
  2046. this.onReadySuccess = testAutoBattle;
  2047. // setTimeout(bossBattle, 1000);
  2048. }
  2049. }
  2050. } else if (call.args.result.stars < 3 && call.name == 'towerEndBattle') {
  2051. resultPopup = await showMsg(I18N('LOST_HEROES'), I18N('BTN_OK'), I18N('BTN_CANCEL'), I18N('BTN_AUTO'));
  2052. if (resultPopup) {
  2053. fixBattle(call.args.progress[0].attackers.heroes);
  2054. fixBattle(call.args.progress[0].defenders.heroes);
  2055. changeRequest = true;
  2056. if (resultPopup > 1) {
  2057. this.onReadySuccess = testAutoBattle;
  2058. }
  2059. }
  2060. }
  2061. // Потасовки
  2062. if (isChecked('autoBrawls') && !isBrawlsAutoStart && call.name == 'brawl_endBattle') {
  2063. if (await popup.confirm(I18N('START_AUTO_BRAWLS'), [
  2064. { msg: I18N('BTN_NO'), result: false },
  2065. { msg: I18N('BTN_YES'), result: true },
  2066. ])) {
  2067. this.onReadySuccess = testBrawls;
  2068. isBrawlsAutoStart = true;
  2069. }
  2070. }
  2071. }
  2072. /**
  2073. * Save pack for Brawls
  2074. *
  2075. * Сохраняем пачку для потасовок
  2076. */
  2077. if (call.name == 'brawl_startBattle') {
  2078. console.log(JSON.stringify(call.args));
  2079. brawlsPack = call.args;
  2080. }
  2081. /**
  2082. * Canceled fight in Asgard
  2083. * Отмена боя в Асгарде
  2084. */
  2085. if (call.name == 'clanRaid_endBossBattle' &&
  2086. isCancalBossBattle &&
  2087. isChecked('cancelBattle')) {
  2088. bossDamage = call.args.progress[0].defenders.heroes[1].extra;
  2089. sumDamage = bossDamage.damageTaken + bossDamage.damageTakenNextLevel;
  2090. let resultPopup = await showMsgs(
  2091. `${I18N('MSG_YOU_APPLIED')} ${sumDamage.toLocaleString()} ${I18N('MSG_DAMAGE')}.`,
  2092. I18N('BTN_OK'), I18N('BTN_AUTO_F5'), I18N('MSG_CANCEL_AND_STAT'))
  2093. if (resultPopup) {
  2094. fixBattle(call.args.progress[0].attackers.heroes);
  2095. fixBattle(call.args.progress[0].defenders.heroes);
  2096. changeRequest = true;
  2097. if (resultPopup > 1) {
  2098. this.onReadySuccess = testBossBattle;
  2099. // setTimeout(bossBattle, 1000);
  2100. }
  2101. }
  2102. }
  2103. /**
  2104. * Save the Asgard Boss Attack Pack
  2105. * Сохраняем пачку для атаки босса Асгарда
  2106. */
  2107. if (call.name == 'clanRaid_startBossBattle') {
  2108. lastBossBattle = call.args;
  2109. }
  2110. /**
  2111. * Saving the request to start the last battle
  2112. * Сохранение запроса начала последнего боя
  2113. */
  2114. if (call.name == 'clanWarAttack' ||
  2115. call.name == 'crossClanWar_startBattle' ||
  2116. call.name == 'adventure_turnStartBattle' ||
  2117. call.name == 'bossAttack' ||
  2118. call.name == 'invasion_bossStart' ||
  2119. call.name == 'towerStartBattle') {
  2120. nameFuncStartBattle = call.name;
  2121. lastBattleArg = call.args;
  2122.  
  2123. if (call.name == 'invasion_bossStart') {
  2124. const timePassed = Date.now() - lastBossBattleStart;
  2125. if (timePassed < invasionTimer) {
  2126. await new Promise((e) => setTimeout(e, invasionTimer - timePassed));
  2127. }
  2128. invasionTimer -= 1;
  2129. }
  2130. lastBossBattleStart = Date.now();
  2131. }
  2132. if (call.name == 'invasion_bossEnd') {
  2133. const lastBattle = lastBattleInfo;
  2134. if (lastBattle && call.args.result.win) {
  2135. lastBattle.progress = call.args.progress;
  2136. const result = await Calc(lastBattle);
  2137. let timer = getTimer(result.battleTime, 1) + addBattleTimer;
  2138. const period = Math.ceil((Date.now() - lastBossBattleStart) / 1000);
  2139. console.log(timer, period);
  2140. if (period < timer) {
  2141. timer = timer - period;
  2142. await countdownTimer(timer);
  2143. }
  2144. }
  2145. }
  2146. /**
  2147. * Disable spending divination cards
  2148. * Отключить трату карт предсказаний
  2149. */
  2150. if (call.name == 'dungeonEndBattle') {
  2151. if (call.args.isRaid) {
  2152. if (countPredictionCard <= 0) {
  2153. delete call.args.isRaid;
  2154. changeRequest = true;
  2155. } else if (countPredictionCard > 0) {
  2156. countPredictionCard--;
  2157. }
  2158. }
  2159. console.log(`Cards: ${countPredictionCard}`);
  2160. /**
  2161. * Fix endless cards
  2162. * Исправление бесконечных карт
  2163. */
  2164. const lastBattle = lastDungeonBattleData;
  2165. if (lastBattle && !call.args.isRaid) {
  2166. if (changeRequest) {
  2167. lastBattle.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  2168. } else {
  2169. lastBattle.progress = call.args.progress;
  2170. }
  2171. const result = await Calc(lastBattle);
  2172.  
  2173. if (changeRequest) {
  2174. call.args.progress = result.progress;
  2175. call.args.result = result.result;
  2176. }
  2177.  
  2178. let timer = getTimer(result.battleTime) + addBattleTimer;
  2179. const period = Math.ceil((Date.now() - lastDungeonBattleStart) / 1000);
  2180. console.log(timer, period);
  2181. if (period < timer) {
  2182. timer = timer - period;
  2183. await countdownTimer(timer);
  2184. }
  2185. }
  2186. }
  2187. /**
  2188. * Quiz Answer
  2189. * Ответ на викторину
  2190. */
  2191. if (call.name == 'quizAnswer') {
  2192. /**
  2193. * Automatically changes the answer to the correct one if there is one.
  2194. * Автоматически меняет ответ на правильный если он есть
  2195. */
  2196. if (lastAnswer && isChecked('getAnswer')) {
  2197. call.args.answerId = lastAnswer;
  2198. lastAnswer = null;
  2199. changeRequest = true;
  2200. }
  2201. }
  2202. /**
  2203. * Present
  2204. * Подарки
  2205. */
  2206. if (call.name == 'freebieCheck') {
  2207. freebieCheckInfo = call;
  2208. }
  2209. /** missionTimer */
  2210. if (call.name == 'missionEnd' && missionBattle) {
  2211. missionBattle.progress = call.args.progress;
  2212. missionBattle.result = call.args.result;
  2213. const result = await Calc(missionBattle);
  2214.  
  2215. let timer = getTimer(result.battleTime) + addBattleTimer;
  2216. const period = Math.ceil((Date.now() - lastMissionBattleStart) / 1000);
  2217. if (period < timer) {
  2218. timer = timer - period;
  2219. await countdownTimer(timer);
  2220. }
  2221. missionBattle = null;
  2222. }
  2223. /**
  2224. * Getting mission data for auto-repeat
  2225. * Получение данных миссии для автоповтора
  2226. */
  2227. if (isChecked('repeatMission') &&
  2228. call.name == 'missionEnd') {
  2229. let missionInfo = {
  2230. id: call.args.id,
  2231. result: call.args.result,
  2232. heroes: call.args.progress[0].attackers.heroes,
  2233. count: 0,
  2234. }
  2235. setTimeout(async () => {
  2236. if (!isSendsMission && await popup.confirm(I18N('MSG_REPEAT_MISSION'), [
  2237. { msg: I18N('BTN_REPEAT'), result: true},
  2238. { msg: I18N('BTN_NO'), result: false},
  2239. ])) {
  2240. isStopSendMission = false;
  2241. isSendsMission = true;
  2242. sendsMission(missionInfo);
  2243. }
  2244. }, 0);
  2245. }
  2246. /**
  2247. * Getting mission data
  2248. * Получение данных миссии
  2249. * missionTimer
  2250. */
  2251. if (call.name == 'missionStart') {
  2252. lastMissionStart = call.args;
  2253. lastMissionBattleStart = Date.now();
  2254. }
  2255.  
  2256. /**
  2257. * Specify the quantity for Titan Orbs and Pet Eggs
  2258. * Указать количество для сфер титанов и яиц петов
  2259. */
  2260. if (isChecked('countControl') &&
  2261. (call.name == 'pet_chestOpen' ||
  2262. call.name == 'titanUseSummonCircle') &&
  2263. call.args.amount > 1) {
  2264. call.args.amount = 1;
  2265. const result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2266. { msg: I18N('BTN_OPEN'), isInput: true, default: call.args.amount},
  2267. ]);
  2268. if (result) {
  2269. call.args.amount = result;
  2270. changeRequest = true;
  2271. }
  2272. }
  2273. /**
  2274. * Specify the amount for keys and spheres of titan artifacts
  2275. * Указать колличество для ключей и сфер артефактов титанов
  2276. */
  2277. if (isChecked('countControl') &&
  2278. (call.name == 'artifactChestOpen' ||
  2279. call.name == 'titanArtifactChestOpen') &&
  2280. call.args.amount > 1 &&
  2281. call.args.free &&
  2282. !changeRequest) {
  2283. artifactChestOpenCallName = call.name;
  2284. let result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2285. { msg: I18N('BTN_OPEN'), isInput: true, default: call.args.amount },
  2286. ]);
  2287. if (result) {
  2288. let sphere = result < 10 ? 1 : 10;
  2289.  
  2290. call.args.amount = sphere;
  2291. result -= sphere;
  2292.  
  2293. for (let count = result; count > 0; count -= sphere) {
  2294. if (count < 10) sphere = 1;
  2295. const ident = artifactChestOpenCallName + "_" + count;
  2296. testData.calls.push({
  2297. name: artifactChestOpenCallName,
  2298. args: {
  2299. amount: sphere,
  2300. free: true,
  2301. },
  2302. ident: ident
  2303. });
  2304. if (!Array.isArray(requestHistory[this.uniqid].calls[call.name])) {
  2305. requestHistory[this.uniqid].calls[call.name] = [requestHistory[this.uniqid].calls[call.name]];
  2306. }
  2307. requestHistory[this.uniqid].calls[call.name].push(ident);
  2308. }
  2309.  
  2310. artifactChestOpen = true;
  2311. changeRequest = true;
  2312. }
  2313. }
  2314. if (call.name == 'consumableUseLootBox') {
  2315. lastRussianDollId = call.args.libId;
  2316. /**
  2317. * Specify quantity for gold caskets
  2318. * Указать количество для золотых шкатулок
  2319. */
  2320. if (isChecked('countControl') &&
  2321. call.args.libId == 148 &&
  2322. call.args.amount > 1) {
  2323. const result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2324. { msg: I18N('BTN_OPEN'), isInput: true, default: call.args.amount},
  2325. ]);
  2326. call.args.amount = result;
  2327. changeRequest = true;
  2328. }
  2329. }
  2330. /**
  2331. * Changing the maximum number of raids in the campaign
  2332. * Изменение максимального количества рейдов в кампании
  2333. */
  2334. // if (call.name == 'missionRaid') {
  2335. // if (isChecked('countControl') && call.args.times > 1) {
  2336. // const result = +(await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2337. // { msg: I18N('BTN_RUN'), isInput: true, default: call.args.times },
  2338. // ]));
  2339. // call.args.times = result > call.args.times ? call.args.times : result;
  2340. // changeRequest = true;
  2341. // }
  2342. // }
  2343. }
  2344.  
  2345. let headers = requestHistory[this.uniqid].headers;
  2346. if (changeRequest) {
  2347. sourceData = JSON.stringify(testData);
  2348. headers['X-Auth-Signature'] = getSignature(headers, sourceData);
  2349. }
  2350.  
  2351. let signature = headers['X-Auth-Signature'];
  2352. if (signature) {
  2353. original.setRequestHeader.call(this, 'X-Auth-Signature', signature);
  2354. }
  2355. } catch (err) {
  2356. console.log("Request(send, " + this.uniqid + "):\n", sourceData, "Error:\n", err);
  2357. }
  2358. return sourceData;
  2359. }
  2360. /**
  2361. * Processing and substitution of incoming data
  2362. *
  2363. * Обработка и подмена входящих данных
  2364. */
  2365. async function checkChangeResponse(response) {
  2366. try {
  2367. isChange = false;
  2368. let nowTime = Math.round(Date.now() / 1000);
  2369. callsIdent = requestHistory[this.uniqid].calls;
  2370. respond = JSON.parse(response);
  2371. /**
  2372. * If the request returned an error removes the error (removes synchronization errors)
  2373. * Если запрос вернул ошибку удаляет ошибку (убирает ошибки синхронизации)
  2374. */
  2375. if (respond.error) {
  2376. isChange = true;
  2377. console.error(respond.error);
  2378. if (isChecked('showErrors')) {
  2379. popup.confirm(I18N('ERROR_MSG', {
  2380. name: respond.error.name,
  2381. description: respond.error.description,
  2382. }));
  2383. }
  2384. delete respond.error;
  2385. respond.results = [];
  2386. }
  2387. let mainReward = null;
  2388. const allReward = {};
  2389. let countTypeReward = 0;
  2390. let readQuestInfo = false;
  2391. for (const call of respond.results) {
  2392. /**
  2393. * Obtaining initial data for completing quests
  2394. * Получение исходных данных для выполнения квестов
  2395. */
  2396. if (readQuestInfo) {
  2397. questsInfo[call.ident] = call.result.response;
  2398. }
  2399. /**
  2400. * Getting a user ID
  2401. * Получение идетификатора пользователя
  2402. */
  2403. if (call.ident == callsIdent['registration']) {
  2404. userId = call.result.response.userId;
  2405. if (localStorage['userId'] != userId) {
  2406. localStorage['newGiftSendIds'] = '';
  2407. localStorage['userId'] = userId;
  2408. }
  2409. await openOrMigrateDatabase(userId);
  2410. readQuestInfo = true;
  2411. }
  2412. /**
  2413. * Hiding donation offers 1
  2414. * Скрываем предложения доната 1
  2415. */
  2416. if (call.ident == callsIdent['billingGetAll'] && getSaveVal('noOfferDonat')) {
  2417. const billings = call.result.response?.billings;
  2418. const bundle = call.result.response?.bundle;
  2419. if (billings && bundle) {
  2420. call.result.response.billings = [];
  2421. call.result.response.bundle = [];
  2422. isChange = true;
  2423. }
  2424. }
  2425. /**
  2426. * Hiding donation offers 2
  2427. * Скрываем предложения доната 2
  2428. */
  2429. if (getSaveVal('noOfferDonat') &&
  2430. (call.ident == callsIdent['offerGetAll'] ||
  2431. call.ident == callsIdent['specialOffer_getAll'])) {
  2432. let offers = call.result.response;
  2433. if (offers) {
  2434. call.result.response = offers.filter(e => !['addBilling', 'bundleCarousel'].includes(e.type) || ['idleResource'].includes(e.offerType));
  2435. isChange = true;
  2436. }
  2437. }
  2438. /**
  2439. * Hiding donation offers 3
  2440. * Скрываем предложения доната 3
  2441. */
  2442. if (getSaveVal('noOfferDonat') && call.result?.bundleUpdate) {
  2443. delete call.result.bundleUpdate;
  2444. isChange = true;
  2445. }
  2446. /**
  2447. * Copies a quiz question to the clipboard
  2448. * Копирует вопрос викторины в буфер обмена и получает на него ответ если есть
  2449. */
  2450. if (call.ident == callsIdent['quizGetNewQuestion']) {
  2451. let quest = call.result.response;
  2452. console.log(quest.question);
  2453. copyText(quest.question);
  2454. setProgress(I18N('QUESTION_COPY'), true);
  2455. quest.lang = null;
  2456. if (typeof NXFlashVars !== 'undefined') {
  2457. quest.lang = NXFlashVars.interface_lang;
  2458. }
  2459. lastQuestion = quest;
  2460. if (isChecked('getAnswer')) {
  2461. const answer = await getAnswer(lastQuestion);
  2462. let showText = '';
  2463. if (answer) {
  2464. lastAnswer = answer;
  2465. console.log(answer);
  2466. showText = `${I18N('ANSWER_KNOWN')}: ${answer}`;
  2467. } else {
  2468. showText = I18N('ANSWER_NOT_KNOWN');
  2469. }
  2470.  
  2471. try {
  2472. const hint = hintQuest(quest);
  2473. if (hint) {
  2474. showText += I18N('HINT') + hint;
  2475. }
  2476. } catch(e) {}
  2477.  
  2478. setProgress(showText, true);
  2479. }
  2480. }
  2481. /**
  2482. * Submits a question with an answer to the database
  2483. * Отправляет вопрос с ответом в базу данных
  2484. */
  2485. if (call.ident == callsIdent['quizAnswer']) {
  2486. const answer = call.result.response;
  2487. if (lastQuestion) {
  2488. const answerInfo = {
  2489. answer,
  2490. question: lastQuestion,
  2491. lang: null,
  2492. }
  2493. if (typeof NXFlashVars !== 'undefined') {
  2494. answerInfo.lang = NXFlashVars.interface_lang;
  2495. }
  2496. lastQuestion = null;
  2497. setTimeout(sendAnswerInfo, 0, answerInfo);
  2498. }
  2499. }
  2500. /**
  2501. * Get user data
  2502. * Получить даныне пользователя
  2503. */
  2504. if (call.ident == callsIdent['userGetInfo']) {
  2505. let user = call.result.response;
  2506. userInfo = Object.assign({}, user);
  2507. delete userInfo.refillable;
  2508. if (!questsInfo['userGetInfo']) {
  2509. questsInfo['userGetInfo'] = user;
  2510. }
  2511. }
  2512. /**
  2513. * Start of the battle for recalculation
  2514. * Начало боя для прерасчета
  2515. */
  2516. if (call.ident == callsIdent['clanWarAttack'] ||
  2517. call.ident == callsIdent['crossClanWar_startBattle'] ||
  2518. call.ident == callsIdent['bossAttack'] ||
  2519. call.ident == callsIdent['battleGetReplay'] ||
  2520. call.ident == callsIdent['brawl_startBattle'] ||
  2521. call.ident == callsIdent['adventureSolo_turnStartBattle'] ||
  2522. call.ident == callsIdent['invasion_bossStart'] ||
  2523. call.ident == callsIdent['towerStartBattle'] ||
  2524. call.ident == callsIdent['adventure_turnStartBattle']) {
  2525. let battle = call.result.response.battle || call.result.response.replay;
  2526. if (call.ident == callsIdent['brawl_startBattle'] ||
  2527. call.ident == callsIdent['bossAttack'] ||
  2528. call.ident == callsIdent['towerStartBattle'] ||
  2529. call.ident == callsIdent['invasion_bossStart']) {
  2530. battle = call.result.response;
  2531. }
  2532. lastBattleInfo = battle;
  2533. if (!isChecked('preCalcBattle')) {
  2534. continue;
  2535. }
  2536. setProgress(I18N('BEING_RECALC'));
  2537. let battleDuration = 120;
  2538. try {
  2539. const typeBattle = getBattleType(battle.type);
  2540. battleDuration = +lib.data.battleConfig[typeBattle.split('_')[1]].config.battleDuration;
  2541. } catch (e) { }
  2542. //console.log(battle.type);
  2543. function getBattleInfo(battle, isRandSeed) {
  2544. return new Promise(function (resolve) {
  2545. if (isRandSeed) {
  2546. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  2547. }
  2548. BattleCalc(battle, getBattleType(battle.type), e => resolve(e));
  2549. });
  2550. }
  2551. let actions = [getBattleInfo(battle, false)]
  2552. const countTestBattle = getInput('countTestBattle');
  2553. if (call.ident == callsIdent['battleGetReplay']) {
  2554. battle.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  2555. }
  2556. for (let i = 0; i < countTestBattle; i++) {
  2557. actions.push(getBattleInfo(battle, true));
  2558. }
  2559. Promise.all(actions)
  2560. .then(e => {
  2561. e = e.map(n => ({win: n.result.win, time: n.battleTime}));
  2562. let firstBattle = e.shift();
  2563. const timer = Math.floor(battleDuration - firstBattle.time);
  2564. const min = ('00' + Math.floor(timer / 60)).slice(-2);
  2565. const sec = ('00' + Math.floor(timer - min * 60)).slice(-2);
  2566. const countWin = e.reduce((w, s) => w + s.win, 0);
  2567. 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)
  2568. });
  2569. }
  2570. //тест сохранки
  2571. /** Запоминаем команды в реплее*/
  2572. if (call.ident == callsIdent['battleGetReplay']) {
  2573. let battle = call.result.response.replay;
  2574. repleyBattle.attackers = battle.attackers;
  2575. repleyBattle.defenders = battle.defenders[0];
  2576. repleyBattle.effects = battle.effects.defenders;
  2577. repleyBattle.state = battle.progress[0].defenders.heroes;
  2578. repleyBattle.seed = battle.seed;
  2579. }
  2580. /** Нападение в турнире*/
  2581. if (call.ident == callsIdent['titanArenaStartBattle']) {
  2582. let bestBattle = getInput('countBattle');
  2583. let unrandom = getInput('needResource');
  2584. let maxPower = getInput('needResource2');
  2585. if (bestBattle * unrandom * maxPower == 0) {
  2586. let battle = call.result.response.battle;
  2587. if (bestBattle == 0) {
  2588. battle.progress = bestLordBattle[battle.typeId]?.progress;
  2589. }
  2590. if (unrandom == 0 && !!repleyBattle.seed) {
  2591. battle.seed = repleyBattle.seed;
  2592. }
  2593. if (maxPower == 0) {
  2594. battle.attackers = getTitansPack(Object.keys(battle.attackers));
  2595. }
  2596. isChange = true;
  2597. }
  2598. }
  2599. /** Тест боев с усилениями команд защиты*/
  2600. if (call.ident == callsIdent['chatAcceptChallenge']) {
  2601. let battle = call.result.response.battle;
  2602. addBuff(battle);
  2603. let testType = getInput('countBattle');
  2604. if (testType.slice(0, 1) == "-") {
  2605. testType = parseInt(testType.slice(1), 10);
  2606. switch (testType) {
  2607. case 1:
  2608. battle.defenders[0] = repleyBattle.defenders;
  2609. break; //наша атака против защиты из реплея
  2610. case 2:
  2611. battle.defenders[0] = repleyBattle.attackers;
  2612. break; //наша атака против атаки из реплея
  2613. case 3:
  2614. battle.attackers = repleyBattle.attackers;
  2615. break; //атака из реплея против защиты в чате
  2616. case 4:
  2617. battle.attackers = repleyBattle.defenders;
  2618. break; //защита из реплея против защиты в чате
  2619. case 5:
  2620. battle.attackers = repleyBattle.attackers;
  2621. battle.defenders[0] = repleyBattle.defenders;
  2622. break; //атака из реплея против защиты из реплея
  2623. case 6:
  2624. battle.attackers = repleyBattle.defenders;
  2625. battle.defenders[0] = repleyBattle.attackers;
  2626. break; //защита из реплея против атаки из реплея
  2627. case 7:
  2628. battle.attackers = repleyBattle.attackers;
  2629. battle.defenders[0] = repleyBattle.attackers;
  2630. break; //атака из реплея против атаки из реплея
  2631. case 8:
  2632. battle.attackers = repleyBattle.defenders;
  2633. battle.defenders[0] = repleyBattle.defenders;
  2634. break; //защита из реплея против защиты из реплея
  2635. }
  2636. }
  2637.  
  2638. isChange = true;
  2639. }
  2640. /** Тест боев с усилениями команд защиты тренировках*/
  2641. if (call.ident == callsIdent['demoBattles_startBattle']) {
  2642. let battle = call.result.response.battle;
  2643. addBuff(battle);
  2644. let testType = getInput('countBattle');
  2645. if (testType.slice(0, 1) == "-") {
  2646. testType = parseInt(testType.slice(1), 10);
  2647. switch (testType) {
  2648. case 1:
  2649. battle.defenders[0] = repleyBattle.defenders;
  2650. break; //наша атака против защиты из реплея
  2651. case 2:
  2652. battle.defenders[0] = repleyBattle.attackers;
  2653. break; //наша атака против атаки из реплея
  2654. case 3:
  2655. battle.attackers = repleyBattle.attackers;
  2656. break; //атака из реплея против защиты в чате
  2657. case 4:
  2658. battle.attackers = repleyBattle.defenders;
  2659. break; //защита из реплея против защиты в чате
  2660. case 5:
  2661. battle.attackers = repleyBattle.attackers;
  2662. battle.defenders[0] = repleyBattle.defenders;
  2663. break; //атака из реплея против защиты из реплея
  2664. case 6:
  2665. battle.attackers = repleyBattle.defenders;
  2666. battle.defenders[0] = repleyBattle.attackers;
  2667. break; //защита из реплея против атаки из реплея
  2668. case 7:
  2669. battle.attackers = repleyBattle.attackers;
  2670. battle.defenders[0] = repleyBattle.attackers;
  2671. break; //атака из реплея против атаки из реплея
  2672. case 8:
  2673. battle.attackers = repleyBattle.defenders;
  2674. battle.defenders[0] = repleyBattle.defenders;
  2675. break; //защита из реплея против защиты из реплея
  2676. }
  2677. }
  2678.  
  2679. isChange = true;
  2680. }
  2681. //тест сохранки
  2682. /**
  2683. * Start of the Asgard boss fight
  2684. * Начало боя с боссом Асгарда
  2685. */
  2686. if (call.ident == callsIdent['clanRaid_startBossBattle']) {
  2687. lastBossBattleInfo = call.result.response.battle;
  2688. if (isChecked('preCalcBattle')) {
  2689. const result = await Calc(lastBossBattleInfo).then(e => e.progress[0].defenders.heroes[1].extra);
  2690. const bossDamage = result.damageTaken + result.damageTakenNextLevel;
  2691. setProgress(I18N('BOSS_DAMAGE') + bossDamage.toLocaleString(), false, hideProgress);
  2692. }
  2693. }
  2694. /**
  2695. * Cancel tutorial
  2696. * Отмена туториала
  2697. */
  2698. if (isCanceledTutorial && call.ident == callsIdent['tutorialGetInfo']) {
  2699. let chains = call.result.response.chains;
  2700. for (let n in chains) {
  2701. chains[n] = 9999;
  2702. }
  2703. isChange = true;
  2704. }
  2705. /**
  2706. * Opening keys and spheres of titan artifacts
  2707. * Открытие ключей и сфер артефактов титанов
  2708. */
  2709. if (artifactChestOpen &&
  2710. (call.ident == callsIdent[artifactChestOpenCallName] ||
  2711. (callsIdent[artifactChestOpenCallName] && callsIdent[artifactChestOpenCallName].includes(call.ident)))) {
  2712. let reward = call.result.response[artifactChestOpenCallName == 'artifactChestOpen' ? 'chestReward' : 'reward'];
  2713.  
  2714. reward.forEach(e => {
  2715. for (let f in e) {
  2716. if (!allReward[f]) {
  2717. allReward[f] = {};
  2718. }
  2719. for (let o in e[f]) {
  2720. if (!allReward[f][o]) {
  2721. allReward[f][o] = e[f][o];
  2722. countTypeReward++;
  2723. } else {
  2724. allReward[f][o] += e[f][o];
  2725. }
  2726. }
  2727. }
  2728. });
  2729.  
  2730. if (!call.ident.includes(artifactChestOpenCallName)) {
  2731. mainReward = call.result.response;
  2732. }
  2733. }
  2734.  
  2735. if (countTypeReward > 20) {
  2736. correctShowOpenArtifact = 3;
  2737. } else {
  2738. correctShowOpenArtifact = 0;
  2739. }
  2740.  
  2741. /**
  2742. * Sum the result of opening Pet Eggs
  2743. * Суммирование результата открытия яиц питомцев
  2744. */
  2745. if (isChecked('countControl') && call.ident == callsIdent['pet_chestOpen']) {
  2746. const rewards = call.result.response.rewards;
  2747. if (rewards.length > 10) {
  2748. /**
  2749. * Removing pet cards
  2750. * Убираем карточки петов
  2751. */
  2752. for (const reward of rewards) {
  2753. if (reward.petCard) {
  2754. delete reward.petCard;
  2755. }
  2756. }
  2757. }
  2758. rewards.forEach(e => {
  2759. for (let f in e) {
  2760. if (!allReward[f]) {
  2761. allReward[f] = {};
  2762. }
  2763. for (let o in e[f]) {
  2764. if (!allReward[f][o]) {
  2765. allReward[f][o] = e[f][o];
  2766. } else {
  2767. allReward[f][o] += e[f][o];
  2768. }
  2769. }
  2770. }
  2771. });
  2772. call.result.response.rewards = [allReward];
  2773. isChange = true;
  2774. }
  2775. /**
  2776. * Removing titan cards
  2777. * Убираем карточки титанов
  2778. */
  2779. if (call.ident == callsIdent['titanUseSummonCircle']) {
  2780. if (call.result.response.rewards.length > 10) {
  2781. for (const reward of call.result.response.rewards) {
  2782. if (reward.titanCard) {
  2783. delete reward.titanCard;
  2784. }
  2785. }
  2786. isChange = true;
  2787. }
  2788. }
  2789. /**
  2790. * Auto-repeat opening matryoshkas
  2791. * АвтоПовтор открытия матрешек
  2792. */
  2793. if (isChecked('countControl') && call.ident == callsIdent['consumableUseLootBox']) {
  2794. let lootBox = call.result.response;
  2795. let newCount = 0;
  2796. for (let n of lootBox) {
  2797. if (n?.consumable && n.consumable[lastRussianDollId]) {
  2798. newCount += n.consumable[lastRussianDollId]
  2799. }
  2800. }
  2801. if (newCount && await popup.confirm(`${I18N('BTN_OPEN')} ${newCount} ${I18N('OPEN_DOLLS')}?`, [
  2802. { msg: I18N('BTN_OPEN'), result: true},
  2803. { msg: I18N('BTN_NO'), result: false},
  2804. ])) {
  2805. const recursionResult = await openRussianDolls(lastRussianDollId, newCount);
  2806. lootBox = [...lootBox, ...recursionResult];
  2807. }
  2808.  
  2809. /** Объединение результата лутбоксов */
  2810. const allLootBox = {};
  2811. lootBox.forEach(e => {
  2812. for (let f in e) {
  2813. if (!allLootBox[f]) {
  2814. if (typeof e[f] == 'object') {
  2815. allLootBox[f] = {};
  2816. } else {
  2817. allLootBox[f] = 0;
  2818. }
  2819. }
  2820. if (typeof e[f] == 'object') {
  2821. for (let o in e[f]) {
  2822. if (newCount && o == lastRussianDollId) {
  2823. continue;
  2824. }
  2825. if (!allLootBox[f][o]) {
  2826. allLootBox[f][o] = e[f][o];
  2827. } else {
  2828. allLootBox[f][o] += e[f][o];
  2829. }
  2830. }
  2831. } else {
  2832. allLootBox[f] += e[f];
  2833. }
  2834. }
  2835. });
  2836. /** Разбитие результата */
  2837. const output = [];
  2838. const maxCount = 5;
  2839. let currentObj = {};
  2840. let count = 0;
  2841. for (let f in allLootBox) {
  2842. if (!currentObj[f]) {
  2843. if (typeof allLootBox[f] == 'object') {
  2844. for (let o in allLootBox[f]) {
  2845. currentObj[f] ||= {}
  2846. if (!currentObj[f][o]) {
  2847. currentObj[f][o] = allLootBox[f][o];
  2848. count++;
  2849. if (count === maxCount) {
  2850. output.push(currentObj);
  2851. currentObj = {};
  2852. count = 0;
  2853. }
  2854. }
  2855. }
  2856. } else {
  2857. currentObj[f] = allLootBox[f];
  2858. count++;
  2859. if (count === maxCount) {
  2860. output.push(currentObj);
  2861. currentObj = {};
  2862. count = 0;
  2863. }
  2864. }
  2865. }
  2866. }
  2867. if (count > 0) {
  2868. output.push(currentObj);
  2869. }
  2870.  
  2871. console.log(output);
  2872. call.result.response = output;
  2873. isChange = true;
  2874. }
  2875. /**
  2876. * Dungeon recalculation (fix endless cards)
  2877. * Прерасчет подземки (исправление бесконечных карт)
  2878. */
  2879. if (call.ident == callsIdent['dungeonStartBattle']) {
  2880. lastDungeonBattleData = call.result.response;
  2881. lastDungeonBattleStart = Date.now();
  2882. }
  2883. /**
  2884. * Getting the number of prediction cards
  2885. * Получение количества карт предсказаний
  2886. */
  2887. if (call.ident == callsIdent['inventoryGet']) {
  2888. countPredictionCard = call.result.response.consumable[81] || 0;
  2889. }
  2890. /**
  2891. * Getting subscription status
  2892. * Получение состояния подписки
  2893. */
  2894. if (call.ident == callsIdent['subscriptionGetInfo']) {
  2895. const subscription = call.result.response.subscription;
  2896. if (subscription) {
  2897. subEndTime = subscription.endTime * 1000;
  2898. }
  2899. }
  2900. /**
  2901. * Getting prediction cards
  2902. * Получение карт предсказаний
  2903. */
  2904. if (call.ident == callsIdent['questFarm']) {
  2905. const consumable = call.result.response?.consumable;
  2906. if (consumable && consumable[81]) {
  2907. countPredictionCard += consumable[81];
  2908. console.log(`Cards: ${countPredictionCard}`);
  2909. }
  2910. }
  2911. /**
  2912. * Hiding extra servers
  2913. * Скрытие лишних серверов
  2914. */
  2915. if (call.ident == callsIdent['serverGetAll'] && isChecked('hideServers')) {
  2916. let servers = call.result.response.users.map(s => s.serverId)
  2917. call.result.response.servers = call.result.response.servers.filter(s => servers.includes(s.id));
  2918. isChange = true;
  2919. }
  2920. /**
  2921. * Displays player positions in the adventure
  2922. * Отображает позиции игроков в приключении
  2923. */
  2924. if (call.ident == callsIdent['adventure_getLobbyInfo']) {
  2925. const users = Object.values(call.result.response.users);
  2926. const mapIdent = call.result.response.mapIdent;
  2927. const adventureId = call.result.response.adventureId;
  2928. const maps = {
  2929. adv_strongford_3pl_hell: 9,
  2930. adv_valley_3pl_hell: 10,
  2931. adv_ghirwil_3pl_hell: 11,
  2932. adv_angels_3pl_hell: 12,
  2933. }
  2934. let msg = I18N('MAP') + (mapIdent in maps ? maps[mapIdent] : adventureId);
  2935. msg += '<br>' + I18N('PLAYER_POS');
  2936. for (const user of users) {
  2937. msg += `<br>${user.user.name} - ${user.currentNode}`;
  2938. }
  2939. setProgress(msg, false, hideProgress);
  2940. }
  2941. /**
  2942. * Automatic launch of a raid at the end of the adventure
  2943. * Автоматический запуск рейда при окончании приключения
  2944. */
  2945. if (call.ident == callsIdent['adventure_end']) {
  2946. autoRaidAdventure()
  2947. }
  2948. /** Удаление лавки редкостей */
  2949. if (call.ident == callsIdent['missionRaid']) {
  2950. if (call.result?.heroesMerchant) {
  2951. delete call.result.heroesMerchant;
  2952. isChange = true;
  2953. }
  2954. }
  2955. /** missionTimer */
  2956. if (call.ident == callsIdent['missionStart']) {
  2957. missionBattle = call.result.response;
  2958. }
  2959. }
  2960.  
  2961. if (mainReward && artifactChestOpen) {
  2962. console.log(allReward);
  2963. mainReward[artifactChestOpenCallName == 'artifactChestOpen' ? 'chestReward' : 'reward'] = [allReward];
  2964. artifactChestOpen = false;
  2965. artifactChestOpenCallName = '';
  2966. isChange = true;
  2967. }
  2968. } catch(err) {
  2969. console.log("Request(response, " + this.uniqid + "):\n", "Error:\n", response, err);
  2970. }
  2971.  
  2972. if (isChange) {
  2973. Object.defineProperty(this, 'responseText', {
  2974. writable: true
  2975. });
  2976. this.responseText = JSON.stringify(respond);
  2977. }
  2978. }
  2979.  
  2980. /** Добавляет в бой эффекты усиления*/
  2981. function addBuff(battle) {
  2982. let effects = battle.effects;
  2983. let buffType = getInput('needResource2');
  2984. if (-1 < buffType && buffType < 7) {
  2985. let percentBuff = getInput('needResource');
  2986. effects.defenders = {};
  2987. effects.defenders[buffs[buffType]] = percentBuff;
  2988. } else if (buffType.slice(0, 1) == "-" || isChecked('treningBattle')) {
  2989. buffType = parseInt(buffType.slice(1), 10);
  2990. effects.defenders = repleyBattle.effects;
  2991. battle.defenders[0] = repleyBattle.defenders;
  2992. let def = battle.defenders[0];
  2993. if (buffType == 1) {
  2994. for (let i in def) {
  2995. let state = def[i].state;
  2996. state.hp = state.maxHp;
  2997. state.energy = 0;
  2998. state.isDead = false;
  2999. }
  3000. } else if (buffType == 2 || isChecked('finishingBattle')) {
  3001. for (let i in def) {
  3002. let state = def[i].state;
  3003. let rState = repleyBattle.state[i];
  3004. if (!!rState) {
  3005. state.hp = rState.hp;
  3006. state.energy = rState.energy;
  3007. state.isDead = rState.isDead;
  3008. } else {
  3009. state.hp = 0;
  3010. state.energy = 0;
  3011. state.isDead = true;
  3012. }
  3013. }
  3014. }
  3015. }
  3016. }
  3017. 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'];
  3018.  
  3019. /**
  3020. * Request an answer to a question
  3021. *
  3022. * Запрос ответа на вопрос
  3023. */
  3024. async function getAnswer(question) {
  3025. const now = Date.now();
  3026. const body = JSON.stringify({ ...question, now });
  3027. const signature = window['\x73\x69\x67\x6e'](now);
  3028. return new Promise(resolve => {
  3029. fetch('https://zingery.ru/heroes/getAnswer.php', {
  3030. method: 'POST',
  3031. headers: {
  3032. 'X-Request-Signature': signature,
  3033. 'X-Script-Name': GM_info.script.name,
  3034. 'X-Script-Version': GM_info.script.version,
  3035. 'X-Script-Author': GM_info.script.author,
  3036. },
  3037. body,
  3038. }).then(
  3039. response => response.json()
  3040. ).then(
  3041. data => {
  3042. if (data.result) {
  3043. resolve(data.result);
  3044. } else {
  3045. resolve(false);
  3046. }
  3047. }
  3048. ).catch((error) => {
  3049. console.error(error);
  3050. resolve(false);
  3051. });
  3052. })
  3053. }
  3054.  
  3055. /**
  3056. * Submitting a question and answer to a database
  3057. *
  3058. * Отправка вопроса и ответа в базу данных
  3059. */
  3060. function sendAnswerInfo(answerInfo) {
  3061. fetch('https://zingery.ru/heroes/setAnswer.php', {
  3062. method: 'POST',
  3063. body: JSON.stringify(answerInfo)
  3064. }).then(
  3065. response => response.json()
  3066. ).then(
  3067. data => {
  3068. if (data.result) {
  3069. console.log(I18N('SENT_QUESTION'));
  3070. }
  3071. }
  3072. )
  3073. }
  3074.  
  3075. /**
  3076. * Returns the battle type by preset type
  3077. *
  3078. * Возвращает тип боя по типу пресета
  3079. */
  3080. function getBattleType(strBattleType) {
  3081. if (strBattleType.includes("invasion")) {
  3082. return "get_invasion";
  3083. }
  3084. if (strBattleType.includes("boss")) {
  3085. return "get_boss";
  3086. }
  3087. switch (strBattleType) {
  3088. case "invasion":
  3089. return "get_invasion";
  3090. case "titan_pvp_manual":
  3091. return "get_titanPvpManual";
  3092. case "titan_pvp":
  3093. return "get_titanPvp";
  3094. case "titan_clan_pvp":
  3095. case "clan_pvp_titan":
  3096. case "clan_global_pvp_titan":
  3097. case "brawl_titan":
  3098. case "challenge_titan":
  3099. return "get_titanClanPvp";
  3100. case "clan_raid": // Asgard Boss // Босс асгарда
  3101. case "adventure": // Adventures // Приключения
  3102. case "clan_global_pvp":
  3103. case "clan_pvp":
  3104. return "get_clanPvp";
  3105. case "dungeon_titan":
  3106. case "titan_tower":
  3107. return "get_titan";
  3108. case "tower":
  3109. case "clan_dungeon":
  3110. return "get_tower";
  3111. case "pve":
  3112. return "get_pve";
  3113. case "pvp_manual":
  3114. return "get_pvpManual";
  3115. case "grand":
  3116. case "arena":
  3117. case "pvp":
  3118. case "challenge":
  3119. return "get_pvp";
  3120. case "core":
  3121. return "get_core";
  3122. case "boss_10":
  3123. case "boss_11":
  3124. case "boss_12":
  3125. return "get_boss";
  3126. default:
  3127. return "get_clanPvp";
  3128. }
  3129. }
  3130. /**
  3131. * Returns the class name of the passed object
  3132. *
  3133. * Возвращает название класса переданного объекта
  3134. */
  3135. function getClass(obj) {
  3136. return {}.toString.call(obj).slice(8, -1);
  3137. }
  3138. /**
  3139. * Calculates the request signature
  3140. *
  3141. * Расчитывает сигнатуру запроса
  3142. */
  3143. this.getSignature = function(headers, data) {
  3144. const sign = {
  3145. signature: '',
  3146. length: 0,
  3147. add: function (text) {
  3148. this.signature += text;
  3149. if (this.length < this.signature.length) {
  3150. this.length = 3 * (this.signature.length + 1) >> 1;
  3151. }
  3152. },
  3153. }
  3154. sign.add(headers["X-Request-Id"]);
  3155. sign.add(':');
  3156. sign.add(headers["X-Auth-Token"]);
  3157. sign.add(':');
  3158. sign.add(headers["X-Auth-Session-Id"]);
  3159. sign.add(':');
  3160. sign.add(data);
  3161. sign.add(':');
  3162. sign.add('LIBRARY-VERSION=1');
  3163. sign.add('UNIQUE-SESSION-ID=' + headers["X-Env-Unique-Session-Id"]);
  3164.  
  3165. return md5(sign.signature);
  3166. }
  3167. /**
  3168. * Creates an interface
  3169. *
  3170. * Создает интерфейс
  3171. */
  3172. function createInterface() {
  3173. scriptMenu.init({
  3174. showMenu: true
  3175. });
  3176. scriptMenu.addHeader(GM_info.script.name, justInfo);
  3177. scriptMenu.addHeader('v' + GM_info.script.version);
  3178. }
  3179.  
  3180. function addControls() {
  3181. createInterface();
  3182. const checkboxDetails = scriptMenu.addDetails(I18N('SETTINGS'));
  3183. for (let name in checkboxes) {
  3184. if (checkboxes[name].hide) {
  3185. continue;
  3186. }
  3187. checkboxes[name].cbox = scriptMenu.addCheckbox(checkboxes[name].label, checkboxes[name].title, checkboxDetails);
  3188. /**
  3189. * Getting the state of checkboxes from storage
  3190. * Получаем состояние чекбоксов из storage
  3191. */
  3192. let val = storage.get(name, null);
  3193. if (val != null) {
  3194. checkboxes[name].cbox.checked = val;
  3195. } else {
  3196. storage.set(name, checkboxes[name].default);
  3197. checkboxes[name].cbox.checked = checkboxes[name].default;
  3198. }
  3199. /**
  3200. * Tracing the change event of the checkbox for writing to storage
  3201. * Отсеживание события изменения чекбокса для записи в storage
  3202. */
  3203. checkboxes[name].cbox.dataset['name'] = name;
  3204. checkboxes[name].cbox.addEventListener('change', async function (event) {
  3205. const nameCheckbox = this.dataset['name'];
  3206. /*
  3207. if (this.checked && nameCheckbox == 'cancelBattle') {
  3208. this.checked = false;
  3209. if (await popup.confirm(I18N('MSG_BAN_ATTENTION'), [
  3210. { msg: I18N('BTN_NO_I_AM_AGAINST'), result: true },
  3211. { msg: I18N('BTN_YES_I_AGREE'), result: false },
  3212. ])) {
  3213. return;
  3214. }
  3215. this.checked = true;
  3216. }
  3217. */
  3218. storage.set(nameCheckbox, this.checked);
  3219. })
  3220. }
  3221.  
  3222. const inputDetails = scriptMenu.addDetails(I18N('VALUES'));
  3223. for (let name in inputs) {
  3224. inputs[name].input = scriptMenu.addInputText(inputs[name].title, false, inputDetails);
  3225. /**
  3226. * Get inputText state from storage
  3227. * Получаем состояние inputText из storage
  3228. */
  3229. let val = storage.get(name, null);
  3230. if (val != null) {
  3231. inputs[name].input.value = val;
  3232. } else {
  3233. storage.set(name, inputs[name].default);
  3234. inputs[name].input.value = inputs[name].default;
  3235. }
  3236. /**
  3237. * Tracing a field change event for a record in storage
  3238. * Отсеживание события изменения поля для записи в storage
  3239. */
  3240. inputs[name].input.dataset['name'] = name;
  3241. inputs[name].input.addEventListener('input', function () {
  3242. const inputName = this.dataset['name'];
  3243. let value = +this.value;
  3244. if (!value || Number.isNaN(value)) {
  3245. value = storage.get(inputName, inputs[inputName].default);
  3246. inputs[name].input.value = value;
  3247. }
  3248. storage.set(inputName, value);
  3249. })
  3250. }
  3251. const inputDetails2 = scriptMenu.addDetails(I18N('SAVING'));
  3252. for (let name in inputs2) {
  3253. inputs2[name].input = scriptMenu.addInputText(inputs2[name].title, false, inputDetails2);
  3254. /**
  3255. * Get inputText state from storage
  3256. * Получаем состояние inputText из storage
  3257. */
  3258. let val = storage.get(name, null);
  3259. if (val != null) {
  3260. inputs2[name].input.value = val;
  3261. } else {
  3262. storage.set(name, inputs2[name].default);
  3263. inputs2[name].input.value = inputs2[name].default;
  3264. }
  3265. /**
  3266. * Tracing a field change event for a record in storage
  3267. * Отсеживание события изменения поля для записи в storage
  3268. */
  3269. inputs2[name].input.dataset['name'] = name;
  3270. inputs2[name].input.addEventListener('input', function () {
  3271. const inputName = this.dataset['name'];
  3272. let value = +this.value;
  3273. if (!value || Number.isNaN(value)) {
  3274. value = storage.get(inputName, inputs2[inputName].default);
  3275. inputs2[name].input.value = value;
  3276. }
  3277. storage.set(inputName, value);
  3278. })
  3279. }
  3280. /* const inputDetails3 = scriptMenu.addDetails(I18N('USER_ID'));
  3281. for (let name in inputs3) {
  3282. inputs3[name].input = scriptMenu.addInputText(inputs3[name].title, false, inputDetails3);
  3283. /**
  3284. * Get inputText state from storage
  3285. * Получаем состояние inputText из storage
  3286. *
  3287. let val = storage.get(name, null);
  3288. if (val != null) {
  3289. inputs3[name].input.value = val;
  3290. } else {
  3291. storage.set(name, inputs3[name].default);
  3292. inputs3[name].input.value = inputs3[name].default;
  3293. }
  3294. /**
  3295. * Tracing a field change event for a record in storage
  3296. * Отсеживание события изменения поля для записи в storage
  3297. *
  3298. inputs3[name].input.dataset['name'] = name;
  3299. inputs3[name].input.addEventListener('input', function () {
  3300. const inputName = this.dataset['name'];
  3301. let value = +this.value;
  3302. if (!value || Number.isNaN(value)) {
  3303. value = storage.get(inputName, inputs3[inputName].default);
  3304. inputs3[name].input.value = value;
  3305. }
  3306. storage.set(inputName, value);
  3307. })
  3308. }*/
  3309. }
  3310.  
  3311. /**
  3312. * Sending a request
  3313. *
  3314. * Отправка запроса
  3315. */
  3316. function send(json, callback, pr) {
  3317. if (typeof json == 'string') {
  3318. json = JSON.parse(json);
  3319. }
  3320. for (const call of json.calls) {
  3321. if (!call?.context?.actionTs) {
  3322. call.context = {
  3323. actionTs: Math.floor(performance.now())
  3324. }
  3325. }
  3326. }
  3327. json = JSON.stringify(json);
  3328. /**
  3329. * We get the headlines of the previous intercepted request
  3330. * Получаем заголовки предыдущего перехваченого запроса
  3331. */
  3332. let headers = lastHeaders;
  3333. /**
  3334. * We increase the header of the query Certifier by 1
  3335. * Увеличиваем заголовок идетификатора запроса на 1
  3336. */
  3337. headers["X-Request-Id"]++;
  3338. /**
  3339. * We calculate the title with the signature
  3340. * Расчитываем заголовок с сигнатурой
  3341. */
  3342. headers["X-Auth-Signature"] = getSignature(headers, json);
  3343. /**
  3344. * Create a new ajax request
  3345. * Создаем новый AJAX запрос
  3346. */
  3347. let xhr = new XMLHttpRequest;
  3348. /**
  3349. * Indicate the previously saved URL for API queries
  3350. * Указываем ранее сохраненный URL для API запросов
  3351. */
  3352. xhr.open('POST', apiUrl, true);
  3353. /**
  3354. * Add the function to the event change event
  3355. * Добавляем функцию к событию смены статуса запроса
  3356. */
  3357. xhr.onreadystatechange = function() {
  3358. /**
  3359. * If the result of the request is obtained, we call the flask function
  3360. * Если результат запроса получен вызываем колбек функцию
  3361. */
  3362. if(xhr.readyState == 4) {
  3363. callback(xhr.response, pr);
  3364. }
  3365. };
  3366. /**
  3367. * Indicate the type of request
  3368. * Указываем тип запроса
  3369. */
  3370. xhr.responseType = 'json';
  3371. /**
  3372. * We set the request headers
  3373. * Задаем заголовки запроса
  3374. */
  3375. for(let nameHeader in headers) {
  3376. let head = headers[nameHeader];
  3377. xhr.setRequestHeader(nameHeader, head);
  3378. }
  3379. /**
  3380. * Sending a request
  3381. * Отправляем запрос
  3382. */
  3383. xhr.send(json);
  3384. }
  3385.  
  3386. let hideTimeoutProgress = 0;
  3387. /**
  3388. * Hide progress
  3389. *
  3390. * Скрыть прогресс
  3391. */
  3392. function hideProgress(timeout) {
  3393. timeout = timeout || 0;
  3394. clearTimeout(hideTimeoutProgress);
  3395. hideTimeoutProgress = setTimeout(function () {
  3396. scriptMenu.setStatus('');
  3397. }, timeout);
  3398. }
  3399. /**
  3400. * Progress display
  3401. *
  3402. * Отображение прогресса
  3403. */
  3404. function setProgress(text, hide, onclick) {
  3405. scriptMenu.setStatus(text, onclick);
  3406. hide = hide || false;
  3407. if (hide) {
  3408. hideProgress(3000);
  3409. }
  3410. }
  3411.  
  3412. /**
  3413. * Returns the timer value depending on the subscription
  3414. *
  3415. * Возвращает значение таймера в зависимости от подписки
  3416. */
  3417. function getTimer(time, div) {
  3418. let speedDiv = 5;
  3419. if (subEndTime < Date.now()) {
  3420. speedDiv = div || 1.5;
  3421. }
  3422. return Math.max(Math.ceil(time / speedDiv + 1.5), 4);
  3423. }
  3424.  
  3425. /**
  3426. * Calculates HASH MD5 from string
  3427. *
  3428. * Расчитывает HASH MD5 из строки
  3429. *
  3430. * [js-md5]{@link https://github.com/emn178/js-md5}
  3431. *
  3432. * @namespace md5
  3433. * @version 0.7.3
  3434. * @author Chen, Yi-Cyuan [emn178@gmail.com]
  3435. * @copyright Chen, Yi-Cyuan 2014-2017
  3436. * @license MIT
  3437. */
  3438. !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 _}))}();
  3439.  
  3440. /**
  3441. * Script for beautiful dialog boxes
  3442. *
  3443. * Скрипт для красивых диалоговых окошек
  3444. */
  3445. const popup = new (function () {
  3446. this.popUp,
  3447. this.downer,
  3448. this.middle,
  3449. this.msgText,
  3450. this.buttons = [];
  3451. this.checkboxes = [];
  3452. this.dialogPromice = null;
  3453.  
  3454. function init() {
  3455. addStyle();
  3456. addBlocks();
  3457. addEventListeners();
  3458. }
  3459.  
  3460. const addEventListeners = () => {
  3461. document.addEventListener('keyup', (e) => {
  3462. if (e.key == 'Escape') {
  3463. if (this.dialogPromice) {
  3464. const { func, result } = this.dialogPromice;
  3465. this.dialogPromice = null;
  3466. popup.hide();
  3467. func(result);
  3468. }
  3469. }
  3470. });
  3471. }
  3472.  
  3473. const addStyle = () => {
  3474. let style = document.createElement('style');
  3475. style.innerText = `
  3476. .PopUp_ {
  3477. position: absolute;
  3478. min-width: 300px;
  3479. max-width: 500px;
  3480. max-height: 600px;
  3481. background-color: #190e08e6;
  3482. z-index: 10001;
  3483. top: 169px;
  3484. left: 345px;
  3485. border: 3px #ce9767 solid;
  3486. border-radius: 10px;
  3487. display: flex;
  3488. flex-direction: column;
  3489. justify-content: space-around;
  3490. padding: 15px 9px;
  3491. box-sizing: border-box;
  3492. }
  3493.  
  3494. .PopUp_back {
  3495. position: absolute;
  3496. background-color: #00000066;
  3497. width: 100%;
  3498. height: 100%;
  3499. z-index: 10000;
  3500. top: 0;
  3501. left: 0;
  3502. }
  3503.  
  3504. .PopUp_close {
  3505. width: 40px;
  3506. height: 40px;
  3507. position: absolute;
  3508. right: -18px;
  3509. top: -18px;
  3510. border: 3px solid #c18550;
  3511. border-radius: 20px;
  3512. background: radial-gradient(circle, rgba(190,30,35,1) 0%, rgba(0,0,0,1) 100%);
  3513. background-position-y: 3px;
  3514. box-shadow: -1px 1px 3px black;
  3515. cursor: pointer;
  3516. box-sizing: border-box;
  3517. }
  3518.  
  3519. .PopUp_close:hover {
  3520. filter: brightness(1.2);
  3521. }
  3522.  
  3523. .PopUp_crossClose {
  3524. width: 100%;
  3525. height: 100%;
  3526. background-size: 65%;
  3527. background-position: center;
  3528. background-repeat: no-repeat;
  3529. 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")
  3530. }
  3531.  
  3532. .PopUp_blocks {
  3533. width: 100%;
  3534. height: 50%;
  3535. display: flex;
  3536. justify-content: space-evenly;
  3537. align-items: center;
  3538. flex-wrap: wrap;
  3539. justify-content: center;
  3540. }
  3541.  
  3542. .PopUp_blocks:last-child {
  3543. margin-top: 25px;
  3544. }
  3545.  
  3546. .PopUp_buttons {
  3547. display: flex;
  3548. margin: 7px 10px;
  3549. flex-direction: column;
  3550. }
  3551.  
  3552. .PopUp_button {
  3553. background-color: #52A81C;
  3554. border-radius: 5px;
  3555. box-shadow: inset 0px -4px 10px, inset 0px 3px 2px #99fe20, 0px 0px 4px, 0px -3px 1px #d7b275, 0px 0px 0px 3px #ce9767;
  3556. cursor: pointer;
  3557. padding: 4px 12px 6px;
  3558. }
  3559.  
  3560. .PopUp_input {
  3561. text-align: center;
  3562. font-size: 16px;
  3563. height: 27px;
  3564. border: 1px solid #cf9250;
  3565. border-radius: 9px 9px 0px 0px;
  3566. background: transparent;
  3567. color: #fce1ac;
  3568. padding: 1px 10px;
  3569. box-sizing: border-box;
  3570. box-shadow: 0px 0px 4px, 0px 0px 0px 3px #ce9767;
  3571. }
  3572.  
  3573. .PopUp_checkboxes {
  3574. display: flex;
  3575. flex-direction: column;
  3576. margin: 15px 15px -5px 15px;
  3577. align-items: flex-start;
  3578. }
  3579.  
  3580. .PopUp_ContCheckbox {
  3581. margin: 2px 0px;
  3582. }
  3583.  
  3584. .PopUp_checkbox {
  3585. position: absolute;
  3586. z-index: -1;
  3587. opacity: 0;
  3588. }
  3589. .PopUp_checkbox+label {
  3590. display: inline-flex;
  3591. align-items: center;
  3592. user-select: none;
  3593.  
  3594. font-size: 15px;
  3595. font-family: sans-serif;
  3596. font-weight: 600;
  3597. font-stretch: condensed;
  3598. letter-spacing: 1px;
  3599. color: #fce1ac;
  3600. text-shadow: 0px 0px 1px;
  3601. }
  3602. .PopUp_checkbox+label::before {
  3603. content: '';
  3604. display: inline-block;
  3605. width: 20px;
  3606. height: 20px;
  3607. border: 1px solid #cf9250;
  3608. border-radius: 7px;
  3609. margin-right: 7px;
  3610. }
  3611. .PopUp_checkbox:checked+label::before {
  3612. background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3e%3cpath fill='%2388cb13' d='M6.564.75l-3.59 3.612-1.538-1.55L0 4.26 2.974 7.25 8 2.193z'/%3e%3c/svg%3e");
  3613. }
  3614.  
  3615. .PopUp_input::placeholder {
  3616. color: #fce1ac75;
  3617. }
  3618.  
  3619. .PopUp_input:focus {
  3620. outline: 0;
  3621. }
  3622.  
  3623. .PopUp_input + .PopUp_button {
  3624. border-radius: 0px 0px 5px 5px;
  3625. padding: 2px 18px 5px;
  3626. }
  3627.  
  3628. .PopUp_button:hover {
  3629. filter: brightness(1.2);
  3630. }
  3631.  
  3632. .PopUp_button:active {
  3633. box-shadow: inset 0px 5px 10px, inset 0px 1px 2px #99fe20, 0px 0px 4px, 0px -3px 1px #d7b275, 0px 0px 0px 3px #ce9767;
  3634. }
  3635.  
  3636. .PopUp_text {
  3637. font-size: 22px;
  3638. font-family: sans-serif;
  3639. font-weight: 600;
  3640. font-stretch: condensed;
  3641. white-space: pre-wrap;
  3642. letter-spacing: 1px;
  3643. text-align: center;
  3644. }
  3645.  
  3646. .PopUp_buttonText {
  3647. color: #E4FF4C;
  3648. text-shadow: 0px 1px 2px black;
  3649. }
  3650.  
  3651. .PopUp_msgText {
  3652. color: #FDE5B6;
  3653. text-shadow: 0px 0px 2px;
  3654. }
  3655.  
  3656. .PopUp_hideBlock {
  3657. display: none;
  3658. }
  3659. `;
  3660. document.head.appendChild(style);
  3661. }
  3662.  
  3663. const addBlocks = () => {
  3664. this.back = document.createElement('div');
  3665. this.back.classList.add('PopUp_back');
  3666. this.back.classList.add('PopUp_hideBlock');
  3667. document.body.append(this.back);
  3668.  
  3669. this.popUp = document.createElement('div');
  3670. this.popUp.classList.add('PopUp_');
  3671. this.back.append(this.popUp);
  3672.  
  3673. let upper = document.createElement('div')
  3674. upper.classList.add('PopUp_blocks');
  3675. this.popUp.append(upper);
  3676.  
  3677. this.middle = document.createElement('div')
  3678. this.middle.classList.add('PopUp_blocks');
  3679. this.middle.classList.add('PopUp_checkboxes');
  3680. this.popUp.append(this.middle);
  3681.  
  3682. this.downer = document.createElement('div')
  3683. this.downer.classList.add('PopUp_blocks');
  3684. this.popUp.append(this.downer);
  3685.  
  3686. this.msgText = document.createElement('div');
  3687. this.msgText.classList.add('PopUp_text', 'PopUp_msgText');
  3688. upper.append(this.msgText);
  3689. }
  3690.  
  3691. this.showBack = function () {
  3692. this.back.classList.remove('PopUp_hideBlock');
  3693. }
  3694.  
  3695. this.hideBack = function () {
  3696. this.back.classList.add('PopUp_hideBlock');
  3697. }
  3698.  
  3699. this.show = function () {
  3700. if (this.checkboxes.length) {
  3701. this.middle.classList.remove('PopUp_hideBlock');
  3702. }
  3703. this.showBack();
  3704. this.popUp.classList.remove('PopUp_hideBlock');
  3705. this.popUp.style.left = (window.innerWidth - this.popUp.offsetWidth) / 2 + 'px';
  3706. this.popUp.style.top = (window.innerHeight - this.popUp.offsetHeight) / 3 + 'px';
  3707. }
  3708.  
  3709. this.hide = function () {
  3710. this.hideBack();
  3711. this.popUp.classList.add('PopUp_hideBlock');
  3712. }
  3713.  
  3714. this.addAnyButton = (option) => {
  3715. const contButton = document.createElement('div');
  3716. contButton.classList.add('PopUp_buttons');
  3717. this.downer.append(contButton);
  3718.  
  3719. let inputField = {
  3720. value: option.result || option.default
  3721. }
  3722. if (option.isInput) {
  3723. inputField = document.createElement('input');
  3724. inputField.type = 'text';
  3725. if (option.placeholder) {
  3726. inputField.placeholder = option.placeholder;
  3727. }
  3728. if (option.default) {
  3729. inputField.value = option.default;
  3730. }
  3731. inputField.classList.add('PopUp_input');
  3732. contButton.append(inputField);
  3733. }
  3734.  
  3735. const button = document.createElement('div');
  3736. button.classList.add('PopUp_button');
  3737. button.title = option.title || '';
  3738. contButton.append(button);
  3739.  
  3740. const buttonText = document.createElement('div');
  3741. buttonText.classList.add('PopUp_text', 'PopUp_buttonText');
  3742. buttonText.innerText = option.msg;
  3743. button.append(buttonText);
  3744.  
  3745. return { button, contButton, inputField };
  3746. }
  3747.  
  3748. this.addCloseButton = () => {
  3749. let button = document.createElement('div')
  3750. button.classList.add('PopUp_close');
  3751. this.popUp.append(button);
  3752.  
  3753. let crossClose = document.createElement('div')
  3754. crossClose.classList.add('PopUp_crossClose');
  3755. button.append(crossClose);
  3756.  
  3757. return { button, contButton: button };
  3758. }
  3759.  
  3760. this.addButton = (option, buttonClick) => {
  3761.  
  3762. const { button, contButton, inputField } = option.isClose ? this.addCloseButton() : this.addAnyButton(option);
  3763. if (option.isClose) {
  3764. this.dialogPromice = {func: buttonClick, result: option.result};
  3765. }
  3766. button.addEventListener('click', () => {
  3767. let result = '';
  3768. if (option.isInput) {
  3769. result = inputField.value;
  3770. }
  3771. if (option.isClose || option.isCancel) {
  3772. this.dialogPromice = null;
  3773. }
  3774. buttonClick(result);
  3775. });
  3776.  
  3777. this.buttons.push(contButton);
  3778. }
  3779.  
  3780. this.clearButtons = () => {
  3781. while (this.buttons.length) {
  3782. this.buttons.pop().remove();
  3783. }
  3784. }
  3785.  
  3786. this.addCheckBox = (checkBox) => {
  3787. const contCheckbox = document.createElement('div');
  3788. contCheckbox.classList.add('PopUp_ContCheckbox');
  3789. this.middle.append(contCheckbox);
  3790.  
  3791. const checkbox = document.createElement('input');
  3792. checkbox.type = 'checkbox';
  3793. checkbox.id = 'PopUpCheckbox' + this.checkboxes.length;
  3794. checkbox.dataset.name = checkBox.name;
  3795. checkbox.checked = checkBox.checked;
  3796. checkbox.label = checkBox.label;
  3797. checkbox.title = checkBox.title || '';
  3798. checkbox.classList.add('PopUp_checkbox');
  3799. contCheckbox.appendChild(checkbox)
  3800.  
  3801. const checkboxLabel = document.createElement('label');
  3802. checkboxLabel.innerText = checkBox.label;
  3803. checkboxLabel.title = checkBox.title || '';
  3804. checkboxLabel.setAttribute('for', checkbox.id);
  3805. contCheckbox.appendChild(checkboxLabel);
  3806.  
  3807. this.checkboxes.push(checkbox);
  3808. }
  3809.  
  3810. this.clearCheckBox = () => {
  3811. this.middle.classList.add('PopUp_hideBlock');
  3812. while (this.checkboxes.length) {
  3813. this.checkboxes.pop().parentNode.remove();
  3814. }
  3815. }
  3816.  
  3817. this.setMsgText = (text) => {
  3818. this.msgText.innerHTML = text;
  3819. }
  3820.  
  3821. this.getCheckBoxes = () => {
  3822. const checkBoxes = [];
  3823.  
  3824. for (const checkBox of this.checkboxes) {
  3825. checkBoxes.push({
  3826. name: checkBox.dataset.name,
  3827. label: checkBox.label,
  3828. checked: checkBox.checked
  3829. });
  3830. }
  3831.  
  3832. return checkBoxes;
  3833. }
  3834.  
  3835. this.confirm = async (msg, buttOpt, checkBoxes = []) => {
  3836. this.clearButtons();
  3837. this.clearCheckBox();
  3838. return new Promise((complete, failed) => {
  3839. this.setMsgText(msg);
  3840. if (!buttOpt) {
  3841. buttOpt = [{ msg: 'Ok', result: true, isInput: false }];
  3842. }
  3843. for (const checkBox of checkBoxes) {
  3844. this.addCheckBox(checkBox);
  3845. }
  3846. for (let butt of buttOpt) {
  3847. this.addButton(butt, (result) => {
  3848. result = result || butt.result;
  3849. complete(result);
  3850. popup.hide();
  3851. });
  3852. if (butt.isCancel) {
  3853. this.dialogPromice = {func: complete, result: butt.result};
  3854. }
  3855. }
  3856. this.show();
  3857. });
  3858. }
  3859.  
  3860. document.addEventListener('DOMContentLoaded', init);
  3861. });
  3862.  
  3863. /**
  3864. * Script control panel
  3865. *
  3866. * Панель управления скриптом
  3867. */
  3868. const scriptMenu = new (function () {
  3869.  
  3870. this.mainMenu,
  3871. this.buttons = [],
  3872. this.checkboxes = [];
  3873. this.option = {
  3874. showMenu: false,
  3875. showDetails: {}
  3876. };
  3877.  
  3878. this.init = function (option = {}) {
  3879. this.option = Object.assign(this.option, option);
  3880. this.option.showDetails = this.loadShowDetails();
  3881. addStyle();
  3882. addBlocks();
  3883. }
  3884.  
  3885. const addStyle = () => {
  3886. style = document.createElement('style');
  3887. style.innerText = `
  3888. .scriptMenu_status {
  3889. position: absolute;
  3890. z-index: 10001;
  3891. white-space: pre-wrap; //тест для выравнивания кнопок
  3892. /* max-height: 30px; */
  3893. top: -1px;
  3894. left: 30%;
  3895. cursor: pointer;
  3896. border-radius: 0px 0px 10px 10px;
  3897. background: #190e08e6;
  3898. border: 1px #ce9767 solid;
  3899. font-size: 18px;
  3900. font-family: sans-serif;
  3901. font-weight: 600;
  3902. font-stretch: condensed;
  3903. letter-spacing: 1px;
  3904. color: #fce1ac;
  3905. text-shadow: 0px 0px 1px;
  3906. transition: 0.5s;
  3907. padding: 2px 10px 3px;
  3908. }
  3909. .scriptMenu_statusHide {
  3910. top: -35px;
  3911. height: 30px;
  3912. overflow: hidden;
  3913. }
  3914. .scriptMenu_label {
  3915. position: absolute;
  3916. top: 30%;
  3917. left: -4px;
  3918. z-index: 9999;
  3919. cursor: pointer;
  3920. width: 30px;
  3921. height: 30px;
  3922. background: radial-gradient(circle, #47a41b 0%, #1a2f04 100%);
  3923. border: 1px solid #1a2f04;
  3924. border-radius: 5px;
  3925. box-shadow:
  3926. inset 0px 2px 4px #83ce26,
  3927. inset 0px -4px 6px #1a2f04,
  3928. 0px 0px 2px black,
  3929. 0px 0px 0px 2px #ce9767;
  3930. }
  3931. .scriptMenu_label:hover {
  3932. filter: brightness(1.2);
  3933. }
  3934. .scriptMenu_arrowLabel {
  3935. width: 100%;
  3936. height: 100%;
  3937. background-size: 75%;
  3938. background-position: center;
  3939. background-repeat: no-repeat;
  3940. 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");
  3941. box-shadow: 0px 1px 2px #000;
  3942. border-radius: 5px;
  3943. filter: drop-shadow(0px 1px 2px #000D);
  3944. }
  3945. .scriptMenu_main {
  3946. position: absolute;
  3947. max-width: 285px;
  3948. z-index: 9999;
  3949. top: 50%;
  3950. transform: translateY(-40%);
  3951. background: #190e08e6;
  3952. border: 1px #ce9767 solid;
  3953. border-radius: 0px 10px 10px 0px;
  3954. border-left: none;
  3955. padding: 5px 10px 5px 5px;
  3956. box-sizing: border-box;
  3957. font-size: 15px;
  3958. font-family: sans-serif;
  3959. font-weight: 600;
  3960. font-stretch: condensed;
  3961. letter-spacing: 1px;
  3962. color: #fce1ac;
  3963. text-shadow: 0px 0px 1px;
  3964. transition: 1s;
  3965. display: flex;
  3966. flex-direction: column;
  3967. flex-wrap: nowrap;
  3968. }
  3969. .scriptMenu_showMenu {
  3970. display: none;
  3971. }
  3972. .scriptMenu_showMenu:checked~.scriptMenu_main {
  3973. left: 0px;
  3974. }
  3975. .scriptMenu_showMenu:not(:checked)~.scriptMenu_main {
  3976. left: -300px;
  3977. }
  3978. .scriptMenu_divInput {
  3979. margin: 2px;
  3980. }
  3981. .scriptMenu_divInputText {
  3982. margin: 2px;
  3983. align-self: center;
  3984. display: flex;
  3985. }
  3986. .scriptMenu_checkbox {
  3987. position: absolute;
  3988. z-index: -1;
  3989. opacity: 0;
  3990. }
  3991. .scriptMenu_checkbox+label {
  3992. display: inline-flex;
  3993. align-items: center;
  3994. user-select: none;
  3995. }
  3996. .scriptMenu_checkbox+label::before {
  3997. content: '';
  3998. display: inline-block;
  3999. width: 20px;
  4000. height: 20px;
  4001. border: 1px solid #cf9250;
  4002. border-radius: 7px;
  4003. margin-right: 7px;
  4004. }
  4005. .scriptMenu_checkbox:checked+label::before {
  4006. 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");
  4007. }
  4008. .scriptMenu_close {
  4009. width: 40px;
  4010. height: 40px;
  4011. position: absolute;
  4012. right: -18px;
  4013. top: -18px;
  4014. border: 3px solid #c18550;
  4015. border-radius: 20px;
  4016. background: radial-gradient(circle, rgba(190,30,35,1) 0%, rgba(0,0,0,1) 100%);
  4017. background-position-y: 3px;
  4018. box-shadow: -1px 1px 3px black;
  4019. cursor: pointer;
  4020. box-sizing: border-box;
  4021. }
  4022. .scriptMenu_close:hover {
  4023. filter: brightness(1.2);
  4024. }
  4025. .scriptMenu_crossClose {
  4026. width: 100%;
  4027. height: 100%;
  4028. background-size: 65%;
  4029. background-position: center;
  4030. background-repeat: no-repeat;
  4031. 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")
  4032. }
  4033. .scriptMenu_button {
  4034. user-select: none;
  4035. border-radius: 5px;
  4036. cursor: pointer;
  4037. padding: 5px 14px 8px;
  4038. margin: 4px;
  4039. background: radial-gradient(circle, rgba(165,120,56,1) 80%, rgba(0,0,0,1) 110%);
  4040. box-shadow: inset 0px -4px 6px #442901, inset 0px 1px 6px #442901, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 2px #ce9767;
  4041. }
  4042. .scriptMenu_button:hover {
  4043. filter: brightness(1.2);
  4044. }
  4045. .scriptMenu_button:active {
  4046. box-shadow: inset 0px 4px 6px #442901, inset 0px 4px 6px #442901, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 2px #ce9767;
  4047. }
  4048. .scriptMenu_buttonText {
  4049. color: #fce5b7;
  4050. text-shadow: 0px 1px 2px black;
  4051. text-align: center;
  4052. }
  4053. .scriptMenu_header {
  4054. text-align: center;
  4055. align-self: center;
  4056. font-size: 15px;
  4057. margin: 0px 15px;
  4058. }
  4059. .scriptMenu_header a {
  4060. color: #fce5b7;
  4061. text-decoration: none;
  4062. }
  4063. .scriptMenu_InputText {
  4064. text-align: center;
  4065. width: 130px;
  4066. height: 24px;
  4067. border: 1px solid #cf9250;
  4068. border-radius: 9px;
  4069. background: transparent;
  4070. color: #fce1ac;
  4071. padding: 0px 10px;
  4072. box-sizing: border-box;
  4073. }
  4074. .scriptMenu_InputText:focus {
  4075. filter: brightness(1.2);
  4076. outline: 0;
  4077. }
  4078. .scriptMenu_InputText::placeholder {
  4079. color: #fce1ac75;
  4080. }
  4081. .scriptMenu_Summary {
  4082. cursor: pointer;
  4083. margin-left: 7px;
  4084. }
  4085. .scriptMenu_Details {
  4086. align-self: center;
  4087. }
  4088. `;
  4089. document.head.appendChild(style);
  4090. }
  4091.  
  4092. const addBlocks = () => {
  4093. const main = document.createElement('div');
  4094. document.body.appendChild(main);
  4095.  
  4096. this.status = document.createElement('div');
  4097. this.status.classList.add('scriptMenu_status');
  4098. this.setStatus('');
  4099. main.appendChild(this.status);
  4100.  
  4101. const label = document.createElement('label');
  4102. label.classList.add('scriptMenu_label');
  4103. label.setAttribute('for', 'checkbox_showMenu');
  4104. main.appendChild(label);
  4105.  
  4106. const arrowLabel = document.createElement('div');
  4107. arrowLabel.classList.add('scriptMenu_arrowLabel');
  4108. label.appendChild(arrowLabel);
  4109.  
  4110. const checkbox = document.createElement('input');
  4111. checkbox.type = 'checkbox';
  4112. checkbox.id = 'checkbox_showMenu';
  4113. checkbox.checked = this.option.showMenu;
  4114. checkbox.classList.add('scriptMenu_showMenu');
  4115. main.appendChild(checkbox);
  4116.  
  4117. this.mainMenu = document.createElement('div');
  4118. this.mainMenu.classList.add('scriptMenu_main');
  4119. main.appendChild(this.mainMenu);
  4120.  
  4121. const closeButton = document.createElement('label');
  4122. closeButton.classList.add('scriptMenu_close');
  4123. closeButton.setAttribute('for', 'checkbox_showMenu');
  4124. this.mainMenu.appendChild(closeButton);
  4125.  
  4126. const crossClose = document.createElement('div');
  4127. crossClose.classList.add('scriptMenu_crossClose');
  4128. closeButton.appendChild(crossClose);
  4129. }
  4130.  
  4131. this.setStatus = (text, onclick) => {
  4132. if (!text) {
  4133. this.status.classList.add('scriptMenu_statusHide');
  4134. } else {
  4135. this.status.classList.remove('scriptMenu_statusHide');
  4136. this.status.innerHTML = text;
  4137. }
  4138.  
  4139. if (typeof onclick == 'function') {
  4140. this.status.addEventListener("click", onclick, {
  4141. once: true
  4142. });
  4143. }
  4144. }
  4145.  
  4146. /**
  4147. * Adding a text element
  4148. *
  4149. * Добавление текстового элемента
  4150. * @param {String} text text // текст
  4151. * @param {Function} func Click function // функция по клику
  4152. * @param {HTMLDivElement} main parent // родитель
  4153. */
  4154. this.addHeader = (text, func, main) => {
  4155. main = main || this.mainMenu;
  4156. const header = document.createElement('div');
  4157. header.classList.add('scriptMenu_header');
  4158. header.innerHTML = text;
  4159. if (typeof func == 'function') {
  4160. header.addEventListener('click', func);
  4161. }
  4162. main.appendChild(header);
  4163. }
  4164.  
  4165. /**
  4166. * Adding a button
  4167. *
  4168. * Добавление кнопки
  4169. * @param {String} text
  4170. * @param {Function} func
  4171. * @param {String} title
  4172. * @param {HTMLDivElement} main parent // родитель
  4173. */
  4174. this.addButton = (text, func, title, main) => {
  4175. main = main || this.mainMenu;
  4176. const button = document.createElement('div');
  4177. button.classList.add('scriptMenu_button');
  4178. button.title = title;
  4179. button.addEventListener('click', func);
  4180. main.appendChild(button);
  4181.  
  4182. const buttonText = document.createElement('div');
  4183. buttonText.classList.add('scriptMenu_buttonText');
  4184. buttonText.innerText = text;
  4185. button.appendChild(buttonText);
  4186. this.buttons.push(button);
  4187.  
  4188. return button;
  4189. }
  4190.  
  4191. /**
  4192. * Adding checkbox
  4193. *
  4194. * Добавление чекбокса
  4195. * @param {String} label
  4196. * @param {String} title
  4197. * @param {HTMLDivElement} main parent // родитель
  4198. * @returns
  4199. */
  4200. this.addCheckbox = (label, title, main) => {
  4201. main = main || this.mainMenu;
  4202. const divCheckbox = document.createElement('div');
  4203. divCheckbox.classList.add('scriptMenu_divInput');
  4204. divCheckbox.title = title;
  4205. main.appendChild(divCheckbox);
  4206.  
  4207. const checkbox = document.createElement('input');
  4208. checkbox.type = 'checkbox';
  4209. checkbox.id = 'scriptMenuCheckbox' + this.checkboxes.length;
  4210. checkbox.classList.add('scriptMenu_checkbox');
  4211. divCheckbox.appendChild(checkbox)
  4212.  
  4213. const checkboxLabel = document.createElement('label');
  4214. checkboxLabel.innerText = label;
  4215. checkboxLabel.setAttribute('for', checkbox.id);
  4216. divCheckbox.appendChild(checkboxLabel);
  4217.  
  4218. this.checkboxes.push(checkbox);
  4219. return checkbox;
  4220. }
  4221.  
  4222. /**
  4223. * Adding input field
  4224. *
  4225. * Добавление поля ввода
  4226. * @param {String} title
  4227. * @param {String} placeholder
  4228. * @param {HTMLDivElement} main parent // родитель
  4229. * @returns
  4230. */
  4231. this.addInputText = (title, placeholder, main) => {
  4232. main = main || this.mainMenu;
  4233. const divInputText = document.createElement('div');
  4234. divInputText.classList.add('scriptMenu_divInputText');
  4235. divInputText.title = title;
  4236. main.appendChild(divInputText);
  4237.  
  4238. const newInputText = document.createElement('input');
  4239. newInputText.type = 'text';
  4240. if (placeholder) {
  4241. newInputText.placeholder = placeholder;
  4242. }
  4243. newInputText.classList.add('scriptMenu_InputText');
  4244. divInputText.appendChild(newInputText)
  4245. return newInputText;
  4246. }
  4247.  
  4248. /**
  4249. * Adds a dropdown block
  4250. *
  4251. * Добавляет раскрывающийся блок
  4252. * @param {String} summary
  4253. * @param {String} name
  4254. * @returns
  4255. */
  4256. this.addDetails = (summaryText, name = null) => {
  4257. const details = document.createElement('details');
  4258. details.classList.add('scriptMenu_Details');
  4259. this.mainMenu.appendChild(details);
  4260.  
  4261. const summary = document.createElement('summary');
  4262. summary.classList.add('scriptMenu_Summary');
  4263. summary.innerText = summaryText;
  4264. if (name) {
  4265. const self = this;
  4266. details.open = this.option.showDetails[name];
  4267. details.dataset.name = name;
  4268. summary.addEventListener('click', () => {
  4269. self.option.showDetails[details.dataset.name] = !details.open;
  4270. self.saveShowDetails(self.option.showDetails);
  4271. });
  4272. }
  4273. details.appendChild(summary);
  4274.  
  4275. return details;
  4276. }
  4277.  
  4278. /**
  4279. * Saving the expanded state of the details blocks
  4280. *
  4281. * Сохранение состояния развенутости блоков details
  4282. * @param {*} value
  4283. */
  4284. this.saveShowDetails = (value) => {
  4285. localStorage.setItem('scriptMenu_showDetails', JSON.stringify(value));
  4286. }
  4287.  
  4288. /**
  4289. * Loading the state of expanded blocks details
  4290. *
  4291. * Загрузка состояния развенутости блоков details
  4292. * @returns
  4293. */
  4294. this.loadShowDetails = () => {
  4295. let showDetails = localStorage.getItem('scriptMenu_showDetails');
  4296.  
  4297. if (!showDetails) {
  4298. return {};
  4299. }
  4300.  
  4301. try {
  4302. showDetails = JSON.parse(showDetails);
  4303. } catch (e) {
  4304. return {};
  4305. }
  4306.  
  4307. return showDetails;
  4308. }
  4309. });
  4310.  
  4311. /**
  4312. * Пример использования
  4313. scriptMenu.init();
  4314. scriptMenu.addHeader('v1.508');
  4315. scriptMenu.addCheckbox('testHack', 'Тестовый взлом игры!');
  4316. scriptMenu.addButton('Запуск!', () => console.log('click'), 'подсказака');
  4317. scriptMenu.addInputText('input подсказака');
  4318. */
  4319. /**
  4320. * Game Library
  4321. *
  4322. * Игровая библиотека
  4323. */
  4324. class Library {
  4325. defaultLibUrl = 'https://heroesru-a.akamaihd.net/vk/v1101/lib/lib.json';
  4326.  
  4327. constructor() {
  4328. if (!Library.instance) {
  4329. Library.instance = this;
  4330. }
  4331.  
  4332. return Library.instance;
  4333. }
  4334.  
  4335. async load() {
  4336. try {
  4337. await this.getUrlLib();
  4338. console.log(this.defaultLibUrl);
  4339. this.data = await fetch(this.defaultLibUrl).then(e => e.json())
  4340. } catch (error) {
  4341. console.error('Не удалось загрузить библиотеку', error)
  4342. }
  4343. }
  4344.  
  4345. async getUrlLib() {
  4346. try {
  4347. const db = new Database('hw_cache', 'cache');
  4348. await db.open();
  4349. const cacheLibFullUrl = await db.get('lib/lib.json.gz', false);
  4350. this.defaultLibUrl = cacheLibFullUrl.fullUrl.split('.gz').shift();
  4351. } catch(e) {}
  4352. }
  4353.  
  4354. getData(id) {
  4355. return this.data[id];
  4356. }
  4357. }
  4358.  
  4359. this.lib = new Library();
  4360. /**
  4361. * Database
  4362. *
  4363. * База данных
  4364. */
  4365. class Database {
  4366. constructor(dbName, storeName) {
  4367. this.dbName = dbName;
  4368. this.storeName = storeName;
  4369. this.db = null;
  4370. }
  4371.  
  4372. async open() {
  4373. return new Promise((resolve, reject) => {
  4374. const request = indexedDB.open(this.dbName);
  4375.  
  4376. request.onerror = () => {
  4377. reject(new Error(`Failed to open database ${this.dbName}`));
  4378. };
  4379.  
  4380. request.onsuccess = () => {
  4381. this.db = request.result;
  4382. resolve();
  4383. };
  4384.  
  4385. request.onupgradeneeded = (event) => {
  4386. const db = event.target.result;
  4387. if (!db.objectStoreNames.contains(this.storeName)) {
  4388. db.createObjectStore(this.storeName);
  4389. }
  4390. };
  4391. });
  4392. }
  4393.  
  4394. async set(key, value) {
  4395. return new Promise((resolve, reject) => {
  4396. const transaction = this.db.transaction([this.storeName], 'readwrite');
  4397. const store = transaction.objectStore(this.storeName);
  4398. const request = store.put(value, key);
  4399.  
  4400. request.onerror = () => {
  4401. reject(new Error(`Failed to save value with key ${key}`));
  4402. };
  4403.  
  4404. request.onsuccess = () => {
  4405. resolve();
  4406. };
  4407. });
  4408. }
  4409.  
  4410. async get(key, def) {
  4411. return new Promise((resolve, reject) => {
  4412. const transaction = this.db.transaction([this.storeName], 'readonly');
  4413. const store = transaction.objectStore(this.storeName);
  4414. const request = store.get(key);
  4415.  
  4416. request.onerror = () => {
  4417. resolve(def);
  4418. };
  4419.  
  4420. request.onsuccess = () => {
  4421. resolve(request.result);
  4422. };
  4423. });
  4424. }
  4425.  
  4426. async delete(key) {
  4427. return new Promise((resolve, reject) => {
  4428. const transaction = this.db.transaction([this.storeName], 'readwrite');
  4429. const store = transaction.objectStore(this.storeName);
  4430. const request = store.delete(key);
  4431.  
  4432. request.onerror = () => {
  4433. reject(new Error(`Failed to delete value with key ${key}`));
  4434. };
  4435.  
  4436. request.onsuccess = () => {
  4437. resolve();
  4438. };
  4439. });
  4440. }
  4441. }
  4442.  
  4443. /**
  4444. * Returns the stored value
  4445. *
  4446. * Возвращает сохраненное значение
  4447. */
  4448. function getSaveVal(saveName, def) {
  4449. const result = storage.get(saveName, def);
  4450. return result;
  4451. }
  4452.  
  4453. /**
  4454. * Stores value
  4455. *
  4456. * Сохраняет значение
  4457. */
  4458. function setSaveVal(saveName, value) {
  4459. storage.set(saveName, value);
  4460. }
  4461.  
  4462. /**
  4463. * Database initialization
  4464. *
  4465. * Инициализация базы данных
  4466. */
  4467. const db = new Database(GM_info.script.name, 'settings');
  4468.  
  4469. /**
  4470. * Data store
  4471. *
  4472. * Хранилище данных
  4473. */
  4474. const storage = {
  4475. userId: 0,
  4476. /**
  4477. * Default values
  4478. *
  4479. * Значения по умолчанию
  4480. */
  4481. values: [
  4482. ...Object.entries(checkboxes).map(e => ({ [e[0]]: e[1].default })),
  4483. ...Object.entries(inputs).map(e => ({ [e[0]]: e[1].default })),
  4484. ...Object.entries(inputs2).map(e => ({ [e[0]]: e[1].default })),
  4485. //...Object.entries(inputs3).map(e => ({ [e[0]]: e[1].default })),
  4486. ].reduce((acc, obj) => ({ ...acc, ...obj }), {}),
  4487. name: GM_info.script.name,
  4488. get: function (key, def) {
  4489. if (key in this.values) {
  4490. return this.values[key];
  4491. }
  4492. return def;
  4493. },
  4494. set: function (key, value) {
  4495. this.values[key] = value;
  4496. db.set(this.userId, this.values).catch(
  4497. e => null
  4498. );
  4499. localStorage[this.name + ':' + key] = value;
  4500. },
  4501. delete: function (key) {
  4502. delete this.values[key];
  4503. db.set(this.userId, this.values);
  4504. delete localStorage[this.name + ':' + key];
  4505. }
  4506. }
  4507.  
  4508. /**
  4509. * Returns all keys from localStorage that start with prefix (for migration)
  4510. *
  4511. * Возвращает все ключи из localStorage которые начинаются с prefix (для миграции)
  4512. */
  4513. function getAllValuesStartingWith(prefix) {
  4514. const values = [];
  4515. for (let i = 0; i < localStorage.length; i++) {
  4516. const key = localStorage.key(i);
  4517. if (key.startsWith(prefix)) {
  4518. const val = localStorage.getItem(key);
  4519. const keyValue = key.split(':')[1];
  4520. values.push({ key: keyValue, val });
  4521. }
  4522. }
  4523. return values;
  4524. }
  4525.  
  4526. /**
  4527. * Opens or migrates to a database
  4528. *
  4529. * Открывает или мигрирует в базу данных
  4530. */
  4531. async function openOrMigrateDatabase(userId) {
  4532. storage.userId = userId;
  4533. try {
  4534. await db.open();
  4535. } catch(e) {
  4536. return;
  4537. }
  4538. let settings = await db.get(userId, false);
  4539.  
  4540. if (settings) {
  4541. storage.values = settings;
  4542. return;
  4543. }
  4544.  
  4545. const values = getAllValuesStartingWith(GM_info.script.name);
  4546. for (const value of values) {
  4547. let val = null;
  4548. try {
  4549. val = JSON.parse(value.val);
  4550. } catch {
  4551. break;
  4552. }
  4553. storage.values[value.key] = val;
  4554. }
  4555. await db.set(userId, storage.values);
  4556. }
  4557.  
  4558. /**
  4559. * Sending expeditions
  4560. *
  4561. * Отправка экспедиций
  4562. */
  4563. function checkExpedition() {
  4564. return new Promise((resolve, reject) => {
  4565. const expedition = new Expedition(resolve, reject);
  4566. expedition.start();
  4567. });
  4568. }
  4569.  
  4570. class Expedition {
  4571. checkExpedInfo = {
  4572. calls: [
  4573. {
  4574. name: 'expeditionGet',
  4575. args: {},
  4576. ident: 'expeditionGet',
  4577. },
  4578. {
  4579. name: 'heroGetAll',
  4580. args: {},
  4581. ident: 'heroGetAll',
  4582. },
  4583. ],
  4584. };
  4585.  
  4586. constructor(resolve, reject) {
  4587. this.resolve = resolve;
  4588. this.reject = reject;
  4589. }
  4590.  
  4591. async start() {
  4592. const data = await Send(JSON.stringify(this.checkExpedInfo));
  4593.  
  4594. const expedInfo = data.results[0].result.response;
  4595. const dataHeroes = data.results[1].result.response;
  4596. const dataExped = { useHeroes: [], exped: [] };
  4597. const calls = [];
  4598.  
  4599. /**
  4600. * Adding expeditions to collect
  4601. * Добавляем экспедиции для сбора
  4602. */
  4603. let countGet = 0;
  4604. for (var n in expedInfo) {
  4605. const exped = expedInfo[n];
  4606. const dateNow = Date.now() / 1000;
  4607. if (exped.status == 2 && exped.endTime != 0 && dateNow > exped.endTime) {
  4608. countGet++;
  4609. calls.push({
  4610. name: 'expeditionFarm',
  4611. args: { expeditionId: exped.id },
  4612. ident: 'expeditionFarm_' + exped.id,
  4613. });
  4614. } else {
  4615. dataExped.useHeroes = dataExped.useHeroes.concat(exped.heroes);
  4616. }
  4617. if (exped.status == 1) {
  4618. dataExped.exped.push({ id: exped.id, power: exped.power });
  4619. }
  4620. }
  4621. dataExped.exped = dataExped.exped.sort((a, b) => b.power - a.power);
  4622.  
  4623. /**
  4624. * Putting together a list of heroes
  4625. * Собираем список героев
  4626. */
  4627. const heroesArr = [];
  4628. for (let n in dataHeroes) {
  4629. const hero = dataHeroes[n];
  4630. if (hero.xp > 0 && !dataExped.useHeroes.includes(hero.id)) {
  4631. let heroPower = hero.power;
  4632. // Лара Крофт * 3
  4633. if (hero.id == 63 && hero.color >= 16) {
  4634. heroPower *= 3;
  4635. }
  4636. heroesArr.push({ id: hero.id, power: heroPower });
  4637. }
  4638. }
  4639.  
  4640. /**
  4641. * Adding expeditions to send
  4642. * Добавляем экспедиции для отправки
  4643. */
  4644. let countSend = 0;
  4645. heroesArr.sort((a, b) => a.power - b.power);
  4646. for (const exped of dataExped.exped) {
  4647. let heroesIds = this.selectionHeroes(heroesArr, exped.power);
  4648. if (heroesIds && heroesIds.length > 4) {
  4649. for (let q in heroesArr) {
  4650. if (heroesIds.includes(heroesArr[q].id)) {
  4651. delete heroesArr[q];
  4652. }
  4653. }
  4654. countSend++;
  4655. calls.push({
  4656. name: 'expeditionSendHeroes',
  4657. args: {
  4658. expeditionId: exped.id,
  4659. heroes: heroesIds,
  4660. },
  4661. ident: 'expeditionSendHeroes_' + exped.id,
  4662. });
  4663. }
  4664. }
  4665.  
  4666. if (calls.length) {
  4667. await Send({ calls });
  4668. this.end(I18N('EXPEDITIONS_SENT', {countGet, countSend}));
  4669. return;
  4670. }
  4671. this.end(I18N('EXPEDITIONS_NOTHING'));
  4672. }
  4673.  
  4674. /**
  4675. * Selection of heroes for expeditions
  4676. *
  4677. * Подбор героев для экспедиций
  4678. */
  4679. selectionHeroes(heroes, power) {
  4680. const resultHeroers = [];
  4681. const heroesIds = [];
  4682. for (let q = 0; q < 5; q++) {
  4683. for (let i in heroes) {
  4684. let hero = heroes[i];
  4685. if (heroesIds.includes(hero.id)) {
  4686. continue;
  4687. }
  4688.  
  4689. const summ = resultHeroers.reduce((acc, hero) => acc + hero.power, 0);
  4690. const need = Math.round((power - summ) / (5 - resultHeroers.length));
  4691. if (hero.power > need) {
  4692. resultHeroers.push(hero);
  4693. heroesIds.push(hero.id);
  4694. break;
  4695. }
  4696. }
  4697. }
  4698.  
  4699. const summ = resultHeroers.reduce((acc, hero) => acc + hero.power, 0);
  4700. if (summ < power) {
  4701. return false;
  4702. }
  4703. return heroesIds;
  4704. }
  4705.  
  4706. /**
  4707. * Ends expedition script
  4708. *
  4709. * Завершает скрипт экспедиции
  4710. */
  4711. end(msg) {
  4712. setProgress(msg, true);
  4713. this.resolve();
  4714. }
  4715. }
  4716.  
  4717. /**
  4718. * Walkthrough of the dungeon
  4719. *
  4720. * Прохождение подземелья
  4721. */
  4722. function testDungeon() {
  4723. return new Promise((resolve, reject) => {
  4724. const dung = new executeDungeon(resolve, reject);
  4725. const titanit = getInput('countTitanit');
  4726. dung.start(titanit);
  4727. });
  4728. }
  4729.  
  4730. /**
  4731. * Walkthrough of the dungeon
  4732. *
  4733. * Прохождение подземелья
  4734. */
  4735. function executeDungeon(resolve, reject) {
  4736. dungeonActivity = 0;
  4737. maxDungeonActivity = 150;
  4738.  
  4739. titanGetAll = [];
  4740.  
  4741. teams = {
  4742. heroes: [],
  4743. earth: [],
  4744. fire: [],
  4745. neutral: [],
  4746. water: [],
  4747. }
  4748.  
  4749. titanStats = [];
  4750.  
  4751. titansStates = {};
  4752.  
  4753. callsExecuteDungeon = {
  4754. calls: [{
  4755. name: "dungeonGetInfo",
  4756. args: {},
  4757. ident: "dungeonGetInfo"
  4758. }, {
  4759. name: "teamGetAll",
  4760. args: {},
  4761. ident: "teamGetAll"
  4762. }, {
  4763. name: "teamGetFavor",
  4764. args: {},
  4765. ident: "teamGetFavor"
  4766. }, {
  4767. name: "clanGetInfo",
  4768. args: {},
  4769. ident: "clanGetInfo"
  4770. }, {
  4771. name: "titanGetAll",
  4772. args: {},
  4773. ident: "titanGetAll"
  4774. }, {
  4775. name: "inventoryGet",
  4776. args: {},
  4777. ident: "inventoryGet"
  4778. }]
  4779. }
  4780.  
  4781. this.start = function(titanit) {
  4782. maxDungeonActivity = titanit || getInput('countTitanit');
  4783. send(JSON.stringify(callsExecuteDungeon), startDungeon);
  4784. }
  4785.  
  4786. /**
  4787. * Getting data on the dungeon
  4788. *
  4789. * Получаем данные по подземелью
  4790. */
  4791. function startDungeon(e) {
  4792. stopDung = false; // стоп подземка
  4793. res = e.results;
  4794. dungeonGetInfo = res[0].result.response;
  4795. if (!dungeonGetInfo) {
  4796. endDungeon('noDungeon', res);
  4797. return;
  4798. }
  4799. teamGetAll = res[1].result.response;
  4800. teamGetFavor = res[2].result.response;
  4801. dungeonActivity = res[3].result.response.stat.todayDungeonActivity;
  4802. titanGetAll = Object.values(res[4].result.response);
  4803. countPredictionCard = res[5].result.response.consumable[81];
  4804.  
  4805. teams.hero = {
  4806. favor: teamGetFavor.dungeon_hero,
  4807. heroes: teamGetAll.dungeon_hero.filter(id => id < 6000),
  4808. teamNum: 0,
  4809. }
  4810. heroPet = teamGetAll.dungeon_hero.filter(id => id >= 6000).pop();
  4811. if (heroPet) {
  4812. teams.hero.pet = heroPet;
  4813. }
  4814.  
  4815. teams.neutral = {
  4816. favor: {},
  4817. heroes: getTitanTeam(titanGetAll, 'neutral'),
  4818. teamNum: 0,
  4819. };
  4820. teams.water = {
  4821. favor: {},
  4822. heroes: getTitanTeam(titanGetAll, 'water'),
  4823. teamNum: 0,
  4824. };
  4825. teams.fire = {
  4826. favor: {},
  4827. heroes: getTitanTeam(titanGetAll, 'fire'),
  4828. teamNum: 0,
  4829. };
  4830. teams.earth = {
  4831. favor: {},
  4832. heroes: getTitanTeam(titanGetAll, 'earth'),
  4833. teamNum: 0,
  4834. };
  4835.  
  4836.  
  4837. checkFloor(dungeonGetInfo);
  4838. }
  4839.  
  4840. function getTitanTeam(titans, type) {
  4841. switch (type) {
  4842. case 'neutral':
  4843. return titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  4844. case 'water':
  4845. return titans.filter(e => e.id.toString().slice(2, 3) == '0').map(e => e.id);
  4846. case 'fire':
  4847. return titans.filter(e => e.id.toString().slice(2, 3) == '1').map(e => e.id);
  4848. case 'earth':
  4849. return titans.filter(e => e.id.toString().slice(2, 3) == '2').map(e => e.id);
  4850. }
  4851. }
  4852.  
  4853. function getNeutralTeam() {
  4854. const titans = titanGetAll.filter(e => !titansStates[e.id]?.isDead)
  4855. return titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  4856. }
  4857.  
  4858. function fixTitanTeam(titans) {
  4859. titans.heroes = titans.heroes.filter(e => !titansStates[e]?.isDead);
  4860. return titans;
  4861. }
  4862.  
  4863. /**
  4864. * Checking the floor
  4865. *
  4866. * Проверяем этаж
  4867. */
  4868. async function checkFloor(dungeonInfo) {
  4869. if (!('floor' in dungeonInfo) || dungeonInfo.floor?.state == 2) {
  4870. saveProgress();
  4871. return;
  4872. }
  4873. // console.log(dungeonInfo, dungeonActivity);
  4874. setProgress(`${I18N('DUNGEON')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity}`);
  4875. if (dungeonActivity >= maxDungeonActivity) {
  4876. endDungeon('endDungeon', 'maxActive ' + dungeonActivity + '/' + maxDungeonActivity);
  4877. return;
  4878. }
  4879. titansStates = dungeonInfo.states.titans;
  4880. titanStats = titanObjToArray(titansStates);
  4881. if (stopDung){
  4882. endDungeon('Стоп подземка,', 'набрано титанита: ' + dungeonActivity + '/' + maxDungeonActivity);
  4883. return;
  4884. }
  4885. const floorChoices = dungeonInfo.floor.userData;
  4886. const floorType = dungeonInfo.floorType;
  4887. //const primeElement = dungeonInfo.elements.prime;
  4888. if (floorType == "battle") {
  4889. const calls = [];
  4890. for (let teamNum in floorChoices) {
  4891. attackerType = floorChoices[teamNum].attackerType;
  4892. const args = fixTitanTeam(teams[attackerType]);
  4893. if (attackerType == 'neutral') {
  4894. args.heroes = getNeutralTeam();
  4895. }
  4896. if (!args.heroes.length) {
  4897. continue;
  4898. }
  4899. args.teamNum = teamNum;
  4900. calls.push({
  4901. name: "dungeonStartBattle",
  4902. args,
  4903. ident: "body_" + teamNum
  4904. })
  4905. }
  4906. if (!calls.length) {
  4907. endDungeon('endDungeon', 'All Dead');
  4908. return;
  4909. }
  4910. const battleDatas = await Send(JSON.stringify({ calls }))
  4911. .then(e => e.results.map(n => n.result.response))
  4912. const battleResults = [];
  4913. for (n in battleDatas) {
  4914. battleData = battleDatas[n]
  4915. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  4916. battleResults.push(await Calc(battleData).then(result => {
  4917. result.teamNum = n;
  4918. result.attackerType = floorChoices[n].attackerType;
  4919. return result;
  4920. }));
  4921. }
  4922. processingPromises(battleResults)
  4923. }
  4924. }
  4925.  
  4926. function processingPromises(results) {
  4927. let selectBattle = results[0];
  4928. if (results.length < 2) {
  4929. // console.log(selectBattle);
  4930. if (!selectBattle.result.win) {
  4931. endDungeon('dungeonEndBattle\n', selectBattle);
  4932. return;
  4933. }
  4934. endBattle(selectBattle);
  4935. return;
  4936. }
  4937.  
  4938. selectBattle = false;
  4939. let bestState = -1000;
  4940. for (const result of results) {
  4941. const recovery = getState(result);
  4942. if (recovery > bestState) {
  4943. bestState = recovery;
  4944. selectBattle = result
  4945. }
  4946. }
  4947. // console.log(selectBattle.teamNum, results);
  4948. if (!selectBattle || bestState <= -1000) {
  4949. endDungeon('dungeonEndBattle\n', results);
  4950. return;
  4951. }
  4952.  
  4953. startBattle(selectBattle.teamNum, selectBattle.attackerType)
  4954. .then(endBattle);
  4955. }
  4956.  
  4957. /**
  4958. * Let's start the fight
  4959. *
  4960. * Начинаем бой
  4961. */
  4962. function startBattle(teamNum, attackerType) {
  4963. return new Promise(function (resolve, reject) {
  4964. args = fixTitanTeam(teams[attackerType]);
  4965. args.teamNum = teamNum;
  4966. if (attackerType == 'neutral') {
  4967. const titans = titanGetAll.filter(e => !titansStates[e.id]?.isDead)
  4968. args.heroes = titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  4969. }
  4970. startBattleCall = {
  4971. calls: [{
  4972. name: "dungeonStartBattle",
  4973. args,
  4974. ident: "body"
  4975. }]
  4976. }
  4977. send(JSON.stringify(startBattleCall), resultBattle, {
  4978. resolve,
  4979. teamNum,
  4980. attackerType
  4981. });
  4982. });
  4983. }
  4984. /**
  4985. * Returns the result of the battle in a promise
  4986. *
  4987. * Возращает резульат боя в промис
  4988. */
  4989. function resultBattle(resultBattles, args) {
  4990. battleData = resultBattles.results[0].result.response;
  4991. battleType = "get_tower";
  4992. if (battleData.type == "dungeon_titan") {
  4993. battleType = "get_titan";
  4994. }
  4995. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  4996. BattleCalc(battleData, battleType, function (result) {
  4997. result.teamNum = args.teamNum;
  4998. result.attackerType = args.attackerType;
  4999. args.resolve(result);
  5000. });
  5001. }
  5002. /**
  5003. * Finishing the fight
  5004. *
  5005. * Заканчиваем бой
  5006. */
  5007. async function endBattle(battleInfo) {
  5008. if (battleInfo.result.win) {
  5009. const args = {
  5010. result: battleInfo.result,
  5011. progress: battleInfo.progress,
  5012. }
  5013. if (countPredictionCard > 0) {
  5014. args.isRaid = true;
  5015. } else {
  5016. const timer = getTimer(battleInfo.battleTime);
  5017. console.log(timer);
  5018. await countdownTimer(timer, `${I18N('DUNGEON')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity}`);
  5019. }
  5020. const calls = [{
  5021. name: "dungeonEndBattle",
  5022. args,
  5023. ident: "body"
  5024. }];
  5025. lastDungeonBattleData = null;
  5026. send(JSON.stringify({ calls }), resultEndBattle);
  5027. } else {
  5028. endDungeon('dungeonEndBattle win: false\n', battleInfo);
  5029. }
  5030. }
  5031.  
  5032. /**
  5033. * Getting and processing battle results
  5034. *
  5035. * Получаем и обрабатываем результаты боя
  5036. */
  5037. function resultEndBattle(e) {
  5038. if ('error' in e) {
  5039. popup.confirm(I18N('ERROR_MSG', {
  5040. name: e.error.name,
  5041. description: e.error.description,
  5042. }));
  5043. endDungeon('errorRequest', e);
  5044. return;
  5045. }
  5046. battleResult = e.results[0].result.response;
  5047. if ('error' in battleResult) {
  5048. endDungeon('errorBattleResult', battleResult);
  5049. return;
  5050. }
  5051. dungeonGetInfo = battleResult.dungeon ?? battleResult;
  5052. dungeonActivity += battleResult.reward.dungeonActivity ?? 0;
  5053. checkFloor(dungeonGetInfo);
  5054. }
  5055.  
  5056. /**
  5057. * Returns the coefficient of condition of the
  5058. * difference in titanium before and after the battle
  5059. *
  5060. * Возвращает коэффициент состояния титанов после боя
  5061. */
  5062. function getState(result) {
  5063. if (!result.result.win) {
  5064. return -1000;
  5065. }
  5066.  
  5067. let beforeSumFactor = 0;
  5068. const beforeTitans = result.battleData.attackers;
  5069. for (let titanId in beforeTitans) {
  5070. const titan = beforeTitans[titanId];
  5071. const state = titan.state;
  5072. let factor = 1;
  5073. if (state) {
  5074. const hp = state.hp / titan.hp;
  5075. const energy = state.energy / 1e3;
  5076. factor = hp + energy / 20
  5077. }
  5078. beforeSumFactor += factor;
  5079. }
  5080.  
  5081. let afterSumFactor = 0;
  5082. const afterTitans = result.progress[0].attackers.heroes;
  5083. for (let titanId in afterTitans) {
  5084. const titan = afterTitans[titanId];
  5085. const hp = titan.hp / beforeTitans[titanId].hp;
  5086. const energy = titan.energy / 1e3;
  5087. const factor = hp + energy / 20;
  5088. afterSumFactor += factor;
  5089. }
  5090. return afterSumFactor - beforeSumFactor;
  5091. }
  5092.  
  5093. /**
  5094. * Converts an object with IDs to an array with IDs
  5095. *
  5096. * Преобразует объект с идетификаторами в массив с идетификаторами
  5097. */
  5098. function titanObjToArray(obj) {
  5099. let titans = [];
  5100. for (let id in obj) {
  5101. obj[id].id = id;
  5102. titans.push(obj[id]);
  5103. }
  5104. return titans;
  5105. }
  5106.  
  5107. function saveProgress() {
  5108. let saveProgressCall = {
  5109. calls: [{
  5110. name: "dungeonSaveProgress",
  5111. args: {},
  5112. ident: "body"
  5113. }]
  5114. }
  5115. send(JSON.stringify(saveProgressCall), resultEndBattle);
  5116. }
  5117.  
  5118. function endDungeon(reason, info) {
  5119. console.warn(reason, info);
  5120. setProgress(`${I18N('DUNGEON')} ${I18N('COMPLETED')}`, true);
  5121. resolve();
  5122. }
  5123. }
  5124.  
  5125. /**
  5126. * Passing the tower
  5127. *
  5128. * Прохождение башни
  5129. */
  5130. function testTower() {
  5131. return new Promise((resolve, reject) => {
  5132. tower = new executeTower(resolve, reject);
  5133. tower.start();
  5134. });
  5135. }
  5136.  
  5137. /**
  5138. * Passing the tower
  5139. *
  5140. * Прохождение башни
  5141. */
  5142. function executeTower(resolve, reject) {
  5143. lastTowerInfo = {};
  5144.  
  5145. scullCoin = 0;
  5146.  
  5147. heroGetAll = [];
  5148.  
  5149. heroesStates = {};
  5150.  
  5151. argsBattle = {
  5152. heroes: [],
  5153. favor: {},
  5154. };
  5155.  
  5156. callsExecuteTower = {
  5157. calls: [{
  5158. name: "towerGetInfo",
  5159. args: {},
  5160. ident: "towerGetInfo"
  5161. }, {
  5162. name: "teamGetAll",
  5163. args: {},
  5164. ident: "teamGetAll"
  5165. }, {
  5166. name: "teamGetFavor",
  5167. args: {},
  5168. ident: "teamGetFavor"
  5169. }, {
  5170. name: "inventoryGet",
  5171. args: {},
  5172. ident: "inventoryGet"
  5173. }, {
  5174. name: "heroGetAll",
  5175. args: {},
  5176. ident: "heroGetAll"
  5177. }]
  5178. }
  5179.  
  5180. buffIds = [
  5181. {id: 0, cost: 0, isBuy: false}, // plug // заглушка
  5182. {id: 1, cost: 1, isBuy: true}, // 3% attack // 3% атака
  5183. {id: 2, cost: 6, isBuy: true}, // 2% attack // 2% атака
  5184. {id: 3, cost: 16, isBuy: true}, // 4% attack // 4% атака
  5185. {id: 4, cost: 40, isBuy: true}, // 8% attack // 8% атака
  5186. {id: 5, cost: 1, isBuy: true}, // 10% armor // 10% броня
  5187. {id: 6, cost: 6, isBuy: true}, // 5% armor // 5% броня
  5188. {id: 7, cost: 16, isBuy: true}, // 10% armor // 10% броня
  5189. {id: 8, cost: 40, isBuy: true}, // 20% armor // 20% броня
  5190. { id: 9, cost: 1, isBuy: true }, // 10% protection from magic // 10% защита от магии
  5191. { id: 10, cost: 6, isBuy: true }, // 5% protection from magic // 5% защита от магии
  5192. { id: 11, cost: 16, isBuy: true }, // 10% protection from magic // 10% защита от магии
  5193. { id: 12, cost: 40, isBuy: true }, // 20% protection from magic // 20% защита от магии
  5194. { id: 13, cost: 1, isBuy: false }, // 40% health hero // 40% здоровья герою
  5195. { id: 14, cost: 6, isBuy: false }, // 40% health hero // 40% здоровья герою
  5196. { id: 15, cost: 16, isBuy: false }, // 80% health hero // 80% здоровья герою
  5197. { id: 16, cost: 40, isBuy: false }, // 40% health to all heroes // 40% здоровья всем героям
  5198. { id: 17, cost: 1, isBuy: false }, // 40% energy to the hero // 40% энергии герою
  5199. { id: 18, cost: 3, isBuy: false }, // 40% energy to the hero // 40% энергии герою
  5200. { id: 19, cost: 8, isBuy: false }, // 80% energy to the hero // 80% энергии герою
  5201. { id: 20, cost: 20, isBuy: false }, // 40% energy to all heroes // 40% энергии всем героям
  5202. { id: 21, cost: 40, isBuy: false }, // Hero Resurrection // Воскрешение героя
  5203. ]
  5204.  
  5205. this.start = function () {
  5206. send(JSON.stringify(callsExecuteTower), startTower);
  5207. }
  5208.  
  5209. /**
  5210. * Getting data on the Tower
  5211. *
  5212. * Получаем данные по башне
  5213. */
  5214. function startTower(e) {
  5215. res = e.results;
  5216. towerGetInfo = res[0].result.response;
  5217. if (!towerGetInfo) {
  5218. endTower('noTower', res);
  5219. return;
  5220. }
  5221. teamGetAll = res[1].result.response;
  5222. teamGetFavor = res[2].result.response;
  5223. inventoryGet = res[3].result.response;
  5224. heroGetAll = Object.values(res[4].result.response);
  5225.  
  5226. scullCoin = inventoryGet.coin[7] ?? 0;
  5227.  
  5228. argsBattle.favor = teamGetFavor.tower;
  5229. argsBattle.heroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5230. pet = teamGetAll.tower.filter(id => id >= 6000).pop();
  5231. if (pet) {
  5232. argsBattle.pet = pet;
  5233. }
  5234.  
  5235. checkFloor(towerGetInfo);
  5236. }
  5237.  
  5238. function fixHeroesTeam(argsBattle) {
  5239. let fixHeroes = argsBattle.heroes.filter(e => !heroesStates[e]?.isDead);
  5240. if (fixHeroes.length < 5) {
  5241. heroGetAll = heroGetAll.filter(e => !heroesStates[e.id]?.isDead);
  5242. fixHeroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5243. Object.keys(argsBattle.favor).forEach(e => {
  5244. if (!fixHeroes.includes(+e)) {
  5245. delete argsBattle.favor[e];
  5246. }
  5247. })
  5248. }
  5249. argsBattle.heroes = fixHeroes;
  5250. return argsBattle;
  5251. }
  5252.  
  5253. /**
  5254. * Check the floor
  5255. *
  5256. * Проверяем этаж
  5257. */
  5258. function checkFloor(towerInfo) {
  5259. lastTowerInfo = towerInfo;
  5260. maySkipFloor = +towerInfo.maySkipFloor;
  5261. floorNumber = +towerInfo.floorNumber;
  5262. heroesStates = towerInfo.states.heroes;
  5263. floorInfo = towerInfo.floor;
  5264.  
  5265. /**
  5266. * Is there at least one chest open on the floor
  5267. * Открыт ли на этаже хоть один сундук
  5268. */
  5269. isOpenChest = false;
  5270. if (towerInfo.floorType == "chest") {
  5271. isOpenChest = towerInfo.floor.chests.reduce((n, e) => n + e.opened, 0);
  5272. }
  5273.  
  5274. setProgress(`${I18N('TOWER')}: ${I18N('FLOOR')} ${floorNumber}`);
  5275. if (floorNumber > 49) {
  5276. if (isOpenChest) {
  5277. endTower('alreadyOpenChest 50 floor', floorNumber);
  5278. return;
  5279. }
  5280. }
  5281. /**
  5282. * If the chest is open and you can skip floors, then move on
  5283. * Если сундук открыт и можно скипать этажи, то переходим дальше
  5284. */
  5285. if (towerInfo.mayFullSkip && +towerInfo.teamLevel == 130) {
  5286. if (isOpenChest) {
  5287. nextOpenChest(floorNumber);
  5288. } else {
  5289. nextChestOpen(floorNumber);
  5290. }
  5291. return;
  5292. }
  5293.  
  5294. // console.log(towerInfo, scullCoin);
  5295. switch (towerInfo.floorType) {
  5296. case "battle":
  5297. if (floorNumber <= maySkipFloor) {
  5298. skipFloor();
  5299. return;
  5300. }
  5301. if (floorInfo.state == 2) {
  5302. nextFloor();
  5303. return;
  5304. }
  5305. startBattle().then(endBattle);
  5306. return;
  5307. case "buff":
  5308. checkBuff(towerInfo);
  5309. return;
  5310. case "chest":
  5311. openChest(floorNumber);
  5312. return;
  5313. default:
  5314. console.log('!', towerInfo.floorType, towerInfo);
  5315. break;
  5316. }
  5317. }
  5318.  
  5319. /**
  5320. * Let's start the fight
  5321. *
  5322. * Начинаем бой
  5323. */
  5324. function startBattle() {
  5325. return new Promise(function (resolve, reject) {
  5326. towerStartBattle = {
  5327. calls: [{
  5328. name: "towerStartBattle",
  5329. args: fixHeroesTeam(argsBattle),
  5330. ident: "body"
  5331. }]
  5332. }
  5333. send(JSON.stringify(towerStartBattle), resultBattle, resolve);
  5334. });
  5335. }
  5336. /**
  5337. * Returns the result of the battle in a promise
  5338. *
  5339. * Возращает резульат боя в промис
  5340. */
  5341. function resultBattle(resultBattles, resolve) {
  5342. battleData = resultBattles.results[0].result.response;
  5343. battleType = "get_tower";
  5344. BattleCalc(battleData, battleType, function (result) {
  5345. resolve(result);
  5346. });
  5347. }
  5348. /**
  5349. * Finishing the fight
  5350. *
  5351. * Заканчиваем бой
  5352. */
  5353. function endBattle(battleInfo) {
  5354. if (battleInfo.result.stars >= 3) {
  5355. endBattleCall = {
  5356. calls: [{
  5357. name: "towerEndBattle",
  5358. args: {
  5359. result: battleInfo.result,
  5360. progress: battleInfo.progress,
  5361. },
  5362. ident: "body"
  5363. }]
  5364. }
  5365. send(JSON.stringify(endBattleCall), resultEndBattle);
  5366. } else {
  5367. endTower('towerEndBattle win: false\n', battleInfo);
  5368. }
  5369. }
  5370.  
  5371. /**
  5372. * Getting and processing battle results
  5373. *
  5374. * Получаем и обрабатываем результаты боя
  5375. */
  5376. function resultEndBattle(e) {
  5377. battleResult = e.results[0].result.response;
  5378. if ('error' in battleResult) {
  5379. endTower('errorBattleResult', battleResult);
  5380. return;
  5381. }
  5382. if ('reward' in battleResult) {
  5383. scullCoin += battleResult.reward?.coin[7] ?? 0;
  5384. }
  5385. nextFloor();
  5386. }
  5387.  
  5388. function nextFloor() {
  5389. nextFloorCall = {
  5390. calls: [{
  5391. name: "towerNextFloor",
  5392. args: {},
  5393. ident: "body"
  5394. }]
  5395. }
  5396. send(JSON.stringify(nextFloorCall), checkDataFloor);
  5397. }
  5398.  
  5399. function openChest(floorNumber) {
  5400. floorNumber = floorNumber || 0;
  5401. openChestCall = {
  5402. calls: [{
  5403. name: "towerOpenChest",
  5404. args: {
  5405. num: 2
  5406. },
  5407. ident: "body"
  5408. }]
  5409. }
  5410. send(JSON.stringify(openChestCall), floorNumber < 50 ? nextFloor : lastChest);
  5411. }
  5412.  
  5413. function lastChest() {
  5414. endTower('openChest 50 floor', floorNumber);
  5415. }
  5416.  
  5417. function skipFloor() {
  5418. skipFloorCall = {
  5419. calls: [{
  5420. name: "towerSkipFloor",
  5421. args: {},
  5422. ident: "body"
  5423. }]
  5424. }
  5425. send(JSON.stringify(skipFloorCall), checkDataFloor);
  5426. }
  5427.  
  5428. function checkBuff(towerInfo) {
  5429. buffArr = towerInfo.floor;
  5430. promises = [];
  5431. for (let buff of buffArr) {
  5432. buffInfo = buffIds[buff.id];
  5433. if (buffInfo.isBuy && buffInfo.cost <= scullCoin) {
  5434. scullCoin -= buffInfo.cost;
  5435. promises.push(buyBuff(buff.id));
  5436. }
  5437. }
  5438. Promise.all(promises).then(nextFloor);
  5439. }
  5440.  
  5441. function buyBuff(buffId) {
  5442. return new Promise(function (resolve, reject) {
  5443. buyBuffCall = {
  5444. calls: [{
  5445. name: "towerBuyBuff",
  5446. args: {
  5447. buffId
  5448. },
  5449. ident: "body"
  5450. }]
  5451. }
  5452. send(JSON.stringify(buyBuffCall), resolve);
  5453. });
  5454. }
  5455.  
  5456. function checkDataFloor(result) {
  5457. towerInfo = result.results[0].result.response;
  5458. if ('reward' in towerInfo && towerInfo.reward?.coin) {
  5459. scullCoin += towerInfo.reward?.coin[7] ?? 0;
  5460. }
  5461. if ('tower' in towerInfo) {
  5462. towerInfo = towerInfo.tower;
  5463. }
  5464. if ('skullReward' in towerInfo) {
  5465. scullCoin += towerInfo.skullReward?.coin[7] ?? 0;
  5466. }
  5467. checkFloor(towerInfo);
  5468. }
  5469. /**
  5470. * Getting tower rewards
  5471. *
  5472. * Получаем награды башни
  5473. */
  5474. function farmTowerRewards(reason) {
  5475. let { pointRewards, points } = lastTowerInfo;
  5476. let pointsAll = Object.getOwnPropertyNames(pointRewards);
  5477. let farmPoints = pointsAll.filter(e => +e <= +points && !pointRewards[e]);
  5478. if (!farmPoints.length) {
  5479. return;
  5480. }
  5481. let farmTowerRewardsCall = {
  5482. calls: [{
  5483. name: "tower_farmPointRewards",
  5484. args: {
  5485. points: farmPoints
  5486. },
  5487. ident: "tower_farmPointRewards"
  5488. }]
  5489. }
  5490.  
  5491. if (scullCoin > 0 && reason == 'openChest 50 floor') {
  5492. farmTowerRewardsCall.calls.push({
  5493. name: "tower_farmSkullReward",
  5494. args: {},
  5495. ident: "tower_farmSkullReward"
  5496. });
  5497. }
  5498.  
  5499. send(JSON.stringify(farmTowerRewardsCall), () => { });
  5500. }
  5501.  
  5502. function fullSkipTower() {
  5503. /**
  5504. * Next chest
  5505. *
  5506. * Следующий сундук
  5507. */
  5508. function nextChest(n) {
  5509. return {
  5510. name: "towerNextChest",
  5511. args: {},
  5512. ident: "group_" + n + "_body"
  5513. }
  5514. }
  5515. /**
  5516. * Open chest
  5517. *
  5518. * Открыть сундук
  5519. */
  5520. function openChest(n) {
  5521. return {
  5522. name: "towerOpenChest",
  5523. args: {
  5524. "num": 2
  5525. },
  5526. ident: "group_" + n + "_body"
  5527. }
  5528. }
  5529.  
  5530. const fullSkipTowerCall = {
  5531. calls: []
  5532. }
  5533.  
  5534. let n = 0;
  5535. for (let i = 0; i < 15; i++) {
  5536. fullSkipTowerCall.calls.push(nextChest(++n));
  5537. fullSkipTowerCall.calls.push(openChest(++n));
  5538. }
  5539.  
  5540. send(JSON.stringify(fullSkipTowerCall), data => {
  5541. data.results[0] = data.results[28];
  5542. checkDataFloor(data);
  5543. });
  5544. }
  5545.  
  5546. function nextChestOpen(floorNumber) {
  5547. const calls = [{
  5548. name: "towerOpenChest",
  5549. args: {
  5550. num: 2
  5551. },
  5552. ident: "towerOpenChest"
  5553. }];
  5554.  
  5555. Send(JSON.stringify({ calls })).then(e => {
  5556. nextOpenChest(floorNumber);
  5557. });
  5558. }
  5559.  
  5560. function nextOpenChest(floorNumber) {
  5561. if (floorNumber > 49) {
  5562. endTower('openChest 50 floor', floorNumber);
  5563. return;
  5564. }
  5565. if (floorNumber == 1) {
  5566. fullSkipTower();
  5567. return;
  5568. }
  5569.  
  5570. let nextOpenChestCall = {
  5571. calls: [{
  5572. name: "towerNextChest",
  5573. args: {},
  5574. ident: "towerNextChest"
  5575. }, {
  5576. name: "towerOpenChest",
  5577. args: {
  5578. num: 2
  5579. },
  5580. ident: "towerOpenChest"
  5581. }]
  5582. }
  5583. send(JSON.stringify(nextOpenChestCall), checkDataFloor);
  5584. }
  5585.  
  5586. function endTower(reason, info) {
  5587. console.log(reason, info);
  5588. if (reason != 'noTower') {
  5589. farmTowerRewards(reason);
  5590. }
  5591. setProgress(`${I18N('TOWER')} ${I18N('COMPLETED')}!`, true);
  5592. resolve();
  5593. }
  5594. }
  5595.  
  5596. /**
  5597. * Passage of the arena of the titans
  5598. *
  5599. * Прохождение арены титанов
  5600. */
  5601. function testTitanArena() {
  5602. return new Promise((resolve, reject) => {
  5603. titAren = new executeTitanArena(resolve, reject);
  5604. titAren.start();
  5605. });
  5606. }
  5607.  
  5608. /**
  5609. * Passage of the arena of the titans
  5610. *
  5611. * Прохождение арены титанов
  5612. */
  5613. function executeTitanArena(resolve, reject) {
  5614. let titan_arena = [];
  5615. let finishListBattle = [];
  5616. /**
  5617. * ID of the current batch
  5618. *
  5619. * Идетификатор текущей пачки
  5620. */
  5621. let currentRival = 0;
  5622. /**
  5623. * Number of attempts to finish off the pack
  5624. *
  5625. * Количество попыток добития пачки
  5626. */
  5627. let attempts = 0;
  5628. /**
  5629. * Was there an attempt to finish off the current shooting range
  5630. *
  5631. * Была ли попытка добития текущего тира
  5632. */
  5633. let isCheckCurrentTier = false;
  5634. /**
  5635. * Current shooting range
  5636. *
  5637. * Текущий тир
  5638. */
  5639. let currTier = 0;
  5640. /**
  5641. * Number of battles on the current dash
  5642. *
  5643. * Количество битв на текущем тире
  5644. */
  5645. let countRivalsTier = 0;
  5646.  
  5647. let callsStart = {
  5648. calls: [{
  5649. name: "titanArenaGetStatus",
  5650. args: {},
  5651. ident: "titanArenaGetStatus"
  5652. }, {
  5653. name: "teamGetAll",
  5654. args: {},
  5655. ident: "teamGetAll"
  5656. }]
  5657. }
  5658.  
  5659. this.start = function () {
  5660. send(JSON.stringify(callsStart), startTitanArena);
  5661. }
  5662.  
  5663. function startTitanArena(data) {
  5664. let titanArena = data.results[0].result.response;
  5665. if (titanArena.status == 'disabled') {
  5666. endTitanArena('disabled', titanArena);
  5667. return;
  5668. }
  5669.  
  5670. let teamGetAll = data.results[1].result.response;
  5671. titan_arena = teamGetAll.titan_arena;
  5672.  
  5673. checkTier(titanArena)
  5674. }
  5675.  
  5676. function checkTier(titanArena) {
  5677. if (titanArena.status == "peace_time") {
  5678. endTitanArena('Peace_time', titanArena);
  5679. return;
  5680. }
  5681. currTier = titanArena.tier;
  5682. if (currTier) {
  5683. setProgress(`${I18N('TITAN_ARENA')}: ${I18N('LEVEL')} ${currTier}`);
  5684. }
  5685.  
  5686. if (titanArena.status == "completed_tier") {
  5687. titanArenaCompleteTier();
  5688. return;
  5689. }
  5690. /**
  5691. * Checking for the possibility of a raid
  5692. * Проверка на возможность рейда
  5693. */
  5694. if (titanArena.canRaid) {
  5695. titanArenaStartRaid();
  5696. return;
  5697. }
  5698. /**
  5699. * Check was an attempt to achieve the current shooting range
  5700. * Проверка была ли попытка добития текущего тира
  5701. */
  5702. if (!isCheckCurrentTier) {
  5703. checkRivals(titanArena.rivals);
  5704. return;
  5705. }
  5706.  
  5707. endTitanArena('Done or not canRaid', titanArena);
  5708. }
  5709. /**
  5710. * Submit dash information for verification
  5711. *
  5712. * Отправка информации о тире на проверку
  5713. */
  5714. function checkResultInfo(data) {
  5715. let titanArena = data.results[0].result.response;
  5716. checkTier(titanArena);
  5717. }
  5718. /**
  5719. * Finish the current tier
  5720. *
  5721. * Завершить текущий тир
  5722. */
  5723. function titanArenaCompleteTier() {
  5724. isCheckCurrentTier = false;
  5725. let calls = [{
  5726. name: "titanArenaCompleteTier",
  5727. args: {},
  5728. ident: "body"
  5729. }];
  5730. send(JSON.stringify({calls}), checkResultInfo);
  5731. }
  5732. /**
  5733. * Gathering points to be completed
  5734. *
  5735. * Собираем точки которые нужно добить
  5736. */
  5737. function checkRivals(rivals) {
  5738. finishListBattle = [];
  5739. for (let n in rivals) {
  5740. if (rivals[n].attackScore < 250) {
  5741. finishListBattle.push(n);
  5742. }
  5743. }
  5744. console.log('checkRivals', finishListBattle);
  5745. countRivalsTier = finishListBattle.length;
  5746. roundRivals();
  5747. }
  5748. /**
  5749. * Selecting the next point to finish off
  5750. *
  5751. * Выбор следующей точки для добития
  5752. */
  5753. function roundRivals() {
  5754. let countRivals = finishListBattle.length;
  5755. if (!countRivals) {
  5756. /**
  5757. * Whole range checked
  5758. *
  5759. * Весь тир проверен
  5760. */
  5761. isCheckCurrentTier = true;
  5762. titanArenaGetStatus();
  5763. return;
  5764. }
  5765. // setProgress('TitanArena: Уровень ' + currTier + ' Бои: ' + (countRivalsTier - countRivals + 1) + '/' + countRivalsTier);
  5766. currentRival = finishListBattle.pop();
  5767. attempts = +currentRival;
  5768. // console.log('roundRivals', currentRival);
  5769. titanArenaStartBattle(currentRival);
  5770. }
  5771. /**
  5772. * The start of a solo battle
  5773. *
  5774. * Начало одиночной битвы
  5775. */
  5776. function titanArenaStartBattle(rivalId) {
  5777. let calls = [{
  5778. name: "titanArenaStartBattle",
  5779. args: {
  5780. rivalId: rivalId,
  5781. titans: titan_arena
  5782. },
  5783. ident: "body"
  5784. }];
  5785. send(JSON.stringify({calls}), calcResult);
  5786. }
  5787. /**
  5788. * Calculation of the results of the battle
  5789. *
  5790. * Расчет результатов боя
  5791. */
  5792. function calcResult(data) {
  5793. let battlesInfo = data.results[0].result.response.battle;
  5794. /**
  5795. * If attempts are equal to the current battle number we make
  5796. * Если попытки равны номеру текущего боя делаем прерасчет
  5797. */
  5798. if (attempts == currentRival) {
  5799. preCalcBattle(battlesInfo);
  5800. return;
  5801. }
  5802. /**
  5803. * If there are still attempts, we calculate a new battle
  5804. * Если попытки еще есть делаем расчет нового боя
  5805. */
  5806. if (attempts > 0) {
  5807. attempts--;
  5808. calcBattleResult(battlesInfo)
  5809. .then(resultCalcBattle);
  5810. return;
  5811. }
  5812. /**
  5813. * Otherwise, go to the next opponent
  5814. * Иначе переходим к следующему сопернику
  5815. */
  5816. roundRivals();
  5817. }
  5818. /**
  5819. * Processing the results of the battle calculation
  5820. *
  5821. * Обработка результатов расчета битвы
  5822. */
  5823. function resultCalcBattle(resultBattle) {
  5824. // console.log('resultCalcBattle', currentRival, attempts, resultBattle.result.win);
  5825. /**
  5826. * If the current calculation of victory is not a chance or the attempt ended with the finish the battle
  5827. * Если текущий расчет победа или шансов нет или попытки кончились завершаем бой
  5828. */
  5829. if (resultBattle.result.win || !attempts) {
  5830. titanArenaEndBattle({
  5831. progress: resultBattle.progress,
  5832. result: resultBattle.result,
  5833. rivalId: resultBattle.battleData.typeId
  5834. });
  5835. return;
  5836. }
  5837. /**
  5838. * If not victory and there are attempts we start a new battle
  5839. * Если не победа и есть попытки начинаем новый бой
  5840. */
  5841. titanArenaStartBattle(resultBattle.battleData.typeId);
  5842. }
  5843. /**
  5844. * Returns the promise of calculating the results of the battle
  5845. *
  5846. * Возращает промис расчета результатов битвы
  5847. */
  5848. function getBattleInfo(battle, isRandSeed) {
  5849. return new Promise(function (resolve) {
  5850. if (isRandSeed) {
  5851. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  5852. }
  5853. // console.log(battle.seed);
  5854. BattleCalc(battle, "get_titanClanPvp", e => resolve(e));
  5855. });
  5856. }
  5857. /**
  5858. * Recalculate battles
  5859. *
  5860. * Прерасчтет битвы
  5861. */
  5862. function preCalcBattle(battle) {
  5863. let actions = [getBattleInfo(battle, false)];
  5864. const countTestBattle = getInput('countTestBattle');
  5865. for (let i = 0; i < countTestBattle; i++) {
  5866. actions.push(getBattleInfo(battle, true));
  5867. }
  5868. Promise.all(actions)
  5869. .then(resultPreCalcBattle);
  5870. }
  5871. /**
  5872. * Processing the results of the battle recalculation
  5873. *
  5874. * Обработка результатов прерасчета битвы
  5875. */
  5876. function resultPreCalcBattle(e) {
  5877. let wins = e.map(n => n.result.win);
  5878. let firstBattle = e.shift();
  5879. let countWin = wins.reduce((w, s) => w + s);
  5880. const countTestBattle = getInput('countTestBattle');
  5881. console.log('resultPreCalcBattle', `${countWin}/${countTestBattle}`)
  5882. if (countWin > 0) {
  5883. attempts = getInput('countAutoBattle');
  5884. } else {
  5885. attempts = 0;
  5886. }
  5887. resultCalcBattle(firstBattle);
  5888. }
  5889.  
  5890. /**
  5891. * Complete an arena battle
  5892. *
  5893. * Завершить битву на арене
  5894. */
  5895. function titanArenaEndBattle(args) {
  5896. let calls = [{
  5897. name: "titanArenaEndBattle",
  5898. args,
  5899. ident: "body"
  5900. }];
  5901. send(JSON.stringify({calls}), resultTitanArenaEndBattle);
  5902. }
  5903.  
  5904. function resultTitanArenaEndBattle(e) {
  5905. let attackScore = e.results[0].result.response.attackScore;
  5906. let numReval = countRivalsTier - finishListBattle.length;
  5907. setProgress(`${I18N('TITAN_ARENA')}: ${I18N('LEVEL')} ${currTier} </br>${I18N('BATTLES')}: ${numReval}/${countRivalsTier} - ${attackScore}`);
  5908. /**
  5909. * TODO: Might need to improve the results.
  5910. * TODO: Возможно стоит сделать улучшение результатов
  5911. */
  5912. // console.log('resultTitanArenaEndBattle', e)
  5913. console.log('resultTitanArenaEndBattle', numReval + '/' + countRivalsTier, attempts)
  5914. roundRivals();
  5915. }
  5916. /**
  5917. * Arena State
  5918. *
  5919. * Состояние арены
  5920. */
  5921. function titanArenaGetStatus() {
  5922. let calls = [{
  5923. name: "titanArenaGetStatus",
  5924. args: {},
  5925. ident: "body"
  5926. }];
  5927. send(JSON.stringify({calls}), checkResultInfo);
  5928. }
  5929. /**
  5930. * Arena Raid Request
  5931. *
  5932. * Запрос рейда арены
  5933. */
  5934. function titanArenaStartRaid() {
  5935. let calls = [{
  5936. name: "titanArenaStartRaid",
  5937. args: {
  5938. titans: titan_arena
  5939. },
  5940. ident: "body"
  5941. }];
  5942. send(JSON.stringify({calls}), calcResults);
  5943. }
  5944.  
  5945. function calcResults(data) {
  5946. let battlesInfo = data.results[0].result.response;
  5947. let {attackers, rivals} = battlesInfo;
  5948.  
  5949. let promises = [];
  5950. for (let n in rivals) {
  5951. rival = rivals[n];
  5952. promises.push(calcBattleResult({
  5953. attackers: attackers,
  5954. defenders: [rival.team],
  5955. seed: rival.seed,
  5956. typeId: n,
  5957. }));
  5958. }
  5959.  
  5960. Promise.all(promises)
  5961. .then(results => {
  5962. const endResults = {};
  5963. for (let info of results) {
  5964. let id = info.battleData.typeId;
  5965. endResults[id] = {
  5966. progress: info.progress,
  5967. result: info.result,
  5968. }
  5969. }
  5970. titanArenaEndRaid(endResults);
  5971. });
  5972. }
  5973.  
  5974. function calcBattleResult(battleData) {
  5975. return new Promise(function (resolve, reject) {
  5976. BattleCalc(battleData, "get_titanClanPvp", resolve);
  5977. });
  5978. }
  5979.  
  5980. /**
  5981. * Sending Raid Results
  5982. *
  5983. * Отправка результатов рейда
  5984. */
  5985. function titanArenaEndRaid(results) {
  5986. titanArenaEndRaidCall = {
  5987. calls: [{
  5988. name: "titanArenaEndRaid",
  5989. args: {
  5990. results
  5991. },
  5992. ident: "body"
  5993. }]
  5994. }
  5995. send(JSON.stringify(titanArenaEndRaidCall), checkRaidResults);
  5996. }
  5997.  
  5998. function checkRaidResults(data) {
  5999. results = data.results[0].result.response.results;
  6000. isSucsesRaid = true;
  6001. for (let i in results) {
  6002. isSucsesRaid &&= (results[i].attackScore >= 250);
  6003. }
  6004.  
  6005. if (isSucsesRaid) {
  6006. titanArenaCompleteTier();
  6007. } else {
  6008. titanArenaGetStatus();
  6009. }
  6010. }
  6011.  
  6012. function titanArenaFarmDailyReward() {
  6013. titanArenaFarmDailyRewardCall = {
  6014. calls: [{
  6015. name: "titanArenaFarmDailyReward",
  6016. args: {},
  6017. ident: "body"
  6018. }]
  6019. }
  6020. send(JSON.stringify(titanArenaFarmDailyRewardCall), () => {console.log('Done farm daily reward')});
  6021. }
  6022.  
  6023. function endTitanArena(reason, info) {
  6024. if (!['Peace_time', 'disabled'].includes(reason)) {
  6025. titanArenaFarmDailyReward();
  6026. }
  6027. console.log(reason, info);
  6028. setProgress(`${I18N('TITAN_ARENA')} ${I18N('COMPLETED')}!`, true);
  6029. resolve();
  6030. }
  6031. }
  6032.  
  6033. function hackGame() {
  6034. self = this;
  6035. selfGame = null;
  6036. bindId = 1e9;
  6037. this.libGame = null;
  6038.  
  6039. /**
  6040. * List of correspondence of used classes to their names
  6041. *
  6042. * Список соответствия используемых классов их названиям
  6043. */
  6044. ObjectsList = [
  6045. {name:"BattlePresets", prop:"game.battle.controller.thread.BattlePresets"},
  6046. {name:"DataStorage", prop:"game.data.storage.DataStorage"},
  6047. {name:"BattleConfigStorage", prop:"game.data.storage.battle.BattleConfigStorage"},
  6048. {name:"BattleInstantPlay", prop:"game.battle.controller.instant.BattleInstantPlay"},
  6049. {name:"MultiBattleResult", prop:"game.battle.controller.MultiBattleResult"},
  6050.  
  6051. {name:"PlayerMissionData", prop:"game.model.user.mission.PlayerMissionData"},
  6052. {name:"PlayerMissionBattle", prop:"game.model.user.mission.PlayerMissionBattle"},
  6053. {name:"GameModel", prop:"game.model.GameModel"},
  6054. {name:"CommandManager", prop:"game.command.CommandManager"},
  6055. {name:"MissionCommandList", prop:"game.command.rpc.mission.MissionCommandList"},
  6056. {name:"RPCCommandBase", prop:"game.command.rpc.RPCCommandBase"},
  6057. {name:"PlayerTowerData", prop:"game.model.user.tower.PlayerTowerData"},
  6058. {name:"TowerCommandList", prop:"game.command.tower.TowerCommandList"},
  6059. {name:"PlayerHeroTeamResolver", prop:"game.model.user.hero.PlayerHeroTeamResolver"},
  6060. {name:"BattlePausePopup", prop:"game.view.popup.battle.BattlePausePopup"},
  6061. {name:"BattlePopup", prop:"game.view.popup.battle.BattlePopup"},
  6062. {name:"DisplayObjectContainer", prop:"starling.display.DisplayObjectContainer"},
  6063. {name:"GuiClipContainer", prop:"engine.core.clipgui.GuiClipContainer"},
  6064. {name:"BattlePausePopupClip", prop:"game.view.popup.battle.BattlePausePopupClip"},
  6065. {name:"ClipLabel", prop:"game.view.gui.components.ClipLabel"},
  6066. {name:"ClipLabelBase", prop:"game.view.gui.components.ClipLabelBase"},
  6067. {name:"Translate", prop:"com.progrestar.common.lang.Translate"},
  6068. {name:"ClipButtonLabeledCentered", prop:"game.view.gui.components.ClipButtonLabeledCentered"},
  6069. {name:"BattlePausePopupMediator", prop:"game.mediator.gui.popup.battle.BattlePausePopupMediator"},
  6070. {name:"SettingToggleButton", prop:"game.mechanics.settings.popup.view.SettingToggleButton"},
  6071. {name:"PlayerDungeonData", prop:"game.mechanics.dungeon.model.PlayerDungeonData"},
  6072. {name:"NextDayUpdatedManager", prop:"game.model.user.NextDayUpdatedManager"},
  6073. {name:"BattleController", prop:"game.battle.controller.BattleController"},
  6074. {name:"BattleSettingsModel", prop:"game.battle.controller.BattleSettingsModel"},
  6075. {name:"BooleanProperty", prop:"engine.core.utils.property.BooleanProperty"},
  6076. {name:"RuleStorage", prop:"game.data.storage.rule.RuleStorage"},
  6077. {name:"BattleConfig", prop:"battle.BattleConfig"},
  6078. {name:"BattleGuiMediator", prop:"game.battle.gui.BattleGuiMediator"},
  6079. {name:"BooleanPropertyWriteable", prop:"engine.core.utils.property.BooleanPropertyWriteable"},
  6080. { name: "BattleLogEncoder", prop: "battle.log.BattleLogEncoder" },
  6081. { name: "BattleLogReader", prop: "battle.log.BattleLogReader" },
  6082. { name: "PlayerSubscriptionInfoValueObject", prop: "game.model.user.subscription.PlayerSubscriptionInfoValueObject" },
  6083. ];
  6084.  
  6085. /**
  6086. * Contains the game classes needed to write and override game methods
  6087. *
  6088. * Содержит классы игры необходимые для написания и подмены методов игры
  6089. */
  6090. Game = {
  6091. /**
  6092. * Function 'e'
  6093. * Функция 'e'
  6094. */
  6095. bindFunc: function (a, b) {
  6096. if (null == b)
  6097. return null;
  6098. null == b.__id__ && (b.__id__ = bindId++);
  6099. var c;
  6100. null == a.hx__closures__ ? a.hx__closures__ = {} :
  6101. c = a.hx__closures__[b.__id__];
  6102. null == c && (c = b.bind(a), a.hx__closures__[b.__id__] = c);
  6103. return c
  6104. },
  6105. };
  6106.  
  6107. /**
  6108. * Connects to game objects via the object creation event
  6109. *
  6110. * Подключается к объектам игры через событие создания объекта
  6111. */
  6112. function connectGame() {
  6113. for (let obj of ObjectsList) {
  6114. /**
  6115. * https: //stackoverflow.com/questions/42611719/how-to-intercept-and-modify-a-specific-property-for-any-object
  6116. */
  6117. Object.defineProperty(Object.prototype, obj.prop, {
  6118. set: function (value) {
  6119. if (!selfGame) {
  6120. selfGame = this;
  6121. }
  6122. if (!Game[obj.name]) {
  6123. Game[obj.name] = value;
  6124. }
  6125. // console.log('set ' + obj.prop, this, value);
  6126. this[obj.prop + '_'] = value;
  6127. },
  6128. get: function () {
  6129. // console.log('get ' + obj.prop, this);
  6130. return this[obj.prop + '_'];
  6131. }
  6132. });
  6133. }
  6134. }
  6135.  
  6136. /**
  6137. * Game.BattlePresets
  6138. * @param {bool} a isReplay
  6139. * @param {bool} b autoToggleable
  6140. * @param {bool} c auto On Start
  6141. * @param {object} d config
  6142. * @param {bool} f showBothTeams
  6143. */
  6144. /**
  6145. * Returns the results of the battle to the callback function
  6146. * Возвращает в функцию callback результаты боя
  6147. * @param {*} battleData battle data данные боя
  6148. * @param {*} battleConfig combat configuration type options:
  6149. *
  6150. * тип конфигурации боя варианты:
  6151. *
  6152. * "get_invasion", "get_titanPvpManual", "get_titanPvp",
  6153. * "get_titanClanPvp","get_clanPvp","get_titan","get_boss",
  6154. * "get_tower","get_pve","get_pvpManual","get_pvp","get_core"
  6155. *
  6156. * You can specify the xYc function in the game.assets.storage.BattleAssetStorage class
  6157. *
  6158. * Можно уточнить в классе game.assets.storage.BattleAssetStorage функция xYc
  6159. * @param {*} callback функция в которую вернуться результаты боя
  6160. */
  6161. this.BattleCalc = function (battleData, battleConfig, callback) {
  6162. // battleConfig = battleConfig || getBattleType(battleData.type)
  6163. if (!Game.BattlePresets) throw Error('Use connectGame');
  6164. battlePresets = new Game.BattlePresets(!!battleData.progress, !1, !0, Game.DataStorage[getFn(Game.DataStorage, 24)][getF(Game.BattleConfigStorage, battleConfig)](), !1);
  6165. battleInstantPlay = new Game.BattleInstantPlay(battleData, battlePresets);
  6166. battleInstantPlay[getProtoFn(Game.BattleInstantPlay, 9)].add((battleInstant) => {
  6167. const battleResult = battleInstant[getF(Game.BattleInstantPlay, 'get_result')]();
  6168. const battleData = battleInstant[getF(Game.BattleInstantPlay, 'get_rawBattleInfo')]();
  6169. const battleLog = Game.BattleLogEncoder.read(new Game.BattleLogReader(battleResult[getProtoFn(Game.MultiBattleResult, 2)][0]));
  6170. const timeLimit = battlePresets[getF(Game.BattlePresets, 'get_timeLimit')]();
  6171. const battleTime = Math.max(...battleLog.map((e) => (e.time < timeLimit && e.time !== 168.8 ? e.time : 0)));
  6172. callback({
  6173. battleTime,
  6174. battleData,
  6175. progress: battleResult[getF(Game.MultiBattleResult, 'get_progress')](),
  6176. result: battleResult[getF(Game.MultiBattleResult, 'get_result')]()
  6177. })
  6178. });
  6179. battleInstantPlay.start();
  6180. }
  6181.  
  6182. /**
  6183. * Returns a function with the specified name from the class
  6184. *
  6185. * Возвращает из класса функцию с указанным именем
  6186. * @param {Object} classF Class // класс
  6187. * @param {String} nameF function name // имя функции
  6188. * @param {String} pos name and alias order // порядок имени и псевдонима
  6189. * @returns
  6190. */
  6191. function getF(classF, nameF, pos) {
  6192. pos = pos || false;
  6193. let prop = Object.entries(classF.prototype.__properties__)
  6194. if (!pos) {
  6195. return prop.filter((e) => e[1] == nameF).pop()[0];
  6196. } else {
  6197. return prop.filter((e) => e[0] == nameF).pop()[1];
  6198. }
  6199. }
  6200.  
  6201. /**
  6202. * Returns a function with the specified name from the class
  6203. *
  6204. * Возвращает из класса функцию с указанным именем
  6205. * @param {Object} classF Class // класс
  6206. * @param {String} nameF function name // имя функции
  6207. * @returns
  6208. */
  6209. function getFnP(classF, nameF) {
  6210. let prop = Object.entries(classF.__properties__)
  6211. return prop.filter((e) => e[1] == nameF).pop()[0];
  6212. }
  6213.  
  6214. /**
  6215. * Returns the function name with the specified ordinal from the class
  6216. *
  6217. * Возвращает имя функции с указаным порядковым номером из класса
  6218. * @param {Object} classF Class // класс
  6219. * @param {Number} nF Order number of function // порядковый номер функции
  6220. * @returns
  6221. */
  6222. function getFn(classF, nF) {
  6223. let prop = Object.keys(classF);
  6224. return prop[nF];
  6225. }
  6226.  
  6227. /**
  6228. * Returns the name of the function with the specified serial number from the prototype of the class
  6229. *
  6230. * Возвращает имя функции с указаным порядковым номером из прототипа класса
  6231. * @param {Object} classF Class // класс
  6232. * @param {Number} nF Order number of function // порядковый номер функции
  6233. * @returns
  6234. */
  6235. function getProtoFn(classF, nF) {
  6236. let prop = Object.keys(classF.prototype);
  6237. return prop[nF];
  6238. }
  6239. /**
  6240. * Description of replaced functions
  6241. *
  6242. * Описание подменяемых функций
  6243. */
  6244. replaceFunction = {
  6245. company: function() {
  6246. let PMD_12 = getProtoFn(Game.PlayerMissionData, 12);
  6247. let oldSkipMisson = Game.PlayerMissionData.prototype[PMD_12];
  6248. Game.PlayerMissionData.prototype[PMD_12] = function (a, b, c) {
  6249. if (!isChecked('passBattle')) {
  6250. oldSkipMisson.call(this, a, b, c);
  6251. return;
  6252. }
  6253.  
  6254. try {
  6255. this[getProtoFn(Game.PlayerMissionData, 9)] = new Game.PlayerMissionBattle(a, b, c);
  6256.  
  6257. var a = new Game.BattlePresets(!1, !1, !0, Game.DataStorage[getFn(Game.DataStorage, 24)][getProtoFn(Game.BattleConfigStorage, 20)](), !1);
  6258. a = new Game.BattleInstantPlay(c, a);
  6259. a[getProtoFn(Game.BattleInstantPlay, 9)].add(Game.bindFunc(this, this.P$h));
  6260. a.start()
  6261. } catch (error) {
  6262. console.error('company', error)
  6263. oldSkipMisson.call(this, a, b, c);
  6264. }
  6265. }
  6266.  
  6267. Game.PlayerMissionData.prototype.P$h = function (a) {
  6268. let GM_2 = getFn(Game.GameModel, 2);
  6269. let GM_P2 = getProtoFn(Game.GameModel, 2);
  6270. let CM_20 = getProtoFn(Game.CommandManager, 20);
  6271. let MCL_2 = getProtoFn(Game.MissionCommandList, 2);
  6272. let MBR_15 = getF(Game.MultiBattleResult, "get_result");
  6273. let RPCCB_15 = getProtoFn(Game.RPCCommandBase, 16);
  6274. let PMD_32 = getProtoFn(Game.PlayerMissionData, 32);
  6275. Game.GameModel[GM_2]()[GM_P2][CM_20][MCL_2](a[MBR_15]())[RPCCB_15](Game.bindFunc(this, this[PMD_32]))
  6276. }
  6277. },
  6278. tower: function() {
  6279. let PTD_67 = getProtoFn(Game.PlayerTowerData, 67);
  6280. let oldSkipTower = Game.PlayerTowerData.prototype[PTD_67];
  6281. Game.PlayerTowerData.prototype[PTD_67] = function (a) {
  6282. if (!isChecked('passBattle')) {
  6283. oldSkipTower.call(this, a);
  6284. return;
  6285. }
  6286. try {
  6287. var p = new Game.BattlePresets(!1, !1, !0, Game.DataStorage[getFn(Game.DataStorage, 24)][getProtoFn(Game.BattleConfigStorage,20)](), !1);
  6288. a = new Game.BattleInstantPlay(a, p);
  6289. a[getProtoFn(Game.BattleInstantPlay, 9)].add(Game.bindFunc(this, this.P$h));
  6290. a.start()
  6291. } catch (error) {
  6292. console.error('tower', error)
  6293. oldSkipMisson.call(this, a, b, c);
  6294. }
  6295. }
  6296.  
  6297. Game.PlayerTowerData.prototype.P$h = function (a) {
  6298. const GM_2 = getFnP(Game.GameModel, "get_instance");
  6299. const GM_P2 = getProtoFn(Game.GameModel, 2);
  6300. const CM_29 = getProtoFn(Game.CommandManager, 29);
  6301. const TCL_5 = getProtoFn(Game.TowerCommandList, 5);
  6302. const MBR_15 = getF(Game.MultiBattleResult, "get_result");
  6303. const RPCCB_15 = getProtoFn(Game.RPCCommandBase, 17);
  6304. const PTD_78 = getProtoFn(Game.PlayerTowerData, 78);
  6305. Game.GameModel[GM_2]()[GM_P2][CM_29][TCL_5](a[MBR_15]())[RPCCB_15](Game.bindFunc(this, this[PTD_78]));
  6306. }
  6307. },
  6308. // skipSelectHero: function() {
  6309. // if (!HOST) throw Error('Use connectGame');
  6310. // Game.PlayerHeroTeamResolver.prototype[getProtoFn(Game.PlayerHeroTeamResolver, 3)] = () => false;
  6311. // },
  6312. passBattle: function() {
  6313. let BPP_4 = getProtoFn(Game.BattlePausePopup, 4);
  6314. let oldPassBattle = Game.BattlePausePopup.prototype[BPP_4];
  6315. Game.BattlePausePopup.prototype[BPP_4] = function (a) {
  6316. if (!isChecked('passBattle')) {
  6317. oldPassBattle.call(this, a);
  6318. return;
  6319. }
  6320. try {
  6321. Game.BattlePopup.prototype[getProtoFn(Game.BattlePausePopup, 4)].call(this, a);
  6322. this[getProtoFn(Game.BattlePausePopup, 3)]();
  6323. this[getProtoFn(Game.DisplayObjectContainer, 3)](this.clip[getProtoFn(Game.GuiClipContainer, 2)]());
  6324. this.clip[getProtoFn(Game.BattlePausePopupClip, 1)][getProtoFn(Game.ClipLabelBase, 9)](Game.Translate.translate("UI_POPUP_BATTLE_PAUSE"));
  6325.  
  6326. 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)])));
  6327. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 2)](
  6328. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 14)](),
  6329. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 13)]() ?
  6330. (q = this[getProtoFn(Game.BattlePausePopup, 1)], Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 18)])) :
  6331. (q = this[getProtoFn(Game.BattlePausePopup, 1)], Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 18)]))
  6332. );
  6333.  
  6334. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 0)][getProtoFn(Game.ClipLabelBase, 24)]();
  6335. this.clip[getProtoFn(Game.BattlePausePopupClip, 3)][getProtoFn(Game.SettingToggleButton, 3)](this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 9)]());
  6336. this.clip[getProtoFn(Game.BattlePausePopupClip, 4)][getProtoFn(Game.SettingToggleButton, 3)](this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 10)]());
  6337. this.clip[getProtoFn(Game.BattlePausePopupClip, 6)][getProtoFn(Game.SettingToggleButton, 3)](this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 11)]());
  6338. } catch(error) {
  6339. console.error('passBattle', error)
  6340. oldPassBattle.call(this, a);
  6341. }
  6342. }
  6343.  
  6344. let retreatButtonLabel = getF(Game.BattlePausePopupMediator, "get_retreatButtonLabel");
  6345. let oldFunc = Game.BattlePausePopupMediator.prototype[retreatButtonLabel];
  6346. Game.BattlePausePopupMediator.prototype[retreatButtonLabel] = function () {
  6347. if (isChecked('passBattle')) {
  6348. return I18N('BTN_PASS');
  6349. } else {
  6350. return oldFunc.call(this);
  6351. }
  6352. }
  6353. },
  6354. endlessCards: function() {
  6355. let PDD_20 = getProtoFn(Game.PlayerDungeonData, 20);
  6356. let oldEndlessCards = Game.PlayerDungeonData.prototype[PDD_20];
  6357. Game.PlayerDungeonData.prototype[PDD_20] = function () {
  6358. if (countPredictionCard <= 0) {
  6359. return true;
  6360. } else {
  6361. return oldEndlessCards.call(this);
  6362. }
  6363. }
  6364. },
  6365. speedBattle: function () {
  6366. const get_timeScale = getF(Game.BattleController, "get_timeScale");
  6367. const oldSpeedBattle = Game.BattleController.prototype[get_timeScale];
  6368. Game.BattleController.prototype[get_timeScale] = function () {
  6369. const speedBattle = Number.parseFloat(getInput('speedBattle'));
  6370. if (!speedBattle) {
  6371. return oldSpeedBattle.call(this);
  6372. }
  6373. try {
  6374. const BC_12 = getProtoFn(Game.BattleController, 12);
  6375. const BSM_12 = getProtoFn(Game.BattleSettingsModel, 12);
  6376. const BP_get_value = getF(Game.BooleanProperty, "get_value");
  6377. if (this[BC_12][BSM_12][BP_get_value]()) {
  6378. return 0;
  6379. }
  6380. const BSM_2 = getProtoFn(Game.BattleSettingsModel, 2);
  6381. const BC_49 = getProtoFn(Game.BattleController, 49);
  6382. const BSM_1 = getProtoFn(Game.BattleSettingsModel, 1);
  6383. const BC_14 = getProtoFn(Game.BattleController, 14);
  6384. const BC_3 = getFn(Game.BattleController, 3);
  6385. if (this[BC_12][BSM_2][BP_get_value]()) {
  6386. var a = speedBattle * this[BC_49]();
  6387. } else {
  6388. a = this[BC_12][BSM_1][BP_get_value]();
  6389. const maxSpeed = Math.max(...this[BC_14]);
  6390. const multiple = a == this[BC_14].indexOf(maxSpeed) ? (maxSpeed >= 4 ? speedBattle : this[BC_14][a]) : this[BC_14][a];
  6391. a = multiple * Game.BattleController[BC_3][BP_get_value]() * this[BC_49]();
  6392. }
  6393. const BSM_24 = getProtoFn(Game.BattleSettingsModel, 24);
  6394. a > this[BC_12][BSM_24][BP_get_value]() && (a = this[BC_12][BSM_24][BP_get_value]());
  6395. const DS_23 = getFn(Game.DataStorage, 23);
  6396. const get_battleSpeedMultiplier = getF(Game.RuleStorage, "get_battleSpeedMultiplier", true);
  6397. var b = Game.DataStorage[DS_23][get_battleSpeedMultiplier]();
  6398. const R_1 = getFn(selfGame.Reflect, 1);
  6399. const BC_1 = getFn(Game.BattleController, 1);
  6400. const get_config = getF(Game.BattlePresets, "get_config");
  6401. 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"));
  6402. return a
  6403. } catch(error) {
  6404. console.error('passBatspeedBattletle', error)
  6405. return oldSpeedBattle.call(this);
  6406. }
  6407. }
  6408. },
  6409.  
  6410. /**
  6411. * Acceleration button without Valkyries favor
  6412. *
  6413. * Кнопка ускорения без Покровительства Валькирий
  6414. */
  6415. battleFastKey: function () {
  6416. const PSIVO_9 = getProtoFn(Game.PlayerSubscriptionInfoValueObject, 9);
  6417. const oldBattleFastKey = Game.PlayerSubscriptionInfoValueObject.prototype[PSIVO_9];
  6418. Game.PlayerSubscriptionInfoValueObject.prototype[PSIVO_9] = function () {
  6419. //const BGM_42 = getProtoFn(Game.BattleGuiMediator, 42);
  6420. //const oldBattleFastKey = Game.BattleGuiMediator.prototype[BGM_42];
  6421. //Game.BattleGuiMediator.prototype[BGM_42] = function () {
  6422. let flag = true;
  6423. //console.log(flag)
  6424. if (flag) {
  6425. return true;
  6426. } else {
  6427. return oldBattleFastKey.call(this);
  6428. }
  6429. /*
  6430. if (!flag) {
  6431. return oldBattleFastKey.call(this);
  6432. }
  6433. try {
  6434. const BGM_9 = getProtoFn(Game.BattleGuiMediator, 9);
  6435. const BGM_10 = getProtoFn(Game.BattleGuiMediator, 10);
  6436. const BPW_0 = getProtoFn(Game.BooleanPropertyWriteable, 0);
  6437. this[BGM_9][BPW_0](true);
  6438. this[BGM_10][BPW_0](true);
  6439. } catch (error) {
  6440. console.error(error);
  6441. return oldBattleFastKey.call(this);
  6442. }*/
  6443. }
  6444. },
  6445. /* ТЕСТ 2.240
  6446. battleFastKey: function () {
  6447. const BGM_43 = getProtoFn(Game.BattleGuiMediator, 43);
  6448. const oldBattleFastKey = Game.BattleGuiMediator.prototype[BGM_43];
  6449. Game.BattleGuiMediator.prototype[BGM_43] = function () {
  6450. let flag = true;
  6451. //console.log(flag)
  6452. if (!flag) {
  6453. return oldBattleFastKey.call(this);
  6454. }
  6455. try {
  6456. const BGM_9 = getProtoFn(Game.BattleGuiMediator, 9);
  6457. const BGM_10 = getProtoFn(Game.BattleGuiMediator, 10);
  6458. const BPW_0 = getProtoFn(Game.BooleanPropertyWriteable, 0);
  6459. this[BGM_9][BPW_0](true);
  6460. this[BGM_10][BPW_0](true);
  6461. } catch (error) {
  6462. console.error(error);
  6463. return oldBattleFastKey.call(this);
  6464. }
  6465. }
  6466. },*/
  6467. fastSeason: function () {
  6468. const GameNavigator = selfGame["game.screen.navigator.GameNavigator"];
  6469. const oldFuncName = getProtoFn(GameNavigator, 16);
  6470. const newFuncName = getProtoFn(GameNavigator, 14);
  6471. const oldFastSeason = GameNavigator.prototype[oldFuncName];
  6472. const newFastSeason = GameNavigator.prototype[newFuncName];
  6473. GameNavigator.prototype[oldFuncName] = function (a, b) {
  6474. if (isChecked('fastSeason')) {
  6475. return newFastSeason.apply(this, [a]);
  6476. } else {
  6477. return oldFastSeason.apply(this, [a, b]);
  6478. }
  6479. }
  6480. },
  6481. ShowChestReward: function () {
  6482. const TitanArtifactChest = selfGame["game.mechanics.titan_arena.mediator.chest.TitanArtifactChestRewardPopupMediator"];
  6483. const getOpenAmountTitan = getF(TitanArtifactChest, "get_openAmount");
  6484. const oldGetOpenAmountTitan = TitanArtifactChest.prototype[getOpenAmountTitan];
  6485. TitanArtifactChest.prototype[getOpenAmountTitan] = function () {
  6486. if (correctShowOpenArtifact) {
  6487. correctShowOpenArtifact--;
  6488. return 100;
  6489. }
  6490. return oldGetOpenAmountTitan.call(this);
  6491. }
  6492.  
  6493. const ArtifactChest = selfGame["game.view.popup.artifactchest.rewardpopup.ArtifactChestRewardPopupMediator"];
  6494. const getOpenAmount = getF(ArtifactChest, "get_openAmount");
  6495. const oldGetOpenAmount = ArtifactChest.prototype[getOpenAmount];
  6496. ArtifactChest.prototype[getOpenAmount] = function () {
  6497. if (correctShowOpenArtifact) {
  6498. correctShowOpenArtifact--;
  6499. return 100;
  6500. }
  6501. return oldGetOpenAmount.call(this);
  6502. }
  6503.  
  6504. },
  6505. fixCompany: function () {
  6506. const GameBattleView = selfGame["game.mediator.gui.popup.battle.GameBattleView"];
  6507. const BattleThread = selfGame["game.battle.controller.thread.BattleThread"];
  6508. const getOnViewDisposed = getF(BattleThread, 'get_onViewDisposed');
  6509. const getThread = getF(GameBattleView, 'get_thread');
  6510. const oldFunc = GameBattleView.prototype[getThread];
  6511. GameBattleView.prototype[getThread] = function () {
  6512. return oldFunc.call(this) || {
  6513. [getOnViewDisposed]: async () => { }
  6514. }
  6515. }
  6516. }
  6517. }
  6518.  
  6519. /**
  6520. * Starts replacing recorded functions
  6521. *
  6522. * Запускает замену записанных функций
  6523. */
  6524. this.activateHacks = function () {
  6525. if (!selfGame) throw Error('Use connectGame');
  6526. for (let func in replaceFunction) {
  6527. replaceFunction[func]();
  6528. }
  6529. }
  6530.  
  6531. /**
  6532. * Returns the game object
  6533. *
  6534. * Возвращает объект игры
  6535. */
  6536. this.getSelfGame = function () {
  6537. return selfGame;
  6538. }
  6539.  
  6540. /**
  6541. * Updates game data
  6542. *
  6543. * Обновляет данные игры
  6544. */
  6545. this.refreshGame = function () {
  6546. (new Game.NextDayUpdatedManager)[getProtoFn(Game.NextDayUpdatedManager, 5)]();
  6547. try {
  6548. cheats.refreshInventory();
  6549. } catch (e) { }
  6550. }
  6551.  
  6552. /**
  6553. * Update inventory
  6554. *
  6555. * Обновляет инвентарь
  6556. */
  6557. this.refreshInventory = async function () {
  6558. const GM_INST = getFnP(Game.GameModel, "get_instance");
  6559. const GM_0 = getProtoFn(Game.GameModel, 0);
  6560. const P_24 = getProtoFn(selfGame["game.model.user.Player"], 24);
  6561. const Player = Game.GameModel[GM_INST]()[GM_0];
  6562. Player[P_24] = new selfGame["game.model.user.inventory.PlayerInventory"]
  6563. Player[P_24].init(await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"}]}').then(e => e.results[0].result.response))
  6564. }
  6565.  
  6566. /**
  6567. * Change the play screen on windowName
  6568. *
  6569. * Сменить экран игры на windowName
  6570. *
  6571. * Possible options:
  6572. *
  6573. * Возможные варианты:
  6574. *
  6575. * 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
  6576. */
  6577. this.goNavigtor = function (windowName) {
  6578. let mechanicStorage = selfGame["game.data.storage.mechanic.MechanicStorage"];
  6579. let window = mechanicStorage[windowName];
  6580. let event = new selfGame["game.mediator.gui.popup.PopupStashEventParams"];
  6581. let Game = selfGame['Game'];
  6582. let navigator = getF(Game, "get_navigator")
  6583. let navigate = getProtoFn(selfGame["game.screen.navigator.GameNavigator"], 18)
  6584. let instance = getFnP(Game, 'get_instance');
  6585. Game[instance]()[navigator]()[navigate](window, event);
  6586. }
  6587.  
  6588. /**
  6589. * Move to the sanctuary cheats.goSanctuary()
  6590. *
  6591. * Переместиться в святилище cheats.goSanctuary()
  6592. */
  6593. this.goSanctuary = () => {
  6594. this.goNavigtor("SANCTUARY");
  6595. }
  6596.  
  6597. /**
  6598. * Go to Guild War
  6599. *
  6600. * Перейти к Войне Гильдий
  6601. */
  6602. this.goClanWar = function() {
  6603. let instance = getFnP(Game.GameModel, 'get_instance')
  6604. let player = Game.GameModel[instance]().A;
  6605. let clanWarSelect = selfGame["game.mechanics.cross_clan_war.popup.selectMode.CrossClanWarSelectModeMediator"];
  6606. new clanWarSelect(player).open();
  6607. }
  6608.  
  6609. /**
  6610. * Go to BrawlShop
  6611. *
  6612. * Переместиться в BrawlShop
  6613. */
  6614. this.goBrawlShop = () => {
  6615. const instance = getFnP(Game.GameModel, 'get_instance')
  6616. const P_36 = getProtoFn(selfGame["game.model.user.Player"], 36);
  6617. const PSD_0 = getProtoFn(selfGame["game.model.user.shop.PlayerShopData"], 0);
  6618. const IM_0 = getProtoFn(selfGame["haxe.ds.IntMap"], 0);
  6619. const PSDE_4 = getProtoFn(selfGame["game.model.user.shop.PlayerShopDataEntry"], 4);
  6620.  
  6621. const player = Game.GameModel[instance]().A;
  6622. const shop = player[P_36][PSD_0][IM_0][1038][PSDE_4];
  6623. const shopPopup = new selfGame["game.mechanics.brawl.mediator.BrawlShopPopupMediator"](player, shop)
  6624. shopPopup.open(new selfGame["game.mediator.gui.popup.PopupStashEventParams"])
  6625. }
  6626.  
  6627. /**
  6628. * Returns all stores from game data
  6629. *
  6630. * Возвращает все магазины из данных игры
  6631. */
  6632. this.getShops = () => {
  6633. const instance = getFnP(Game.GameModel, 'get_instance')
  6634. const P_36 = getProtoFn(selfGame["game.model.user.Player"], 36);
  6635. const PSD_0 = getProtoFn(selfGame["game.model.user.shop.PlayerShopData"], 0);
  6636. const IM_0 = getProtoFn(selfGame["haxe.ds.IntMap"], 0);
  6637.  
  6638. const player = Game.GameModel[instance]().A;
  6639. return player[P_36][PSD_0][IM_0];
  6640. }
  6641.  
  6642. /**
  6643. * Returns the store from the game data by ID
  6644. *
  6645. * Возвращает магазин из данных игры по идетификатору
  6646. */
  6647. this.getShop = (id) => {
  6648. const PSDE_4 = getProtoFn(selfGame["game.model.user.shop.PlayerShopDataEntry"], 4);
  6649. const shops = this.getShops();
  6650. const shop = shops[id]?.[PSDE_4];
  6651. return shop;
  6652. }
  6653. /**
  6654. * Moves to the store with the specified ID
  6655. *
  6656. * Перемещает к магазину с указанным идетификатором
  6657. */
  6658. this.goShopId = function (id) {
  6659. const shop = this.getShop(id);
  6660. if (!shop) {
  6661. return;
  6662. }
  6663. let event = new selfGame["game.mediator.gui.popup.PopupStashEventParams"];
  6664. let Game = selfGame['Game'];
  6665. let navigator = getF(Game, "get_navigator");
  6666. let navigate = getProtoFn(selfGame["game.screen.navigator.GameNavigator"], 21);
  6667. let instance = getFnP(Game, 'get_instance');
  6668. Game[instance]()[navigator]()[navigate](shop, event);
  6669. }
  6670. /**
  6671. * Opens a list of non-standard stores
  6672. *
  6673. * Открывает список не стандартных магазинов
  6674. */
  6675. this.goCustomShops = async (p = 0) => {
  6676. /** Запрос данных нужных магазинов */
  6677. const calls = [{ name: "shopGetAll", args: {}, ident: "shopGetAll" }];
  6678. const shops = lib.getData('shop');
  6679. for (const id in shops) {
  6680. const check = !shops[id].ident.includes('merchantPromo') &&
  6681. ![1, 4, 5, 6, 7, 8, 9, 10, 11, 1023, 1024].includes(+id);
  6682. if (check) {
  6683. calls.push({
  6684. name: "shopGet", args: { shopId: id }, ident: `shopGet_${id}`
  6685. })
  6686. }
  6687. }
  6688. const result = await Send({ calls }).then(e => e.results.map(n => n.result.response));
  6689. const shopAll = result.shift();
  6690. const DS_32 = getFn(Game.DataStorage, 32)
  6691. const SDS_5 = getProtoFn(selfGame["game.data.storage.shop.ShopDescriptionStorage"], 5)
  6692. const SD_21 = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 21);
  6693. const SD_1 = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 1);
  6694. const SD_9 = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 9);
  6695. const ident = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 11);
  6696. for (let shop of result) {
  6697. shopAll[shop.id] = shop;
  6698. // Снимаем все ограничения с магазинов
  6699. const shopLibData = Game.DataStorage[DS_32][SDS_5](shop.id)
  6700. shopLibData[SD_21] = 1;
  6701. shopLibData[SD_1] = new selfGame["game.model.user.requirement.Requirement"]
  6702. shopLibData[SD_9] = new selfGame["game.data.storage.level.LevelRequirement"]({
  6703. teamLevel: 10
  6704. });
  6705. }
  6706. /** Скрываем все остальные магазины */
  6707. for (let id in shops) {
  6708. const shopLibData = Game.DataStorage[DS_32][SDS_5](id)
  6709. if (shopLibData[ident].includes('merchantPromo')) {
  6710. shopLibData[SD_21] = 0;
  6711. shopLibData[SD_9] = new selfGame["game.data.storage.level.LevelRequirement"]({
  6712. teamLevel: 999
  6713. });
  6714. }
  6715. }
  6716. const instance = getFnP(Game.GameModel, 'get_instance')
  6717. const GM_0 = getProtoFn(Game.GameModel, 0);
  6718. const P_36 = getProtoFn(selfGame["game.model.user.Player"], 36);
  6719. const player = Game.GameModel[instance]()[GM_0];
  6720. /** Пересоздаем объект с магазинами */
  6721. player[P_36] = new selfGame["game.model.user.shop.PlayerShopData"](player);
  6722. player[P_36].init(shopAll);
  6723. /** Даем магазинам новые названия */
  6724. const PSDE_4 = getProtoFn(selfGame["game.model.user.shop.PlayerShopDataEntry"], 4);
  6725. const shopName = getFn(cheats.getShop(1), 14);
  6726. const currentShops = this.getShops();
  6727. let count = 0;
  6728. const start = 9 * p + 1;
  6729. const end = start + 8;
  6730. for (let id in currentShops) {
  6731. const shop = currentShops[id][PSDE_4];
  6732. if ([1, 4, 5, 6, 8, 9, 10, 11].includes(+id)) {
  6733. /** Скрываем стандартные магазины */
  6734. shop[SD_21] = 0;
  6735. } else {
  6736. count++;
  6737. if (count < start || count > end) {
  6738. shop[SD_21] = 0;
  6739. continue;
  6740. }
  6741. shop[SD_21] = 1;
  6742. shop[shopName] = cheats.translate("LIB_SHOP_NAME_" + id) + ' ' + id;
  6743. shop[SD_1] = new selfGame["game.model.user.requirement.Requirement"]
  6744. shop[SD_9] = new selfGame["game.data.storage.level.LevelRequirement"]({
  6745. teamLevel: 10
  6746. });
  6747. }
  6748. }
  6749. console.log(count, start, end)
  6750. /** Отправляемся в городскую лавку */
  6751. this.goShopId(1);
  6752. }
  6753. /**
  6754. * Opens a list of standard stores
  6755. *
  6756. * Открывает список стандартных магазинов
  6757. */
  6758. this.goDefaultShops = async () => {
  6759. const result = await Send({ calls: [{ name: "shopGetAll", args: {}, ident: "shopGetAll" }] })
  6760. .then(e => e.results.map(n => n.result.response));
  6761. const shopAll = result.shift();
  6762. const shops = lib.getData('shop');
  6763. const DS_8 = getFn(Game.DataStorage, 8)
  6764. const DSB_4 = getProtoFn(selfGame["game.data.storage.DescriptionStorageBase"], 4)
  6765. /** Получаем объект валюты магазина для оторажения */
  6766. const coins = Game.DataStorage[DS_8][DSB_4](85);
  6767. coins.__proto__ = selfGame["game.data.storage.resource.ConsumableDescription"].prototype;
  6768. const DS_32 = getFn(Game.DataStorage, 32)
  6769. const SDS_5 = getProtoFn(selfGame["game.data.storage.shop.ShopDescriptionStorage"], 5)
  6770. const SD_21 = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 21);
  6771. for (const id in shops) {
  6772. const shopLibData = Game.DataStorage[DS_32][SDS_5](id)
  6773. if ([1, 4, 5, 6, 8, 9, 10, 11].includes(+id)) {
  6774. shopLibData[SD_21] = 1;
  6775. } else {
  6776. shopLibData[SD_21] = 0;
  6777. }
  6778. }
  6779. const instance = getFnP(Game.GameModel, 'get_instance')
  6780. const GM_0 = getProtoFn(Game.GameModel, 0);
  6781. const P_36 = getProtoFn(selfGame["game.model.user.Player"], 36);
  6782. const player = Game.GameModel[instance]()[GM_0];
  6783. /** Пересоздаем объект с магазинами */
  6784. player[P_36] = new selfGame["game.model.user.shop.PlayerShopData"](player);
  6785. player[P_36].init(shopAll);
  6786. const PSDE_4 = getProtoFn(selfGame["game.model.user.shop.PlayerShopDataEntry"], 4);
  6787. const currentShops = this.getShops();
  6788. for (let id in currentShops) {
  6789. const shop = currentShops[id][PSDE_4];
  6790. if ([1, 4, 5, 6, 8, 9, 10, 11].includes(+id)) {
  6791. shop[SD_21] = 1;
  6792. } else {
  6793. shop[SD_21] = 0;
  6794. }
  6795. }
  6796. this.goShopId(1);
  6797. }
  6798. /**
  6799. * Opens a list of Secret Wealth stores
  6800. *
  6801. * Открывает список магазинов Тайное богатство
  6802. */
  6803. this.goSecretWealthShops = async () => {
  6804. /** Запрос данных нужных магазинов */
  6805. const calls = [{ name: "shopGetAll", args: {}, ident: "shopGetAll" }];
  6806. const shops = lib.getData('shop');
  6807. for (const id in shops) {
  6808. if (shops[id].ident.includes('merchantPromo') && shops[id].teamLevelToUnlock <= 130) {
  6809. calls.push({
  6810. name: "shopGet", args: { shopId: id }, ident: `shopGet_${id}`
  6811. })
  6812. }
  6813. }
  6814. const result = await Send({ calls }).then(e => e.results.map(n => n.result.response));
  6815. const shopAll = result.shift();
  6816. const DS_32 = getFn(Game.DataStorage, 32)
  6817. const SDS_5 = getProtoFn(selfGame["game.data.storage.shop.ShopDescriptionStorage"], 5)
  6818. const SD_21 = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 21);
  6819. const SD_1 = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 1);
  6820. const SD_9 = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 9);
  6821. const ident = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 11);
  6822. const specialCurrency = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 15);
  6823. const DS_8 = getFn(Game.DataStorage, 8)
  6824. const DSB_4 = getProtoFn(selfGame["game.data.storage.DescriptionStorageBase"], 4)
  6825. /** Получаем объект валюты магазина для оторажения */
  6826. const coins = Game.DataStorage[DS_8][DSB_4](85);
  6827. coins.__proto__ = selfGame["game.data.storage.resource.CoinDescription"].prototype;
  6828. for (let shop of result) {
  6829. shopAll[shop.id] = shop;
  6830. /** Снимаем все ограничения с магазинов */
  6831. const shopLibData = Game.DataStorage[DS_32][SDS_5](shop.id)
  6832. if (shopLibData[ident].includes('merchantPromo')) {
  6833. shopLibData[SD_21] = 1;
  6834. shopLibData[SD_1] = new selfGame["game.model.user.requirement.Requirement"]
  6835. shopLibData[SD_9] = new selfGame["game.data.storage.level.LevelRequirement"]({
  6836. teamLevel: 10
  6837. });
  6838. }
  6839. }
  6840. /** Скрываем все остальные магазины */
  6841. for (let id in shops) {
  6842. const shopLibData = Game.DataStorage[DS_32][SDS_5](id)
  6843. if (!shopLibData[ident].includes('merchantPromo')) {
  6844. shopLibData[SD_21] = 0;
  6845. }
  6846. }
  6847. const instance = getFnP(Game.GameModel, 'get_instance')
  6848. const GM_0 = getProtoFn(Game.GameModel, 0);
  6849. const P_36 = getProtoFn(selfGame["game.model.user.Player"], 36);
  6850. const player = Game.GameModel[instance]()[GM_0];
  6851. /** Пересоздаем объект с магазинами */
  6852. player[P_36] = new selfGame["game.model.user.shop.PlayerShopData"](player);
  6853. player[P_36].init(shopAll);
  6854. /** Даем магазинам новые названия */
  6855. const PSDE_4 = getProtoFn(selfGame["game.model.user.shop.PlayerShopDataEntry"], 4);
  6856. const shopName = getFn(cheats.getShop(1), 14);
  6857. const currentShops = this.getShops();
  6858. for (let id in currentShops) {
  6859. const shop = currentShops[id][PSDE_4];
  6860. if (shop[ident].includes('merchantPromo')) {
  6861. shop[SD_21] = 1;
  6862. shop[specialCurrency] = coins;
  6863. shop[shopName] = cheats.translate("LIB_SHOP_NAME_" + id) + ' ' + id;
  6864. } else if ([1, 4, 5, 6, 8, 9, 10, 11].includes(+id)) {
  6865. /** Скрываем стандартные магазины */
  6866. shop[SD_21] = 0;
  6867. }
  6868. }
  6869. /** Отправляемся в городскую лавку */
  6870. this.goShopId(1);
  6871. }
  6872. /**
  6873. * Change island map
  6874. *
  6875. * Сменить карту острова
  6876. */
  6877. this.changeIslandMap = (mapId = 2) => {
  6878. const GameInst = getFnP(selfGame['Game'], 'get_instance');
  6879. const GM_0 = getProtoFn(Game.GameModel, 0);
  6880. const P_59 = getProtoFn(selfGame["game.model.user.Player"], 59);
  6881. const Player = Game.GameModel[GameInst]()[GM_0];
  6882. Player[P_59].$({ id: mapId, seasonAdventure: { id: mapId, startDate: 1701914400, endDate: 1709690400, closed: false } });
  6883.  
  6884. const GN_15 = getProtoFn(selfGame["game.screen.navigator.GameNavigator"], 15)
  6885. const navigator = getF(selfGame['Game'], "get_navigator");
  6886. selfGame['Game'][GameInst]()[navigator]()[GN_15](new selfGame["game.mediator.gui.popup.PopupStashEventParams"]);
  6887. }
  6888.  
  6889. /**
  6890. * Game library availability tracker
  6891. *
  6892. * Отслеживание доступности игровой библиотеки
  6893. */
  6894. function checkLibLoad() {
  6895. timeout = setTimeout(() => {
  6896. if (Game.GameModel) {
  6897. changeLib();
  6898. } else {
  6899. checkLibLoad();
  6900. }
  6901. }, 100)
  6902. }
  6903.  
  6904. /**
  6905. * Game library data spoofing
  6906. *
  6907. * Подмена данных игровой библиотеки
  6908. */
  6909. function changeLib() {
  6910. console.log('lib connect');
  6911. const originalStartFunc = Game.GameModel.prototype.start;
  6912. Game.GameModel.prototype.start = function (a, b, c) {
  6913. self.libGame = b.raw;
  6914. try {
  6915. const levels = b.raw.seasonAdventure.level;
  6916. for (const id in levels) {
  6917. const level = levels[id];
  6918. level.clientData.graphics.fogged = level.clientData.graphics.visible
  6919. }
  6920. } catch (e) {
  6921. console.warn(e);
  6922. }
  6923. originalStartFunc.call(this, a, b, c);
  6924. }
  6925. }
  6926.  
  6927. /**
  6928. * Returns the value of a language constant
  6929. *
  6930. * Возвращает значение языковой константы
  6931. * @param {*} langConst language constant // языковая константа
  6932. * @returns
  6933. */
  6934. this.translate = function (langConst) {
  6935. return Game.Translate.translate(langConst);
  6936. }
  6937.  
  6938. connectGame();
  6939. checkLibLoad();
  6940. }
  6941.  
  6942. /**
  6943. * Auto collection of gifts
  6944. *
  6945. * Автосбор подарков
  6946. */
  6947. function getAutoGifts() {
  6948. let valName = 'giftSendIds_' + userInfo.id;
  6949.  
  6950. if (!localStorage['clearGift' + userInfo.id]) {
  6951. localStorage[valName] = '';
  6952. localStorage['clearGift' + userInfo.id] = '+';
  6953. }
  6954.  
  6955. if (!localStorage[valName]) {
  6956. localStorage[valName] = '';
  6957. }
  6958.  
  6959. const now = Date.now();
  6960. const body = JSON.stringify({ now });
  6961. const signature = window['\x73\x69\x67\x6e'](now);
  6962. /**
  6963. * Submit a request to receive gift codes
  6964. *
  6965. * Отправка запроса для получения кодов подарков
  6966. */
  6967. fetch('https://zingery.ru/heroes/getGifts.php', {
  6968. method: 'POST',
  6969. headers: {
  6970. 'X-Request-Signature': signature,
  6971. 'X-Script-Name': GM_info.script.name,
  6972. 'X-Script-Version': GM_info.script.version,
  6973. 'X-Script-Author': GM_info.script.author,
  6974. },
  6975. body
  6976. }).then(
  6977. response => response.json()
  6978. ).then(
  6979. data => {
  6980. let freebieCheckCalls = {
  6981. calls: []
  6982. }
  6983. data.forEach((giftId, n) => {
  6984. if (localStorage[valName].includes(giftId)) return;
  6985. freebieCheckCalls.calls.push({
  6986. name: "registration",
  6987. args: {
  6988. user: { referrer: {} },
  6989. giftId
  6990. },
  6991. context: {
  6992. actionTs: Math.floor(performance.now()),
  6993. cookie: window?.NXAppInfo?.session_id || null
  6994. },
  6995. ident: giftId
  6996. });
  6997. });
  6998.  
  6999. if (!freebieCheckCalls.calls.length) {
  7000. return;
  7001. }
  7002.  
  7003. send(JSON.stringify(freebieCheckCalls), e => {
  7004. let countGetGifts = 0;
  7005. const gifts = [];
  7006. for (check of e.results) {
  7007. gifts.push(check.ident);
  7008. if (check.result.response != null) {
  7009. countGetGifts++;
  7010. }
  7011. }
  7012. const saveGifts = localStorage[valName].split(';');
  7013. localStorage[valName] = [...saveGifts, ...gifts].slice(-50).join(';');
  7014. console.log(`${I18N('GIFTS')}: ${countGetGifts}`);
  7015. });
  7016. }
  7017. )
  7018. }
  7019.  
  7020. /**
  7021. * To fill the kills in the Forge of Souls
  7022. *
  7023. * Набить килов в горниле душ
  7024. */
  7025. async function bossRatingEvent() {
  7026. const topGet = await Send(JSON.stringify({ calls: [{ name: "topGet", args: { type: "bossRatingTop", extraId: 0 }, ident: "body" }] }));
  7027. if (!topGet || !topGet.results[0].result.response[0]) {
  7028. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  7029. return;
  7030. }
  7031. const replayId = topGet.results[0].result.response[0].userData.replayId;
  7032. const result = await Send(JSON.stringify({
  7033. calls: [
  7034. { name: "battleGetReplay", args: { id: replayId }, ident: "battleGetReplay" },
  7035. { name: "heroGetAll", args: {}, ident: "heroGetAll" },
  7036. { name: "pet_getAll", args: {}, ident: "pet_getAll" },
  7037. { name: "offerGetAll", args: {}, ident: "offerGetAll" }
  7038. ]
  7039. }));
  7040. const bossEventInfo = result.results[3].result.response.find(e => e.offerType == "bossEvent");
  7041. if (!bossEventInfo) {
  7042. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  7043. return;
  7044. }
  7045. const usedHeroes = bossEventInfo.progress.usedHeroes;
  7046. const party = Object.values(result.results[0].result.response.replay.attackers);
  7047. const availableHeroes = Object.values(result.results[1].result.response).map(e => e.id);
  7048. const availablePets = Object.values(result.results[2].result.response).map(e => e.id);
  7049. const calls = [];
  7050. /**
  7051. * First pack
  7052. *
  7053. * Первая пачка
  7054. */
  7055. const args = {
  7056. heroes: [],
  7057. favor: {}
  7058. }
  7059. for (let hero of party) {
  7060. if (hero.id >= 6000 && availablePets.includes(hero.id)) {
  7061. args.pet = hero.id;
  7062. continue;
  7063. }
  7064. if (!availableHeroes.includes(hero.id) || usedHeroes.includes(hero.id)) {
  7065. continue;
  7066. }
  7067. args.heroes.push(hero.id);
  7068. if (hero.favorPetId) {
  7069. args.favor[hero.id] = hero.favorPetId;
  7070. }
  7071. }
  7072. if (args.heroes.length) {
  7073. calls.push({
  7074. name: "bossRatingEvent_startBattle",
  7075. args,
  7076. ident: "body_0"
  7077. });
  7078. }
  7079. /**
  7080. * Other packs
  7081. *
  7082. * Другие пачки
  7083. */
  7084. let heroes = [];
  7085. let count = 1;
  7086. while (heroId = availableHeroes.pop()) {
  7087. if (args.heroes.includes(heroId) || usedHeroes.includes(heroId)) {
  7088. continue;
  7089. }
  7090. heroes.push(heroId);
  7091. if (heroes.length == 5) {
  7092. calls.push({
  7093. name: "bossRatingEvent_startBattle",
  7094. args: {
  7095. heroes: [...heroes],
  7096. pet: availablePets[Math.floor(Math.random() * availablePets.length)]
  7097. },
  7098. ident: "body_" + count
  7099. });
  7100. heroes = [];
  7101. count++;
  7102. }
  7103. }
  7104.  
  7105. if (!calls.length) {
  7106. setProgress(`${I18N('NO_HEROES')}`, true);
  7107. return;
  7108. }
  7109.  
  7110. const resultBattles = await Send(JSON.stringify({ calls }));
  7111. console.log(resultBattles);
  7112. rewardBossRatingEvent();
  7113. }
  7114.  
  7115. /**
  7116. * Collecting Rewards from the Forge of Souls
  7117. *
  7118. * Сбор награды из Горнила Душ
  7119. */
  7120. function rewardBossRatingEvent() {
  7121. let rewardBossRatingCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  7122. send(rewardBossRatingCall, function (data) {
  7123. let bossEventInfo = data.results[0].result.response.find(e => e.offerType == "bossEvent");
  7124. if (!bossEventInfo) {
  7125. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  7126. return;
  7127. }
  7128.  
  7129. let farmedChests = bossEventInfo.progress.farmedChests;
  7130. let score = bossEventInfo.progress.score;
  7131. setProgress(`${I18N('DAMAGE_AMOUNT')}: ${score}`);
  7132. let revard = bossEventInfo.reward;
  7133.  
  7134. let getRewardCall = {
  7135. calls: []
  7136. }
  7137.  
  7138. let count = 0;
  7139. for (let i = 1; i < 10; i++) {
  7140. if (farmedChests.includes(i)) {
  7141. continue;
  7142. }
  7143. if (score < revard[i].score) {
  7144. break;
  7145. }
  7146. getRewardCall.calls.push({
  7147. name: "bossRatingEvent_getReward",
  7148. args: {
  7149. rewardId: i
  7150. },
  7151. ident: "body_" + i
  7152. });
  7153. count++;
  7154. }
  7155. if (!count) {
  7156. setProgress(`${I18N('NOTHING_TO_COLLECT')}`, true);
  7157. return;
  7158. }
  7159.  
  7160. send(JSON.stringify(getRewardCall), e => {
  7161. console.log(e);
  7162. setProgress(`${I18N('COLLECTED')} ${e?.results?.length} ${I18N('REWARD')}`, true);
  7163. });
  7164. });
  7165. }
  7166.  
  7167. /**
  7168. * Collect Easter eggs and event rewards
  7169. *
  7170. * Собрать пасхалки и награды событий
  7171. */
  7172. function offerFarmAllReward() {
  7173. const offerGetAllCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  7174. return Send(offerGetAllCall).then((data) => {
  7175. const offerGetAll = data.results[0].result.response.filter(e => e.type == "reward" && !e?.freeRewardObtained && e.reward);
  7176. if (!offerGetAll.length) {
  7177. setProgress(`${I18N('NOTHING_TO_COLLECT')}`, true);
  7178. return;
  7179. }
  7180.  
  7181. const calls = [];
  7182. for (let reward of offerGetAll) {
  7183. calls.push({
  7184. name: "offerFarmReward",
  7185. args: {
  7186. offerId: reward.id
  7187. },
  7188. ident: "offerFarmReward_" + reward.id
  7189. });
  7190. }
  7191.  
  7192. return Send(JSON.stringify({ calls })).then(e => {
  7193. console.log(e);
  7194. setProgress(`${I18N('COLLECTED')} ${e?.results?.length} ${I18N('REWARD')}`, true);
  7195. });
  7196. });
  7197. }
  7198.  
  7199. /**
  7200. * Assemble Outland
  7201. *
  7202. * Собрать запределье
  7203. */
  7204. function getOutland() {
  7205. return new Promise(function (resolve, reject) {
  7206. send('{"calls":[{"name":"bossGetAll","args":{},"ident":"bossGetAll"}]}', e => {
  7207. let bosses = e.results[0].result.response;
  7208.  
  7209. let bossRaidOpenChestCall = {
  7210. calls: []
  7211. };
  7212.  
  7213. for (let boss of bosses) {
  7214. if (boss.mayRaid) {
  7215. bossRaidOpenChestCall.calls.push({
  7216. name: "bossRaid",
  7217. args: {
  7218. bossId: boss.id
  7219. },
  7220. ident: "bossRaid_" + boss.id
  7221. });
  7222. bossRaidOpenChestCall.calls.push({
  7223. name: "bossOpenChest",
  7224. args: {
  7225. bossId: boss.id,
  7226. amount: 1,
  7227. starmoney: 0
  7228. },
  7229. ident: "bossOpenChest_" + boss.id
  7230. });
  7231. } else if (boss.chestId == 1) {
  7232. bossRaidOpenChestCall.calls.push({
  7233. name: "bossOpenChest",
  7234. args: {
  7235. bossId: boss.id,
  7236. amount: 1,
  7237. starmoney: 0
  7238. },
  7239. ident: "bossOpenChest_" + boss.id
  7240. });
  7241. }
  7242. }
  7243.  
  7244. if (!bossRaidOpenChestCall.calls.length) {
  7245. setProgress(`${I18N('OUTLAND')} ${I18N('NOTHING_TO_COLLECT')}`, true);
  7246. resolve();
  7247. return;
  7248. }
  7249.  
  7250. send(JSON.stringify(bossRaidOpenChestCall), e => {
  7251. setProgress(`${I18N('OUTLAND')} ${I18N('COLLECTED')}`, true);
  7252. resolve();
  7253. });
  7254. });
  7255. });
  7256. }
  7257.  
  7258. /**
  7259. * Collect all rewards
  7260. *
  7261. * Собрать все награды
  7262. */
  7263. function questAllFarm() {
  7264. return new Promise(function (resolve, reject) {
  7265. let questGetAllCall = {
  7266. calls: [{
  7267. name: "questGetAll",
  7268. args: {},
  7269. ident: "body"
  7270. }]
  7271. }
  7272. send(JSON.stringify(questGetAllCall), function (data) {
  7273. let questGetAll = data.results[0].result.response;
  7274. const questAllFarmCall = {
  7275. calls: []
  7276. }
  7277. let number = 0;
  7278. for (let quest of questGetAll) {
  7279. if (quest.id < 1e6 && quest.state == 2) {
  7280. questAllFarmCall.calls.push({
  7281. name: "questFarm",
  7282. args: {
  7283. questId: quest.id
  7284. },
  7285. ident: `group_${number}_body`
  7286. });
  7287. number++;
  7288. }
  7289. }
  7290.  
  7291. if (!questAllFarmCall.calls.length) {
  7292. setProgress(`${I18N('COLLECTED')} ${number} ${I18N('REWARD')}`, true);
  7293. resolve();
  7294. return;
  7295. }
  7296.  
  7297. send(JSON.stringify(questAllFarmCall), function (res) {
  7298. console.log(res);
  7299. setProgress(`${I18N('COLLECTED')} ${number} ${I18N('REWARD')}`, true);
  7300. resolve();
  7301. });
  7302. });
  7303. })
  7304. }
  7305.  
  7306. /**
  7307. * Mission auto repeat
  7308. *
  7309. * Автоповтор миссии
  7310. * isStopSendMission = false;
  7311. * isSendsMission = true;
  7312. **/
  7313. this.sendsMission = async function (param) {
  7314. if (isStopSendMission) {
  7315. isSendsMission = false;
  7316. console.log(I18N('STOPPED'));
  7317. setProgress('');
  7318. await popup.confirm(`${I18N('STOPPED')}<br>${I18N('REPETITIONS')}: ${param.count}`, [{
  7319. msg: 'Ok',
  7320. result: true
  7321. }, ])
  7322. return;
  7323. }
  7324. lastMissionBattleStart = Date.now();
  7325. let missionStartCall = {
  7326. "calls": [{
  7327. "name": "missionStart",
  7328. "args": lastMissionStart,
  7329. "ident": "body"
  7330. }]
  7331. }
  7332. /**
  7333. * Mission Request
  7334. *
  7335. * Запрос на выполнение мисcии
  7336. */
  7337. SendRequest(JSON.stringify(missionStartCall), async e => {
  7338. if (e['error']) {
  7339. isSendsMission = false;
  7340. console.log(e['error']);
  7341. setProgress('');
  7342. let msg = e['error'].name + ' ' + e['error'].description + `<br>${I18N('REPETITIONS')}: ${param.count}`;
  7343. await popup.confirm(msg, [
  7344. {msg: 'Ok', result: true},
  7345. ])
  7346. return;
  7347. }
  7348. /**
  7349. * Mission data calculation
  7350. *
  7351. * Расчет данных мисcии
  7352. */
  7353. BattleCalc(e.results[0].result.response, 'get_tower', async r => {
  7354. /** missionTimer */
  7355. let timer = getTimer(r.battleTime) + 5;
  7356. const period = Math.ceil((Date.now() - lastMissionBattleStart) / 1000);
  7357. if (period < timer) {
  7358. timer = timer - period;
  7359. await countdownTimer(timer, `${I18N('MISSIONS_PASSED')}: ${param.count}`);
  7360. }
  7361.  
  7362. let missionEndCall = {
  7363. "calls": [{
  7364. "name": "missionEnd",
  7365. "args": {
  7366. "id": param.id,
  7367. "result": r.result,
  7368. "progress": r.progress
  7369. },
  7370. "ident": "body"
  7371. }]
  7372. }
  7373. /**
  7374. * Mission Completion Request
  7375. *
  7376. * Запрос на завершение миссии
  7377. */
  7378. SendRequest(JSON.stringify(missionEndCall), async (e) => {
  7379. if (e['error']) {
  7380. isSendsMission = false;
  7381. console.log(e['error']);
  7382. setProgress('');
  7383. let msg = e['error'].name + ' ' + e['error'].description + `<br>${I18N('REPETITIONS')}: ${param.count}`;
  7384. await popup.confirm(msg, [
  7385. {msg: 'Ok', result: true},
  7386. ])
  7387. return;
  7388. }
  7389. r = e.results[0].result.response;
  7390. if (r['error']) {
  7391. isSendsMission = false;
  7392. console.log(r['error']);
  7393. setProgress('');
  7394. await popup.confirm(`<br>${I18N('REPETITIONS')}: ${param.count}` + ' 3 ' + r['error'], [
  7395. {msg: 'Ok', result: true},
  7396. ])
  7397. return;
  7398. }
  7399.  
  7400. param.count++;
  7401. let RaidMission = getInput('countRaid');
  7402.  
  7403. if (RaidMission==param.count){
  7404. isStopSendMission = true;
  7405. console.log(RaidMission);
  7406. }
  7407. setProgress(`${I18N('MISSIONS_PASSED')}: ${param.count} (${I18N('STOP')})`, false, () => {
  7408. isStopSendMission = true;
  7409. });
  7410. setTimeout(sendsMission, 1, param);
  7411. });
  7412. })
  7413. });
  7414. }
  7415.  
  7416. /**
  7417. * Opening of russian dolls
  7418. *
  7419. * Открытие матрешек
  7420. */
  7421. async function openRussianDolls(libId, amount) {
  7422. let sum = 0;
  7423. let sumResult = [];
  7424.  
  7425. while (amount) {
  7426. sum += amount;
  7427. setProgress(`${I18N('TOTAL_OPEN')} ${sum}`);
  7428. const calls = [{
  7429. name: "consumableUseLootBox",
  7430. args: { libId, amount },
  7431. ident: "body"
  7432. }];
  7433. const result = await Send(JSON.stringify({ calls })).then(e => e.results[0].result.response);
  7434. let newCount = 0;
  7435. for (let n of result) {
  7436. if (n?.consumable && n.consumable[libId]) {
  7437. newCount += n.consumable[libId]
  7438. }
  7439. }
  7440. sumResult = [...sumResult, ...result];
  7441. amount = newCount;
  7442. }
  7443.  
  7444. setProgress(`${I18N('TOTAL_OPEN')} ${sum}`, 5000);
  7445. return sumResult;
  7446. }
  7447.  
  7448. /**
  7449. * Collect all mail, except letters with energy and charges of the portal
  7450. *
  7451. * Собрать всю почту, кроме писем с энергией и зарядами портала
  7452. */
  7453. function mailGetAll() {
  7454. const getMailInfo = '{"calls":[{"name":"mailGetAll","args":{},"ident":"body"}]}';
  7455.  
  7456. return Send(getMailInfo).then(dataMail => {
  7457. const letters = dataMail.results[0].result.response.letters;
  7458. const letterIds = lettersFilter(letters);
  7459. if (!letterIds.length) {
  7460. setProgress(I18N('NOTHING_TO_COLLECT'), true);
  7461. return;
  7462. }
  7463.  
  7464. const calls = [
  7465. { name: "mailFarm", args: { letterIds }, ident: "body" }
  7466. ];
  7467.  
  7468. return Send(JSON.stringify({ calls })).then(res => {
  7469. const lettersIds = res.results[0].result.response;
  7470. if (lettersIds) {
  7471. const countLetters = Object.keys(lettersIds).length;
  7472. setProgress(`${I18N('RECEIVED')} ${countLetters} ${I18N('LETTERS')}`, true);
  7473. }
  7474. });
  7475. });
  7476. }
  7477.  
  7478. /**
  7479. * Filters received emails
  7480. *
  7481. * Фильтрует получаемые письма
  7482. */
  7483. function lettersFilter(letters) {
  7484. const lettersIds = [];
  7485. for (let l in letters) {
  7486. letter = letters[l];
  7487. const reward = letter.reward;
  7488. if (!reward) {
  7489. continue;
  7490. }
  7491. /**
  7492. * Mail Collection Exceptions
  7493. *
  7494. * Исключения на сбор писем
  7495. */
  7496. const isFarmLetter = !(
  7497. /** Portals // сферы портала */
  7498. (reward?.refillable ? reward.refillable[45] : false) ||
  7499. /** Energy // энергия */
  7500. (reward?.stamina ? reward.stamina : false) ||
  7501. /** accelerating energy gain // ускорение набора энергии */
  7502. (reward?.buff ? true : false) ||
  7503. /** VIP Points // вип очки */
  7504. (reward?.vipPoints ? reward.vipPoints : false) ||
  7505. /** souls of heroes // душы героев */
  7506. (reward?.fragmentHero ? true : false) ||
  7507. /** heroes // герои */
  7508. (reward?.bundleHeroReward ? true : false)
  7509. );
  7510. if (isFarmLetter) {
  7511. lettersIds.push(~~letter.id);
  7512. continue;
  7513. }
  7514. /**
  7515. * Если до окончания годности письма менее 24 часов,
  7516. * то оно собирается не смотря на исключения
  7517. */
  7518. const availableUntil = +letter?.availableUntil;
  7519. if (availableUntil) {
  7520. const maxTimeLeft = 24 * 60 * 60 * 1000;
  7521. const timeLeft = (new Date(availableUntil * 1000) - new Date())
  7522. console.log('Time left:', timeLeft)
  7523. if (timeLeft < maxTimeLeft) {
  7524. lettersIds.push(~~letter.id);
  7525. continue;
  7526. }
  7527. }
  7528. }
  7529. return lettersIds;
  7530. }
  7531.  
  7532. /**
  7533. * Displaying information about the areas of the portal and attempts on the VG
  7534. *
  7535. * Отображение информации о сферах портала и попытках на ВГ
  7536. */
  7537. async function justInfo() {
  7538. return new Promise(async (resolve, reject) => {
  7539. const calls = [{
  7540. name: "userGetInfo",
  7541. args: {},
  7542. ident: "userGetInfo"
  7543. },
  7544. {
  7545. name: "clanWarGetInfo",
  7546. args: {},
  7547. ident: "clanWarGetInfo"
  7548. },
  7549. {
  7550. name: "titanArenaGetStatus",
  7551. args: {},
  7552. ident: "titanArenaGetStatus"
  7553. }];
  7554. const result = await Send(JSON.stringify({ calls }));
  7555. const infos = result.results;
  7556. const portalSphere = infos[0].result.response.refillable.find(n => n.id == 45);
  7557. const clanWarMyTries = infos[1].result.response?.myTries ?? 0;
  7558. const arePointsMax = infos[1].result.response?.arePointsMax;
  7559. const titansLevel = +(infos[2].result.response?.tier ?? 0);
  7560. const titansStatus = infos[2].result.response?.status; //peace_time || battle
  7561.  
  7562. const sanctuaryButton = buttons['goToSanctuary'].button;
  7563. const clanWarButton = buttons['goToClanWar'].button;
  7564. const titansArenaButton = buttons['testTitanArena'].button;
  7565.  
  7566. /*if (portalSphere.amount) {
  7567. sanctuaryButton.style.color = portalSphere.amount >= 3 ? 'red' : 'brown';
  7568. sanctuaryButton.title = `${I18N('SANCTUARY_TITLE')}\n${portalSphere.amount} ${I18N('PORTALS')}`;
  7569. } else {*/
  7570. sanctuaryButton.style.color = '';
  7571. sanctuaryButton.title = I18N('SANCTUARY_TITLE');
  7572. //}
  7573. /*if (clanWarMyTries && !arePointsMax) {
  7574. clanWarButton.style.color = 'red';
  7575. clanWarButton.title = `${I18N('GUILD_WAR_TITLE')}\n${clanWarMyTries}${I18N('ATTEMPTS')}`;
  7576. } else {*/
  7577. clanWarButton.style.color = '';
  7578. clanWarButton.title = I18N('GUILD_WAR_TITLE');
  7579. //}
  7580.  
  7581. /*if (titansLevel < 7 && titansStatus == 'battle') {
  7582. const partColor = Math.floor(125 * titansLevel / 7);
  7583. titansArenaButton.style.color = `rgb(255,${partColor},${partColor})`;
  7584. titansArenaButton.title = `${I18N('TITAN_ARENA_TITLE')}\n${titansLevel} ${I18N('LEVEL')}`;
  7585. } else {*/
  7586. titansArenaButton.style.color = '';
  7587. titansArenaButton.title = I18N('TITAN_ARENA_TITLE');
  7588. //}
  7589. //тест убрал подсветку красным в меню
  7590. setProgress('<img src="https://zingery.ru/heroes/portal.png" style="height: 25px;position: relative;top: 5px;"> ' + `${portalSphere.amount} </br> ${I18N('GUILD_WAR')}: ${clanWarMyTries}`, true);
  7591. resolve();
  7592. });
  7593. }
  7594. // тест сделать все
  7595. /** Отправить подарки мое*/
  7596. function testclanSendDailyGifts() {
  7597.  
  7598. send('{"calls":[{"name":"clanSendDailyGifts","args":{},"ident":"clanSendDailyGifts"}]}', e => {
  7599. setProgress('Награды собраны', true);});
  7600. }
  7601. /** Открой сферу артефактов титанов*/
  7602. function testtitanArtifactChestOpen() {
  7603. send('{"calls":[{"name":"titanArtifactChestOpen","args":{"amount":1,"free":true},"ident":"body"}]}',
  7604. isWeCanDo => {
  7605. return info['inventoryGet']?.consumable[55] > 0
  7606. //setProgress('Награды собраны', true);
  7607. });
  7608. }
  7609. /** Воспользуйся призывом питомцев 1 раз*/
  7610. function testpet_chestOpen() {
  7611. send('{"calls":[{"name":"pet_chestOpen","args":{"amount":1,"paid":false},"ident":"pet_chestOpen"}]}',
  7612. isWeCanDo => {
  7613. return info['inventoryGet']?.consumable[90] > 0
  7614. //setProgress('Награды собраны', true);
  7615. });
  7616. }
  7617.  
  7618. async function getDailyBonus() {
  7619. const dailyBonusInfo = await Send(JSON.stringify({
  7620. calls: [{
  7621. name: "dailyBonusGetInfo",
  7622. args: {},
  7623. ident: "body"
  7624. }]
  7625. })).then(e => e.results[0].result.response);
  7626. const { availableToday, availableVip, currentDay } = dailyBonusInfo;
  7627.  
  7628. if (!availableToday) {
  7629. console.log('Уже собрано');
  7630. return;
  7631. }
  7632.  
  7633. const currentVipPoints = +userInfo.vipPoints;
  7634. const dailyBonusStat = lib.getData('dailyBonusStatic');
  7635. const vipInfo = lib.getData('level').vip;
  7636. let currentVipLevel = 0;
  7637. for (let i in vipInfo) {
  7638. vipLvl = vipInfo[i];
  7639. if (currentVipPoints >= vipLvl.vipPoints) {
  7640. currentVipLevel = vipLvl.level;
  7641. }
  7642. }
  7643. const vipLevelDouble = dailyBonusStat[`${currentDay}_0_0`].vipLevelDouble;
  7644.  
  7645. const calls = [{
  7646. name: "dailyBonusFarm",
  7647. args: {
  7648. vip: availableVip && currentVipLevel >= vipLevelDouble ? 1 : 0
  7649. },
  7650. ident: "body"
  7651. }];
  7652.  
  7653. const result = await Send(JSON.stringify({ calls }));
  7654. if (result.error) {
  7655. console.error(result.error);
  7656. return;
  7657. }
  7658.  
  7659. const reward = result.results[0].result.response;
  7660. const type = Object.keys(reward).pop();
  7661. const itemId = Object.keys(reward[type]).pop();
  7662. const count = reward[type][itemId];
  7663. const itemName = cheats.translate(`LIB_${type.toUpperCase()}_NAME_${itemId}`);
  7664.  
  7665. console.log(`Ежедневная награда: Получено ${count} ${itemName}`, reward);
  7666. }
  7667.  
  7668. async function farmStamina(lootBoxId = 148) {
  7669. const lootBox = await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"}]}')
  7670. .then(e => e.results[0].result.response.consumable[148]);
  7671.  
  7672. /** Добавить другие ящики */
  7673. /**
  7674. * 144 - медная шкатулка
  7675. * 145 - бронзовая шкатулка
  7676. * 148 - платиновая шкатулка
  7677. */
  7678. if (!lootBox) {
  7679. setProgress(I18N('NO_BOXES'), true);
  7680. return;
  7681. }
  7682.  
  7683. let maxFarmEnergy = getSaveVal('maxFarmEnergy', 100);
  7684. const result = await popup.confirm(I18N('OPEN_LOOTBOX', { lootBox }), [
  7685. { result: false, isClose: true },
  7686. { msg: I18N('BTN_YES'), result: true },
  7687. { msg: I18N('STAMINA'), isInput: true, default: maxFarmEnergy },
  7688. ]);
  7689.  
  7690. if (!+result) {
  7691. return;
  7692. }
  7693.  
  7694. if ((typeof result) !== 'boolean' && Number.parseInt(result)) {
  7695. maxFarmEnergy = +result;
  7696. setSaveVal('maxFarmEnergy', maxFarmEnergy);
  7697. } else {
  7698. maxFarmEnergy = 0;
  7699. }
  7700.  
  7701. let collectEnergy = 0;
  7702. for (let count = lootBox; count > 0; count--) {
  7703. const result = await Send('{"calls":[{"name":"consumableUseLootBox","args":{"libId":148,"amount":1},"ident":"body"}]}')
  7704. .then(e => e.results[0].result.response[0]);
  7705. if ('stamina' in result) {
  7706. setProgress(`${I18N('OPEN')}: ${lootBox - count}/${lootBox} ${I18N('STAMINA')} +${result.stamina}<br>${I18N('STAMINA')}: ${collectEnergy}`, false);
  7707. console.log(`${ I18N('STAMINA') } + ${ result.stamina }`);
  7708. if (!maxFarmEnergy) {
  7709. return;
  7710. }
  7711. collectEnergy += +result.stamina;
  7712. if (collectEnergy >= maxFarmEnergy) {
  7713. console.log(`${I18N('STAMINA')} + ${ collectEnergy }`);
  7714. setProgress(`${I18N('STAMINA')} + ${ collectEnergy }`, false);
  7715. return;
  7716. }
  7717. } else {
  7718. setProgress(`${I18N('OPEN')}: ${lootBox - count}/${lootBox}<br>${I18N('STAMINA')}: ${collectEnergy}`, false);
  7719. console.log(result);
  7720. }
  7721. }
  7722.  
  7723. setProgress(I18N('BOXES_OVER'), true);
  7724. }
  7725.  
  7726. async function fillActive() {
  7727. const data = await Send(JSON.stringify({
  7728. calls: [{
  7729. name: "questGetAll",
  7730. args: {},
  7731. ident: "questGetAll"
  7732. }, {
  7733. name: "inventoryGet",
  7734. args: {},
  7735. ident: "inventoryGet"
  7736. }, {
  7737. name: "clanGetInfo",
  7738. args: {},
  7739. ident: "clanGetInfo"
  7740. }
  7741. ]
  7742. })).then(e => e.results.map(n => n.result.response));
  7743.  
  7744. const quests = data[0];
  7745. const inv = data[1];
  7746. const stat = data[2].stat;
  7747. const maxActive = 2000 - stat.todayItemsActivity;
  7748. if (maxActive <= 0) {
  7749. setProgress(I18N('NO_MORE_ACTIVITY'), true);
  7750. return;
  7751. }
  7752.  
  7753. let countGetActive = 0;
  7754. const quest = quests.find(e => e.id > 10046 && e.id < 10051);
  7755. if (quest) {
  7756. countGetActive = 1750 - quest.progress;
  7757. }
  7758.  
  7759. if (countGetActive <= 0) {
  7760. countGetActive = maxActive;
  7761. }
  7762. console.log(countGetActive);
  7763.  
  7764. countGetActive = +(await popup.confirm(I18N('EXCHANGE_ITEMS', { maxActive }), [
  7765. { result: false, isClose: true },
  7766. { msg: I18N('GET_ACTIVITY'), isInput: true, default: countGetActive.toString() },
  7767. ]));
  7768.  
  7769. if (!countGetActive) {
  7770. return;
  7771. }
  7772.  
  7773. if (countGetActive > maxActive) {
  7774. countGetActive = maxActive;
  7775. }
  7776.  
  7777. const items = lib.getData('inventoryItem');
  7778.  
  7779. let itemsInfo = [];
  7780. for (let type of ['gear', 'scroll']) {
  7781. for (let i in inv[type]) {
  7782. const v = items[type][i]?.enchantValue || 0;
  7783. itemsInfo.push({
  7784. id: i,
  7785. count: inv[type][i],
  7786. v,
  7787. type
  7788. })
  7789. }
  7790. const invType = 'fragment' + type.toLowerCase().charAt(0).toUpperCase() + type.slice(1);
  7791. for (let i in inv[invType]) {
  7792. const v = items[type][i]?.fragmentEnchantValue || 0;
  7793. itemsInfo.push({
  7794. id: i,
  7795. count: inv[invType][i],
  7796. v,
  7797. type: invType
  7798. })
  7799. }
  7800. }
  7801. itemsInfo = itemsInfo.filter(e => e.v < 4 && e.count > 200);
  7802. itemsInfo = itemsInfo.sort((a, b) => b.count - a.count);
  7803. console.log(itemsInfo);
  7804. const activeItem = itemsInfo.shift();
  7805. console.log(activeItem);
  7806. const countItem = Math.ceil(countGetActive / activeItem.v);
  7807. if (countItem > activeItem.count) {
  7808. setProgress(I18N('NOT_ENOUGH_ITEMS'), true);
  7809. console.log(activeItem);
  7810. return;
  7811. }
  7812.  
  7813. await Send(JSON.stringify({
  7814. calls: [{
  7815. name: "clanItemsForActivity",
  7816. args: {
  7817. items: {
  7818. [activeItem.type]: {
  7819. [activeItem.id]: countItem
  7820. }
  7821. }
  7822. },
  7823. ident: "body"
  7824. }]
  7825. })).then(e => {
  7826. /** TODO: Вывести потраченые предметы */
  7827. console.log(e);
  7828. setProgress(`${I18N('ACTIVITY_RECEIVED')}: ` + e.results[0].result.response, true);
  7829. });
  7830. }
  7831.  
  7832. async function buyHeroFragments() {
  7833. const result = await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"},{"name":"shopGetAll","args":{},"ident":"shopGetAll"}]}')
  7834. .then(e => e.results.map(n => n.result.response));
  7835. const inv = result[0];
  7836. const shops = Object.values(result[1]).filter(shop => [4, 5, 6, 8, 9, 10, 17].includes(shop.id));
  7837. const calls = [];
  7838.  
  7839. for (let shop of shops) {
  7840. const slots = Object.values(shop.slots);
  7841. for (const slot of slots) {
  7842. /* Уже куплено */
  7843. if (slot.bought) {
  7844. continue;
  7845. }
  7846. /* Не душа героя */
  7847. if (!('fragmentHero' in slot.reward)) {
  7848. continue;
  7849. }
  7850. const coin = Object.keys(slot.cost).pop();
  7851. const coinId = Object.keys(slot.cost[coin]).pop();
  7852. const stock = inv[coin][coinId] || 0;
  7853. /* Не хватает на покупку */
  7854. if (slot.cost[coin][coinId] > stock) {
  7855. continue;
  7856. }
  7857. inv[coin][coinId] -= slot.cost[coin][coinId];
  7858. calls.push({
  7859. name: "shopBuy",
  7860. args: {
  7861. shopId: shop.id,
  7862. slot: slot.id,
  7863. cost: slot.cost,
  7864. reward: slot.reward,
  7865. },
  7866. ident: `shopBuy_${shop.id}_${slot.id}`,
  7867. })
  7868. }
  7869. }
  7870.  
  7871. if (!calls.length) {
  7872. setProgress(I18N('NO_PURCHASABLE_HERO_SOULS'), true);
  7873. return;
  7874. }
  7875.  
  7876. const bought = await Send(JSON.stringify({ calls })).then(e => e.results.map(n => n.result.response));
  7877. if (!bought) {
  7878. console.log('что-то пошло не так')
  7879. return;
  7880. }
  7881.  
  7882. let countHeroSouls = 0;
  7883. for (const buy of bought) {
  7884. countHeroSouls += +Object.values(Object.values(buy).pop()).pop();
  7885. }
  7886. console.log(countHeroSouls, bought, calls);
  7887. setProgress(I18N('PURCHASED_HERO_SOULS', { countHeroSouls }), true);
  7888. }
  7889.  
  7890. /** Открыть платные сундуки в Запределье за 90 */
  7891. async function bossOpenChestPay() {
  7892. const info = await Send('{"calls":[{"name":"userGetInfo","args":{},"ident":"userGetInfo"},{"name":"bossGetAll","args":{},"ident":"bossGetAll"}]}')
  7893. .then(e => e.results.map(n => n.result.response));
  7894.  
  7895. const user = info[0];
  7896. const boses = info[1];
  7897.  
  7898. const currentStarMoney = user.starMoney;
  7899. if (currentStarMoney < 540) {
  7900. setProgress(I18N('NOT_ENOUGH_EMERALDS_540', { currentStarMoney }), true);
  7901. return;
  7902. }
  7903.  
  7904. const calls = [];
  7905.  
  7906. let n = 0;
  7907. const amount = 1;
  7908. for (let boss of boses) {
  7909. const bossId = boss.id;
  7910. if (boss.chestNum != 2) {
  7911. continue;
  7912. }
  7913. for (const starmoney of [90, 90, 0]) {
  7914. calls.push({
  7915. name: "bossOpenChest",
  7916. args: {
  7917. bossId,
  7918. amount,
  7919. starmoney
  7920. },
  7921. ident: "bossOpenChest_" + (++n)
  7922. });
  7923. }
  7924. }
  7925.  
  7926. if (!calls.length) {
  7927. setProgress(I18N('CHESTS_NOT_AVAILABLE'), true);
  7928. return;
  7929. }
  7930.  
  7931. const result = await Send(JSON.stringify({ calls }));
  7932. console.log(result);
  7933. if (result?.results) {
  7934. setProgress(`${I18N('OUTLAND_CHESTS_RECEIVED')}: ` + result.results.length, true);
  7935. } else {
  7936. setProgress(I18N('CHESTS_NOT_AVAILABLE'), true);
  7937. }
  7938. }
  7939.  
  7940. async function autoRaidAdventure() {
  7941. const calls = [
  7942. {
  7943. name: "userGetInfo",
  7944. args: {},
  7945. ident: "userGetInfo"
  7946. },
  7947. {
  7948. name: "adventure_raidGetInfo",
  7949. args: {},
  7950. ident: "adventure_raidGetInfo"
  7951. }
  7952. ];
  7953. const result = await Send(JSON.stringify({ calls }))
  7954. .then(e => e.results.map(n => n.result.response));
  7955.  
  7956. const portalSphere = result[0].refillable.find(n => n.id == 45);
  7957. const adventureRaid = Object.entries(result[1].raid).filter(e => e[1]).pop()
  7958. const adventureId = adventureRaid ? adventureRaid[0] : 0;
  7959.  
  7960. if (!portalSphere.amount || !adventureId) {
  7961. setProgress(I18N('RAID_NOT_AVAILABLE'), true);
  7962. return;
  7963. }
  7964.  
  7965. const countRaid = +(await popup.confirm(I18N('RAID_ADVENTURE', { adventureId }), [
  7966. { result: false, isClose: true },
  7967. { msg: I18N('RAID'), isInput: true, default: portalSphere.amount },
  7968. ]));
  7969.  
  7970. if (!countRaid) {
  7971. return;
  7972. }
  7973.  
  7974. if (countRaid > portalSphere.amount) {
  7975. countRaid = portalSphere.amount;
  7976. }
  7977.  
  7978. const resultRaid = await Send(JSON.stringify({
  7979. calls: [...Array(countRaid)].map((e, i) => ({
  7980. name: "adventure_raid",
  7981. args: {
  7982. adventureId
  7983. },
  7984. ident: `body_${i}`
  7985. }))
  7986. })).then(e => e.results.map(n => n.result.response));
  7987.  
  7988. if (!resultRaid.length) {
  7989. console.log(resultRaid);
  7990. setProgress(I18N('SOMETHING_WENT_WRONG'), true);
  7991. return;
  7992. }
  7993.  
  7994. console.log(resultRaid, adventureId, portalSphere.amount);
  7995. setProgress(I18N('ADVENTURE_COMPLETED', { adventureId, times: resultRaid.length }), true);
  7996. }
  7997.  
  7998. /** Вывести всю клановую статистику в консоль браузера */
  7999. async function clanStatistic() {
  8000. const copy = function (text) {
  8001. const copyTextarea = document.createElement("textarea");
  8002. copyTextarea.style.opacity = "0";
  8003. copyTextarea.textContent = text;
  8004. document.body.appendChild(copyTextarea);
  8005. copyTextarea.select();
  8006. document.execCommand("copy");
  8007. document.body.removeChild(copyTextarea);
  8008. delete copyTextarea;
  8009. }
  8010. const calls = [
  8011. { name: "clanGetInfo", args: {}, ident: "clanGetInfo" },
  8012. { name: "clanGetWeeklyStat", args: {}, ident: "clanGetWeeklyStat" },
  8013. { name: "clanGetLog", args: {}, ident: "clanGetLog" },
  8014. ];
  8015.  
  8016. const result = await Send(JSON.stringify({ calls }));
  8017.  
  8018. const dataClanInfo = result.results[0].result.response;
  8019. const dataClanStat = result.results[1].result.response;
  8020. const dataClanLog = result.results[2].result.response;
  8021.  
  8022. const membersStat = {};
  8023. for (let i = 0; i < dataClanStat.stat.length; i++) {
  8024. membersStat[dataClanStat.stat[i].id] = dataClanStat.stat[i];
  8025. }
  8026.  
  8027. const joinStat = {};
  8028. historyLog = dataClanLog.history;
  8029. for (let j in historyLog) {
  8030. his = historyLog[j];
  8031. if (his.event == 'join') {
  8032. joinStat[his.userId] = his.ctime;
  8033. }
  8034. }
  8035.  
  8036. const infoArr = [];
  8037. const members = dataClanInfo.clan.members;
  8038. for (let n in members) {
  8039. var member = [
  8040. n,
  8041. members[n].name,
  8042. members[n].level,
  8043. dataClanInfo.clan.warriors.includes(+n) ? 1 : 0,
  8044. (new Date(members[n].lastLoginTime * 1000)).toLocaleString().replace(',', ''),
  8045. joinStat[n] ? (new Date(joinStat[n] * 1000)).toLocaleString().replace(',', '') : '',
  8046. membersStat[n].activity.reverse().join('\t'),
  8047. membersStat[n].adventureStat.reverse().join('\t'),
  8048. membersStat[n].clanGifts.reverse().join('\t'),
  8049. membersStat[n].clanWarStat.reverse().join('\t'),
  8050. membersStat[n].dungeonActivity.reverse().join('\t'),
  8051. ];
  8052. infoArr.push(member);
  8053. }
  8054. const info = infoArr.sort((a, b) => (b[2] - a[2])).map((e) => e.join('\t')).join('\n');
  8055. console.log(info);
  8056. copy(info);
  8057. setProgress(I18N('CLAN_STAT_COPY'), true);
  8058. }
  8059.  
  8060. async function buyInStoreForGold() {
  8061. const result = await Send('{"calls":[{"name":"shopGetAll","args":{},"ident":"body"},{"name":"userGetInfo","args":{},"ident":"userGetInfo"}]}').then(e => e.results.map(n => n.result.response));
  8062. const shops = result[0];
  8063. const user = result[1];
  8064. let gold = user.gold;
  8065. const calls = [];
  8066. if (shops[17]) {
  8067. const slots = shops[17].slots;
  8068. for (let i = 1; i <= 2; i++) {
  8069. if (!slots[i].bought) {
  8070. const costGold = slots[i].cost.gold;
  8071. if ((gold - costGold) < 0) {
  8072. continue;
  8073. }
  8074. gold -= costGold;
  8075. calls.push({
  8076. name: "shopBuy",
  8077. args: {
  8078. shopId: 17,
  8079. slot: i,
  8080. cost: slots[i].cost,
  8081. reward: slots[i].reward,
  8082. },
  8083. ident: 'body_' + i,
  8084. })
  8085. }
  8086. }
  8087. }
  8088. const slots = shops[1].slots;
  8089. for (let i = 4; i <= 6; i++) {
  8090. if (!slots[i].bought && slots[i]?.cost?.gold) {
  8091. const costGold = slots[i].cost.gold;
  8092. if ((gold - costGold) < 0) {
  8093. continue;
  8094. }
  8095. gold -= costGold;
  8096. calls.push({
  8097. name: "shopBuy",
  8098. args: {
  8099. shopId: 1,
  8100. slot: i,
  8101. cost: slots[i].cost,
  8102. reward: slots[i].reward,
  8103. },
  8104. ident: 'body_' + i,
  8105. })
  8106. }
  8107. }
  8108.  
  8109. if (!calls.length) {
  8110. setProgress(I18N('NOTHING_BUY'), true);
  8111. return;
  8112. }
  8113.  
  8114. const resultBuy = await Send(JSON.stringify({ calls })).then(e => e.results.map(n => n.result.response));
  8115. console.log(resultBuy);
  8116. const countBuy = resultBuy.length;
  8117. setProgress(I18N('LOTS_BOUGHT', { countBuy }), true);
  8118. }
  8119.  
  8120. function rewardsAndMailFarm() {
  8121. return new Promise(function (resolve, reject) {
  8122. let questGetAllCall = {
  8123. calls: [{
  8124. name: "questGetAll",
  8125. args: {},
  8126. ident: "questGetAll"
  8127. }, {
  8128. name: "mailGetAll",
  8129. args: {},
  8130. ident: "mailGetAll"
  8131. }]
  8132. }
  8133. send(JSON.stringify(questGetAllCall), function (data) {
  8134. if (!data) return;
  8135. let questGetAll = data.results[0].result.response.filter(e => e.state == 2);
  8136. const questBattlePass = lib.getData('quest').battlePass;
  8137. const questChainBPass = lib.getData('battlePass').questChain;
  8138.  
  8139. const questAllFarmCall = {
  8140. calls: []
  8141. }
  8142. let number = 0;
  8143. for (let quest of questGetAll) {
  8144. if (quest.id > 1e6) {
  8145. const questInfo = questBattlePass[quest.id];
  8146. const chain = questChainBPass[questInfo.chain];
  8147. if (chain.requirement?.battlePassTicket) {
  8148. continue;
  8149. }
  8150. }
  8151. questAllFarmCall.calls.push({
  8152. name: "questFarm",
  8153. args: {
  8154. questId: quest.id
  8155. },
  8156. ident: `questFarm_${number}`
  8157. });
  8158. number++;
  8159. }
  8160.  
  8161. let letters = data?.results[1]?.result?.response?.letters;
  8162. letterIds = lettersFilter(letters);
  8163.  
  8164. if (letterIds.length) {
  8165. questAllFarmCall.calls.push({
  8166. name: "mailFarm",
  8167. args: { letterIds },
  8168. ident: "mailFarm"
  8169. })
  8170. }
  8171.  
  8172. if (!questAllFarmCall.calls.length) {
  8173. setProgress(I18N('NOTHING_TO_COLLECT'), true);
  8174. resolve();
  8175. return;
  8176. }
  8177.  
  8178. send(JSON.stringify(questAllFarmCall), function (res) {
  8179. let reSend = false;
  8180. let countQuests = 0;
  8181. let countMail = 0;
  8182. for (let call of res.results) {
  8183. if (call.ident.includes('questFarm')) {
  8184. countQuests++;
  8185. } else {
  8186. countMail = Object.keys(call.result.response).length;
  8187. }
  8188.  
  8189. /** TODO: Переписать чтоб не вызывать функцию дважды */
  8190. const newQuests = call.result.newQuests;
  8191. if (newQuests) {
  8192. for (let quest of newQuests) {
  8193. if (quest.id < 1e6 && quest.state == 2) {
  8194. reSend = true;
  8195. }
  8196. }
  8197. }
  8198. }
  8199. setProgress(I18N('COLLECT_REWARDS_AND_MAIL', { countQuests, countMail }), true);
  8200. if (reSend) {
  8201. rewardsAndMailFarm()
  8202. }
  8203. resolve();
  8204. });
  8205. });
  8206. })
  8207. }
  8208.  
  8209. class epicBrawl {
  8210. timeout = null;
  8211. time = null;
  8212.  
  8213. constructor() {
  8214. if (epicBrawl.inst) {
  8215. return epicBrawl.inst;
  8216. }
  8217. epicBrawl.inst = this;
  8218. return this;
  8219. }
  8220.  
  8221. runTimeout(func, timeDiff) {
  8222. const worker = new Worker(URL.createObjectURL(new Blob([`
  8223. self.onmessage = function(e) {
  8224. const timeDiff = e.data;
  8225.  
  8226. if (timeDiff > 0) {
  8227. setTimeout(() => {
  8228. self.postMessage(1);
  8229. self.close();
  8230. }, timeDiff);
  8231. }
  8232. };
  8233. `])));
  8234. worker.postMessage(timeDiff);
  8235. worker.onmessage = () => {
  8236. func();
  8237. };
  8238. return true;
  8239. }
  8240.  
  8241. timeDiff(date1, date2) {
  8242. const date1Obj = new Date(date1);
  8243. const date2Obj = new Date(date2);
  8244.  
  8245. const timeDiff = Math.abs(date2Obj - date1Obj);
  8246.  
  8247. const totalSeconds = timeDiff / 1000;
  8248. const minutes = Math.floor(totalSeconds / 60);
  8249. const seconds = Math.floor(totalSeconds % 60);
  8250.  
  8251. const formattedMinutes = String(minutes).padStart(2, '0');
  8252. const formattedSeconds = String(seconds).padStart(2, '0');
  8253.  
  8254. return `${formattedMinutes}:${formattedSeconds}`;
  8255. }
  8256.  
  8257. check() {
  8258. console.log(new Date(this.time))
  8259. if (Date.now() > this.time) {
  8260. this.timeout = null;
  8261. this.start()
  8262. return;
  8263. }
  8264. this.timeout = this.runTimeout(() => this.check(), 6e4);
  8265. return this.timeDiff(this.time, Date.now())
  8266. }
  8267.  
  8268. async start() {
  8269. if (this.timeout) {
  8270. const time = this.timeDiff(this.time, Date.now());
  8271. console.log(new Date(this.time))
  8272. setProgress(I18N('TIMER_ALREADY', { time }), false, hideProgress);
  8273. return;
  8274. }
  8275. setProgress(I18N('EPIC_BRAWL'), false, hideProgress);
  8276. 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));
  8277. const refill = teamInfo[2].refillable.find(n => n.id == 52)
  8278. this.time = (refill.lastRefill + 3600) * 1000
  8279. const attempts = refill.amount;
  8280. if (!attempts) {
  8281. console.log(new Date(this.time));
  8282. const time = this.check();
  8283. setProgress(I18N('NO_ATTEMPTS_TIMER_START', { time }), false, hideProgress);
  8284. return;
  8285. }
  8286.  
  8287. if (!teamInfo[0].epic_brawl) {
  8288. setProgress(I18N('NO_HEROES_PACK'), false, hideProgress);
  8289. return;
  8290. }
  8291.  
  8292. const args = {
  8293. heroes: teamInfo[0].epic_brawl.filter(e => e < 1000),
  8294. pet: teamInfo[0].epic_brawl.filter(e => e > 6000).pop(),
  8295. favor: teamInfo[1].epic_brawl,
  8296. }
  8297.  
  8298. let wins = 0;
  8299. let coins = 0;
  8300. let streak = { progress: 0, nextStage: 0 };
  8301. for (let i = attempts; i > 0; i--) {
  8302. const info = await Send(JSON.stringify({
  8303. calls: [
  8304. { name: "epicBrawl_getEnemy", args: {}, ident: "epicBrawl_getEnemy" }, { name: "epicBrawl_startBattle", args, ident: "epicBrawl_startBattle" }
  8305. ]
  8306. })).then(e => e.results.map(n => n.result.response));
  8307.  
  8308. const { progress, result } = await Calc(info[1].battle);
  8309. 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));
  8310.  
  8311. const resultInfo = endResult[0].result;
  8312. streak = endResult[1];
  8313.  
  8314. wins += resultInfo.win;
  8315. coins += resultInfo.reward ? resultInfo.reward.coin[39] : 0;
  8316.  
  8317. console.log(endResult[0].result)
  8318. if (endResult[1].progress == endResult[1].nextStage) {
  8319. const farm = await Send('{"calls":[{"name":"epicBrawl_farmWinStreak","args":{},"ident":"body"}]}').then(e => e.results[0].result.response);
  8320. coins += farm.coin[39];
  8321. }
  8322.  
  8323. setProgress(I18N('EPIC_BRAWL_RESULT', {
  8324. i, wins, attempts, coins,
  8325. progress: streak.progress,
  8326. nextStage: streak.nextStage,
  8327. end: '',
  8328. }), false, hideProgress);
  8329. }
  8330.  
  8331. console.log(new Date(this.time));
  8332. const time = this.check();
  8333. setProgress(I18N('EPIC_BRAWL_RESULT', {
  8334. wins, attempts, coins,
  8335. i: '',
  8336. progress: streak.progress,
  8337. nextStage: streak.nextStage,
  8338. end: I18N('ATTEMPT_ENDED', { time }),
  8339. }), false, hideProgress);
  8340. }
  8341. }
  8342. /* тест остановка подземки*/
  8343. function stopDungeon(e) {
  8344. stopDung = true;
  8345. }
  8346.  
  8347. function countdownTimer(seconds, message) {
  8348. message = message || I18N('TIMER');
  8349. const stopTimer = Date.now() + seconds * 1e3
  8350. return new Promise(resolve => {
  8351. const interval = setInterval(async () => {
  8352. const now = Date.now();
  8353. setProgress(`${message} ${((stopTimer - now) / 1000).toFixed(2)}`, false);
  8354. if (now > stopTimer) {
  8355. clearInterval(interval);
  8356. setProgress('', 1);
  8357. resolve();
  8358. }
  8359. }, 100);
  8360. });
  8361. }
  8362.  
  8363. /** Набить килов в горниле душк */
  8364. async function bossRatingEventSouls() {
  8365. const data = await Send({
  8366. calls: [
  8367. { name: "heroGetAll", args: {}, ident: "teamGetAll" },
  8368. { name: "offerGetAll", args: {}, ident: "offerGetAll" },
  8369. { name: "pet_getAll", args: {}, ident: "pet_getAll" },
  8370. ]
  8371. });
  8372. const bossEventInfo = data.results[1].result.response.find(e => e.offerType == "bossEvent");
  8373. if (!bossEventInfo) {
  8374. setProgress('Эвент завершен', true);
  8375. return;
  8376. }
  8377.  
  8378. if (bossEventInfo.progress.score > 250) {
  8379. setProgress('Уже убито больше 250 врагов');
  8380. rewardBossRatingEventSouls();
  8381. return;
  8382. }
  8383. const availablePets = Object.values(data.results[2].result.response).map(e => e.id);
  8384. const heroGetAllList = data.results[0].result.response;
  8385. const usedHeroes = bossEventInfo.progress.usedHeroes;
  8386. const heroList = [];
  8387.  
  8388. for (let heroId in heroGetAllList) {
  8389. let hero = heroGetAllList[heroId];
  8390. if (usedHeroes.includes(hero.id)) {
  8391. continue;
  8392. }
  8393. heroList.push(hero.id);
  8394. }
  8395.  
  8396. if (!heroList.length) {
  8397. setProgress('Нет героев', true);
  8398. return;
  8399. }
  8400.  
  8401. const pet = availablePets.includes(6005) ? 6005 : availablePets[Math.floor(Math.random() * availablePets.length)];
  8402. const petLib = lib.getData('pet');
  8403. let count = 1;
  8404.  
  8405. for (const heroId of heroList) {
  8406. const args = {
  8407. heroes: [heroId],
  8408. pet
  8409. }
  8410. /** Поиск питомца для героя */
  8411. for (const petId of availablePets) {
  8412. if (petLib[petId].favorHeroes.includes(heroId)) {
  8413. args.favor = {
  8414. [heroId]: petId
  8415. }
  8416. break;
  8417. }
  8418. }
  8419.  
  8420. const calls = [{
  8421. name: "bossRatingEvent_startBattle",
  8422. args,
  8423. ident: "body"
  8424. }, {
  8425. name: "offerGetAll",
  8426. args: {},
  8427. ident: "offerGetAll"
  8428. }];
  8429.  
  8430. const res = await Send({ calls });
  8431. count++;
  8432.  
  8433. if ('error' in res) {
  8434. console.error(res.error);
  8435. setProgress('Перезагрузите игру и попробуйте позже', true);
  8436. return;
  8437. }
  8438.  
  8439. const eventInfo = res.results[1].result.response.find(e => e.offerType == "bossEvent");
  8440. if (eventInfo.progress.score > 250) {
  8441. break;
  8442. }
  8443. setProgress('Количество убитых врагов: ' + eventInfo.progress.score + '<br>Использовано ' + count + ' героев');
  8444. }
  8445.  
  8446. rewardBossRatingEventSouls();
  8447. }
  8448. /** Сбор награды из Горнила Душ */
  8449. async function rewardBossRatingEventSouls() {
  8450. const data = await Send({
  8451. calls: [
  8452. { name: "offerGetAll", args: {}, ident: "offerGetAll" }
  8453. ]
  8454. });
  8455.  
  8456. const bossEventInfo = data.results[0].result.response.find(e => e.offerType == "bossEvent");
  8457. if (!bossEventInfo) {
  8458. setProgress('Эвент завершен', true);
  8459. return;
  8460. }
  8461.  
  8462. const farmedChests = bossEventInfo.progress.farmedChests;
  8463. const score = bossEventInfo.progress.score;
  8464. // setProgress('Количество убитых врагов: ' + score);
  8465. const revard = bossEventInfo.reward;
  8466. const calls = [];
  8467.  
  8468. let count = 0;
  8469. for (let i = 1; i < 10; i++) {
  8470. if (farmedChests.includes(i)) {
  8471. continue;
  8472. }
  8473. if (score < revard[i].score) {
  8474. break;
  8475. }
  8476. calls.push({
  8477. name: "bossRatingEvent_getReward",
  8478. args: {
  8479. rewardId: i
  8480. },
  8481. ident: "body_" + i
  8482. });
  8483. count++;
  8484. }
  8485. if (!count) {
  8486. setProgress('Нечего собирать', true);
  8487. return;
  8488. }
  8489.  
  8490. Send({ calls }).then(e => {
  8491. console.log(e);
  8492. setProgress('Собрано ' + e?.results?.length + ' наград', true);
  8493. })
  8494. }
  8495. /**
  8496. * Spin the Seer
  8497. *
  8498. * Покрутить провидца
  8499. */
  8500. async function rollAscension() {
  8501. const refillable = await Send({calls:[
  8502. {
  8503. name:"userGetInfo",
  8504. args:{},
  8505. ident:"userGetInfo"
  8506. }
  8507. ]}).then(e => e.results[0].result.response.refillable);
  8508. const i47 = refillable.find(i => i.id == 47);
  8509. if (i47?.amount) {
  8510. await Send({ calls: [{ name: "ascensionChest_open", args: { paid: false, amount: 1 }, ident: "body" }] });
  8511. setProgress(I18N('DONE'), true);
  8512. } else {
  8513. setProgress(I18N('NOT_ENOUGH_AP'), true);
  8514. }
  8515. }
  8516.  
  8517. /**
  8518. * Collect gifts for the New Year
  8519. *
  8520. * Собрать подарки на новый год
  8521. */
  8522. function getGiftNewYear() {
  8523. Send({ calls: [{ name: "newYearGiftGet", args: { type: 0 }, ident: "body" }] }).then(e => {
  8524. const gifts = e.results[0].result.response.gifts;
  8525. const calls = gifts.filter(e => e.opened == 0).map(e => ({
  8526. name: "newYearGiftOpen",
  8527. args: {
  8528. giftId: e.id
  8529. },
  8530. ident: `body_${e.id}`
  8531. }));
  8532. if (!calls.length) {
  8533. setProgress(I18N('NY_NO_GIFTS'), 5000);
  8534. return;
  8535. }
  8536. Send({ calls }).then(e => {
  8537. console.log(e.results)
  8538. const msg = I18N('NY_GIFTS_COLLECTED', { count: e.results.length });
  8539. console.log(msg);
  8540. setProgress(msg, 5000);
  8541. });
  8542. })
  8543. }
  8544.  
  8545. async function updateArtifacts() {
  8546. const count = +await popup.confirm(I18N('SET_NUMBER_LEVELS'), [
  8547. { msg: I18N('BTN_GO'), isInput: true, default: 10 },
  8548. { result: false, isClose: true }
  8549. ]);
  8550. if (!count) {
  8551. return;
  8552. }
  8553. const quest = new questRun;
  8554. await quest.autoInit();
  8555. const heroes = Object.values(quest.questInfo['heroGetAll']);
  8556. const inventory = quest.questInfo['inventoryGet'];
  8557. const calls = [];
  8558. for (let i = count; i > 0; i--) {
  8559. const upArtifact = quest.getUpgradeArtifact();
  8560. if (!upArtifact.heroId) {
  8561. if (await popup.confirm(I18N('POSSIBLE_IMPROVE_LEVELS', { count: calls.length }), [
  8562. { msg: I18N('YES'), result: true },
  8563. { result: false, isClose: true }
  8564. ])) {
  8565. break;
  8566. } else {
  8567. return;
  8568. }
  8569. }
  8570. const hero = heroes.find(e => e.id == upArtifact.heroId);
  8571. hero.artifacts[upArtifact.slotId].level++;
  8572. inventory[upArtifact.costСurrency][upArtifact.costId] -= upArtifact.costValue;
  8573. calls.push({
  8574. name: "heroArtifactLevelUp",
  8575. args: {
  8576. heroId: upArtifact.heroId,
  8577. slotId: upArtifact.slotId
  8578. },
  8579. ident: `heroArtifactLevelUp_${i}`
  8580. });
  8581. }
  8582.  
  8583. if (!calls.length) {
  8584. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  8585. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  8586. return;
  8587. }
  8588.  
  8589. await Send(JSON.stringify({ calls })).then(e => {
  8590. if ('error' in e) {
  8591. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  8592. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  8593. } else {
  8594. console.log(I18N('IMPROVED_LEVELS', { count: e.results.length }));
  8595. setProgress(I18N('IMPROVED_LEVELS', { count: e.results.length }), false);
  8596. }
  8597. });
  8598. }
  8599.  
  8600. window.sign = a => {
  8601. const i = this['\x78\x79\x7a'];
  8602. return md5([i['\x6e\x61\x6d\x65'], i['\x76\x65\x72\x73\x69\x6f\x6e'], i['\x61\x75\x74\x68\x6f\x72'], ~(a % 1e3)]['\x6a\x6f\x69\x6e']('\x5f'))
  8603. }
  8604.  
  8605. async function updateSkins() {
  8606. const count = +await popup.confirm(I18N('SET_NUMBER_LEVELS'), [
  8607. { msg: I18N('BTN_GO'), isInput: true, default: 10 },
  8608. { result: false, isClose: true }
  8609. ]);
  8610. if (!count) {
  8611. return;
  8612. }
  8613.  
  8614. const quest = new questRun;
  8615. await quest.autoInit();
  8616. const heroes = Object.values(quest.questInfo['heroGetAll']);
  8617. const inventory = quest.questInfo['inventoryGet'];
  8618. const calls = [];
  8619. for (let i = count; i > 0; i--) {
  8620. const upSkin = quest.getUpgradeSkin();
  8621. if (!upSkin.heroId) {
  8622. if (await popup.confirm(I18N('POSSIBLE_IMPROVE_LEVELS', { count: calls.length }), [
  8623. { msg: I18N('YES'), result: true },
  8624. { result: false, isClose: true }
  8625. ])) {
  8626. break;
  8627. } else {
  8628. return;
  8629. }
  8630. }
  8631. const hero = heroes.find(e => e.id == upSkin.heroId);
  8632. hero.skins[upSkin.skinId]++;
  8633. inventory[upSkin.costСurrency][upSkin.costСurrencyId] -= upSkin.cost;
  8634. calls.push({
  8635. name: "heroSkinUpgrade",
  8636. args: {
  8637. heroId: upSkin.heroId,
  8638. skinId: upSkin.skinId
  8639. },
  8640. ident: `heroSkinUpgrade_${i}`
  8641. })
  8642. }
  8643.  
  8644. if (!calls.length) {
  8645. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  8646. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  8647. return;
  8648. }
  8649.  
  8650. await Send(JSON.stringify({ calls })).then(e => {
  8651. if ('error' in e) {
  8652. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  8653. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  8654. } else {
  8655. console.log(I18N('IMPROVED_LEVELS', { count: e.results.length }));
  8656. setProgress(I18N('IMPROVED_LEVELS', { count: e.results.length }), false);
  8657. }
  8658. });
  8659. }
  8660.  
  8661. function getQuestionInfo(img, nameOnly = false) {
  8662. const libHeroes = Object.values(lib.data.hero);
  8663. const parts = img.split(':');
  8664. const id = parts[1];
  8665. switch (parts[0]) {
  8666. case 'titanArtifact_id':
  8667. return cheats.translate("LIB_TITAN_ARTIFACT_NAME_" + id);
  8668. case 'titan':
  8669. return cheats.translate("LIB_HERO_NAME_" + id);
  8670. case 'skill':
  8671. return cheats.translate("LIB_SKILL_" + id);
  8672. case 'inventoryItem_gear':
  8673. return cheats.translate("LIB_GEAR_NAME_" + id);
  8674. case 'inventoryItem_coin':
  8675. return cheats.translate("LIB_COIN_NAME_" + id);
  8676. case 'artifact':
  8677. if (nameOnly) {
  8678. return cheats.translate("LIB_ARTIFACT_NAME_" + id);
  8679. }
  8680. heroes = libHeroes.filter(h => h.id < 100 && h.artifacts.includes(+id));
  8681. return {
  8682. /** Как называется этот артефакт? */
  8683. name: cheats.translate("LIB_ARTIFACT_NAME_" + id),
  8684. /** Какому герою принадлежит этот артефакт? */
  8685. heroes: heroes.map(h => cheats.translate("LIB_HERO_NAME_" + h.id))
  8686. };
  8687. case 'hero':
  8688. if (nameOnly) {
  8689. return cheats.translate("LIB_HERO_NAME_" + id);
  8690. }
  8691. artifacts = lib.data.hero[id].artifacts;
  8692. return {
  8693. /** Как зовут этого героя? */
  8694. name: cheats.translate("LIB_HERO_NAME_" + id),
  8695. /** Какой артефакт принадлежит этому герою? */
  8696. artifact: artifacts.map(a => cheats.translate("LIB_ARTIFACT_NAME_" + a))
  8697. };
  8698. }
  8699. }
  8700.  
  8701. function hintQuest(quest) {
  8702. const result = {};
  8703. if (quest?.questionIcon) {
  8704. const info = getQuestionInfo(quest.questionIcon);
  8705. if (info?.heroes) {
  8706. /** Какому герою принадлежит этот артефакт? */
  8707. result.answer = quest.answers.filter(e => info.heroes.includes(e.answerText.slice(1)));
  8708. }
  8709. if (info?.artifact) {
  8710. /** Какой артефакт принадлежит этому герою? */
  8711. result.answer = quest.answers.filter(e => info.artifact.includes(e.answerText.slice(1)));
  8712. }
  8713. if (typeof info == 'string') {
  8714. result.info = { name: info };
  8715. } else {
  8716. result.info = info;
  8717. }
  8718. }
  8719.  
  8720. if (quest.answers[0]?.answerIcon) {
  8721. result.answer = quest.answers.filter(e => quest.question.includes(getQuestionInfo(e.answerIcon, true)))
  8722. }
  8723.  
  8724. if ((!result?.answer || !result.answer.length) && !result.info?.name) {
  8725. return false;
  8726. }
  8727.  
  8728. let resultText = '';
  8729. if (result?.info) {
  8730. resultText += I18N('PICTURE') + result.info.name;
  8731. }
  8732. console.log(result);
  8733. if (result?.answer && result.answer.length) {
  8734. resultText += I18N('ANSWER') + result.answer[0].id + (!result.answer[0].answerIcon ? ' - ' + result.answer[0].answerText : '');
  8735. }
  8736.  
  8737. return resultText;
  8738. }
  8739.  
  8740. /**
  8741. * Attack of the minions of Asgard
  8742. *
  8743. * Атака прислужников Асгарда
  8744. */
  8745. function testRaidNodes() {
  8746. return new Promise((resolve, reject) => {
  8747. const tower = new executeRaidNodes(resolve, reject);
  8748. tower.start();
  8749. });
  8750. }
  8751.  
  8752. /**
  8753. * Attack of the minions of Asgard
  8754. *
  8755. * Атака прислужников Асгарда
  8756. */
  8757. function executeRaidNodes(resolve, reject) {
  8758. let raidData = {
  8759. teams: [],
  8760. favor: {},
  8761. nodes: [],
  8762. attempts: 0,
  8763. countExecuteBattles: 0,
  8764. cancelBattle: 0,
  8765. }
  8766.  
  8767. callsExecuteRaidNodes = {
  8768. calls: [{
  8769. name: "clanRaid_getInfo",
  8770. args: {},
  8771. ident: "clanRaid_getInfo"
  8772. }, {
  8773. name: "teamGetAll",
  8774. args: {},
  8775. ident: "teamGetAll"
  8776. }, {
  8777. name: "teamGetFavor",
  8778. args: {},
  8779. ident: "teamGetFavor"
  8780. }]
  8781. }
  8782.  
  8783. this.start = function () {
  8784. send(JSON.stringify(callsExecuteRaidNodes), startRaidNodes);
  8785. }
  8786.  
  8787. async function startRaidNodes(data) {
  8788. res = data.results;
  8789. clanRaidInfo = res[0].result.response;
  8790. teamGetAll = res[1].result.response;
  8791. teamGetFavor = res[2].result.response;
  8792.  
  8793. let index = 0;
  8794. let isNotFullPack = false;
  8795. for (let team of teamGetAll.clanRaid_nodes) {
  8796. if (team.length < 6) {
  8797. isNotFullPack = true;
  8798. }
  8799. raidData.teams.push({
  8800. data: {},
  8801. heroes: team.filter(id => id < 6000),
  8802. pet: team.filter(id => id >= 6000).pop(),
  8803. battleIndex: index++
  8804. });
  8805. }
  8806. raidData.favor = teamGetFavor.clanRaid_nodes;
  8807.  
  8808. if (isNotFullPack) {
  8809. if (await popup.confirm(I18N('MINIONS_WARNING'), [
  8810. { msg: I18N('BTN_NO'), result: true },
  8811. { msg: I18N('BTN_YES'), result: false },
  8812. ])) {
  8813. endRaidNodes('isNotFullPack');
  8814. return;
  8815. }
  8816. }
  8817.  
  8818. raidData.nodes = clanRaidInfo.nodes;
  8819. raidData.attempts = clanRaidInfo.attempts;
  8820. isCancalBattle = false;
  8821.  
  8822. checkNodes();
  8823. }
  8824.  
  8825. function getAttackNode() {
  8826. for (let nodeId in raidData.nodes) {
  8827. let node = raidData.nodes[nodeId];
  8828. let points = 0
  8829. for (team of node.teams) {
  8830. points += team.points;
  8831. }
  8832. let now = Date.now() / 1000;
  8833. if (!points && now > node.timestamps.start && now < node.timestamps.end) {
  8834. let countTeam = node.teams.length;
  8835. delete raidData.nodes[nodeId];
  8836. return {
  8837. nodeId,
  8838. countTeam
  8839. };
  8840. }
  8841. }
  8842. return null;
  8843. }
  8844.  
  8845. function checkNodes() {
  8846. setProgress(`${I18N('REMAINING_ATTEMPTS')}: ${raidData.attempts}`);
  8847. let nodeInfo = getAttackNode();
  8848. if (nodeInfo && raidData.attempts) {
  8849. startNodeBattles(nodeInfo);
  8850. return;
  8851. }
  8852.  
  8853. endRaidNodes('EndRaidNodes');
  8854. }
  8855.  
  8856. function startNodeBattles(nodeInfo) {
  8857. let {nodeId, countTeam} = nodeInfo;
  8858. let teams = raidData.teams.slice(0, countTeam);
  8859. let heroes = raidData.teams.map(e => e.heroes).flat();
  8860. let favor = {...raidData.favor};
  8861. for (let heroId in favor) {
  8862. if (!heroes.includes(+heroId)) {
  8863. delete favor[heroId];
  8864. }
  8865. }
  8866.  
  8867. let calls = [{
  8868. name: "clanRaid_startNodeBattles",
  8869. args: {
  8870. nodeId,
  8871. teams,
  8872. favor
  8873. },
  8874. ident: "body"
  8875. }];
  8876.  
  8877. send(JSON.stringify({calls}), resultNodeBattles);
  8878. }
  8879.  
  8880. function resultNodeBattles(e) {
  8881. if (e['error']) {
  8882. endRaidNodes('nodeBattlesError', e['error']);
  8883. return;
  8884. }
  8885.  
  8886. console.log(e);
  8887. let battles = e.results[0].result.response.battles;
  8888. let promises = [];
  8889. let battleIndex = 0;
  8890. for (let battle of battles) {
  8891. battle.battleIndex = battleIndex++;
  8892. promises.push(calcBattleResult(battle));
  8893. }
  8894.  
  8895. Promise.all(promises)
  8896. .then(results => {
  8897. const endResults = {};
  8898. let isAllWin = true;
  8899. for (let r of results) {
  8900. isAllWin &&= r.result.win;
  8901. }
  8902. if (!isAllWin) {
  8903. cancelEndNodeBattle(results[0]);
  8904. return;
  8905. }
  8906. raidData.countExecuteBattles = results.length;
  8907. let timeout = 500;
  8908. for (let r of results) {
  8909. setTimeout(endNodeBattle, timeout, r);
  8910. timeout += 500;
  8911. }
  8912. });
  8913. }
  8914. /**
  8915. * Returns the battle calculation promise
  8916. *
  8917. * Возвращает промис расчета боя
  8918. */
  8919. function calcBattleResult(battleData) {
  8920. return new Promise(function (resolve, reject) {
  8921. BattleCalc(battleData, "get_clanPvp", resolve);
  8922. });
  8923. }
  8924. /**
  8925. * Cancels the fight
  8926. *
  8927. * Отменяет бой
  8928. */
  8929. function cancelEndNodeBattle(r) {
  8930. const fixBattle = function (heroes) {
  8931. for (const ids in heroes) {
  8932. hero = heroes[ids];
  8933. hero.energy = random(1, 999);
  8934. if (hero.hp > 0) {
  8935. hero.hp = random(1, hero.hp);
  8936. }
  8937. }
  8938. }
  8939. fixBattle(r.progress[0].attackers.heroes);
  8940. fixBattle(r.progress[0].defenders.heroes);
  8941. endNodeBattle(r);
  8942. }
  8943. /**
  8944. * Ends the fight
  8945. *
  8946. * Завершает бой
  8947. */
  8948. function endNodeBattle(r) {
  8949. let nodeId = r.battleData.result.nodeId;
  8950. let battleIndex = r.battleData.battleIndex;
  8951. let calls = [{
  8952. name: "clanRaid_endNodeBattle",
  8953. args: {
  8954. nodeId,
  8955. battleIndex,
  8956. result: r.result,
  8957. progress: r.progress
  8958. },
  8959. ident: "body"
  8960. }]
  8961.  
  8962. SendRequest(JSON.stringify({calls}), battleResult);
  8963. }
  8964. /**
  8965. * Processing the results of the battle
  8966. *
  8967. * Обработка результатов боя
  8968. */
  8969. function battleResult(e) {
  8970. if (e['error']) {
  8971. endRaidNodes('missionEndError', e['error']);
  8972. return;
  8973. }
  8974. r = e.results[0].result.response;
  8975. if (r['error']) {
  8976. if (r.reason == "invalidBattle") {
  8977. raidData.cancelBattle++;
  8978. checkNodes();
  8979. } else {
  8980. endRaidNodes('missionEndError', e['error']);
  8981. }
  8982. return;
  8983. }
  8984.  
  8985. if (!(--raidData.countExecuteBattles)) {
  8986. raidData.attempts--;
  8987. checkNodes();
  8988. }
  8989. }
  8990. /**
  8991. * Completing a task
  8992. *
  8993. * Завершение задачи
  8994. */
  8995. function endRaidNodes(reason, info) {
  8996. isCancalBattle = true;
  8997. let textCancel = raidData.cancelBattle ? ` ${I18N('BATTLES_CANCELED')}: ${raidData.cancelBattle}` : '';
  8998. setProgress(`${I18N('MINION_RAID')} ${I18N('COMPLETED')}! ${textCancel}`, true);
  8999. console.log(reason, info);
  9000. resolve();
  9001. }
  9002. }
  9003.  
  9004. /**
  9005. * Asgard Boss Attack Replay
  9006. *
  9007. * Повтор атаки босса Асгарда
  9008. */
  9009. function testBossBattle() {
  9010. return new Promise((resolve, reject) => {
  9011. const bossBattle = new executeBossBattle(resolve, reject);
  9012. bossBattle.start(lastBossBattle, lastBossBattleInfo);
  9013. });
  9014. }
  9015.  
  9016. /**
  9017. * Asgard Boss Attack Replay
  9018. *
  9019. * Повтор атаки босса Асгарда
  9020. */
  9021. function executeBossBattle(resolve, reject) {
  9022. let lastBossBattleArgs = {};
  9023. let reachDamage = 0;
  9024. let countBattle = 0;
  9025. let countMaxBattle = 10;
  9026. let lastDamage = 0;
  9027.  
  9028. this.start = function (battleArg, battleInfo) {
  9029. lastBossBattleArgs = battleArg;
  9030. preCalcBattle(battleInfo);
  9031. }
  9032.  
  9033. function getBattleInfo(battle) {
  9034. return new Promise(function (resolve) {
  9035. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  9036. BattleCalc(battle, getBattleType(battle.type), e => {
  9037. let extra = e.progress[0].defenders.heroes[1].extra;
  9038. resolve(extra.damageTaken + extra.damageTakenNextLevel);
  9039. });
  9040. });
  9041. }
  9042.  
  9043. function preCalcBattle(battle) {
  9044. let actions = [];
  9045. const countTestBattle = getInput('countTestBattle');
  9046. for (let i = 0; i < countTestBattle; i++) {
  9047. actions.push(getBattleInfo(battle, true));
  9048. }
  9049. Promise.all(actions)
  9050. .then(resultPreCalcBattle);
  9051. }
  9052.  
  9053. function fixDamage(damage) {
  9054. for (let i = 1e6; i > 1; i /= 10) {
  9055. if (damage > i) {
  9056. let n = i / 10;
  9057. damage = Math.ceil(damage / n) * n;
  9058. break;
  9059. }
  9060. }
  9061. return damage;
  9062. }
  9063.  
  9064. async function resultPreCalcBattle(damages) {
  9065. let maxDamage = 0;
  9066. let minDamage = 1e10;
  9067. let avgDamage = 0;
  9068. for (let damage of damages) {
  9069. avgDamage += damage
  9070. if (damage > maxDamage) {
  9071. maxDamage = damage;
  9072. }
  9073. if (damage < minDamage) {
  9074. minDamage = damage;
  9075. }
  9076. }
  9077. avgDamage /= damages.length;
  9078. console.log(damages.map(e => e.toLocaleString()).join('\n'), avgDamage, maxDamage);
  9079.  
  9080. reachDamage = fixDamage(avgDamage);
  9081. const result = await popup.confirm(
  9082. `${I18N('ROUND_STAT')} ${damages.length} ${I18N('BATTLE')}:` +
  9083. `<br>${I18N('MINIMUM')}: ` + minDamage.toLocaleString() +
  9084. `<br>${I18N('MAXIMUM')}: ` + maxDamage.toLocaleString() +
  9085. `<br>${I18N('AVERAGE')}: ` + avgDamage.toLocaleString()
  9086. /*+ '<br>Поиск урона больше чем ' + reachDamage.toLocaleString()*/
  9087. , [
  9088. { msg: I18N('BTN_OK'), result: 0},
  9089. /* {msg: 'Погнали', isInput: true, default: reachDamage}, */
  9090. ])
  9091. if (result) {
  9092. reachDamage = result;
  9093. isCancalBossBattle = false;
  9094. startBossBattle();
  9095. return;
  9096. }
  9097. endBossBattle(I18N('BTN_CANCEL'));
  9098. }
  9099.  
  9100. function startBossBattle() {
  9101. countBattle++;
  9102. countMaxBattle = getInput('countAutoBattle');
  9103. if (countBattle > countMaxBattle) {
  9104. setProgress('Превышен лимит попыток: ' + countMaxBattle, true);
  9105. endBossBattle('Превышен лимит попыток: ' + countMaxBattle);
  9106. return;
  9107. }
  9108. let calls = [{
  9109. name: "clanRaid_startBossBattle",
  9110. args: lastBossBattleArgs,
  9111. ident: "body"
  9112. }];
  9113. send(JSON.stringify({calls}), calcResultBattle);
  9114. }
  9115.  
  9116. function calcResultBattle(e) {
  9117. BattleCalc(e.results[0].result.response.battle, "get_clanPvp", resultBattle);
  9118. }
  9119.  
  9120. async function resultBattle(e) {
  9121. let extra = e.progress[0].defenders.heroes[1].extra
  9122. resultDamage = extra.damageTaken + extra.damageTakenNextLevel
  9123. console.log(resultDamage);
  9124. scriptMenu.setStatus(countBattle + ') ' + resultDamage.toLocaleString());
  9125. lastDamage = resultDamage;
  9126. if (resultDamage > reachDamage && await popup.confirm(countBattle + ') Урон ' + resultDamage.toLocaleString(), [
  9127. {msg: 'Ок', result: true},
  9128. {msg: 'Не пойдет', result: false},
  9129. ])) {
  9130. endBattle(e, false);
  9131. return;
  9132. }
  9133. cancelEndBattle(e);
  9134. }
  9135.  
  9136. function cancelEndBattle (r) {
  9137. const fixBattle = function (heroes) {
  9138. for (const ids in heroes) {
  9139. hero = heroes[ids];
  9140. hero.energy = random(1, 999);
  9141. if (hero.hp > 0) {
  9142. hero.hp = random(1, hero.hp);
  9143. }
  9144. }
  9145. }
  9146. fixBattle(r.progress[0].attackers.heroes);
  9147. fixBattle(r.progress[0].defenders.heroes);
  9148. endBattle(r, true);
  9149. }
  9150.  
  9151. function endBattle(battleResult, isCancal) {
  9152. let calls = [{
  9153. name: "clanRaid_endBossBattle",
  9154. args: {
  9155. result: battleResult.result,
  9156. progress: battleResult.progress
  9157. },
  9158. ident: "body"
  9159. }];
  9160.  
  9161. send(JSON.stringify({calls}), e => {
  9162. console.log(e);
  9163. if (isCancal) {
  9164. startBossBattle();
  9165. return;
  9166. }
  9167. scriptMenu.setStatus('Босс пробит нанесен урон: ' + lastDamage);
  9168. setTimeout(() => {
  9169. scriptMenu.setStatus('');
  9170. }, 5000);
  9171. endBossBattle('Узпех!');
  9172. });
  9173. }
  9174.  
  9175. /**
  9176. * Completing a task
  9177. *
  9178. * Завершение задачи
  9179. */
  9180. function endBossBattle(reason, info) {
  9181. isCancalBossBattle = true;
  9182. console.log(reason, info);
  9183. resolve();
  9184. }
  9185. }
  9186.  
  9187. /**
  9188. * Auto-repeat attack
  9189. *
  9190. * Автоповтор атаки
  9191. */
  9192. function testAutoBattle() {
  9193. return new Promise((resolve, reject) => {
  9194. const bossBattle = new executeAutoBattle(resolve, reject);
  9195. bossBattle.start(lastBattleArg, lastBattleInfo);
  9196. });
  9197. }
  9198.  
  9199. /**
  9200. * Auto-repeat attack
  9201. *
  9202. * Автоповтор атаки
  9203. */
  9204. function executeAutoBattle(resolve, reject) {
  9205. let battleArg = {};
  9206. let countBattle = 0;
  9207. let countError = 0;
  9208. let findCoeff = 0;
  9209. const svgJustice = '<svg width="20" height="20" viewBox="0 0 124 125" xmlns="http://www.w3.org/2000/svg" style="fill: #fff;"><g><path d="m54 0h-1c-7.25 6.05-17.17 6.97-25.78 10.22-8.6 3.25-23.68 1.07-23.22 12.78s-0.47 24.08 1 35 2.36 18.36 7 28c4.43-8.31-3.26-18.88-3-30 0.26-11.11-2.26-25.29-1-37 11.88-4.16 26.27-0.42 36.77-9.23s20.53 6.05 29.23-0.77c-6.65-2.98-14.08-4.96-20-9z"/></g><g><path d="m108 5c-11.05 2.96-27.82 2.2-35.08 11.92s-14.91 14.71-22.67 23.33c-7.77 8.62-14.61 15.22-22.25 23.75 7.05 11.93 14.33 2.58 20.75-4.25 6.42-6.82 12.98-13.03 19.5-19.5s12.34-13.58 19.75-18.25c2.92 7.29-8.32 12.65-13.25 18.75-4.93 6.11-12.19 11.48-17.5 17.5s-12.31 11.38-17.25 17.75c10.34 14.49 17.06-3.04 26.77-10.23s15.98-16.89 26.48-24.52c10.5-7.64 12.09-24.46 14.75-36.25z"/></g><g><path d="m60 25c-11.52-6.74-24.53 8.28-38 6 0.84 9.61-1.96 20.2 2 29 5.53-4.04-4.15-23.2 4.33-26.67 8.48-3.48 18.14-1.1 24.67-8.33 2.73 0.3 4.81 2.98 7 0z"/></g><g><path d="m100 75c3.84-11.28 5.62-25.85 3-38-4.2 5.12-3.5 13.58-4 20s-3.52 13.18 1 18z"/></g><g><path d="m55 94c15.66-5.61 33.71-20.85 29-39-3.07 8.05-4.3 16.83-10.75 23.25s-14.76 8.35-18.25 15.75z"/></g><g><path d="m0 94v7c6.05 3.66 9.48 13.3 18 11-3.54-11.78 8.07-17.05 14-25 6.66 1.52 13.43 16.26 19 5-11.12-9.62-20.84-21.33-32-31-9.35 6.63 4.76 11.99 6 19-7.88 5.84-13.24 17.59-25 14z"/></g><g><path d="m82 125h26v-19h16v-1c-11.21-8.32-18.38-21.74-30-29-8.59 10.26-19.05 19.27-27 30h15v19z"/></g><g><path d="m68 110c-7.68-1.45-15.22 4.83-21.92-1.08s-11.94-5.72-18.08-11.92c-3.03 8.84 10.66 9.88 16.92 16.08s17.09 3.47 23.08-3.08z"/></g></svg>';
  9210. const svgBoss = '<svg width="20" height="20" viewBox="0 0 40 41" xmlns="http://www.w3.org/2000/svg" style="fill: #fff;"><g><path d="m21 12c-2.19-3.23 5.54-10.95-0.97-10.97-6.52-0.02 1.07 7.75-1.03 10.97-2.81 0.28-5.49-0.2-8-1-0.68 3.53 0.55 6.06 4 4 0.65 7.03 1.11 10.95 1.67 18.33 0.57 7.38 6.13 7.2 6.55-0.11 0.42-7.3 1.35-11.22 1.78-18.22 3.53 1.9 4.73-0.42 4-4-2.61 0.73-5.14 1.35-8 1m-1 17c-1.59-3.6-1.71-10.47 0-14 1.59 3.6 1.71 10.47 0 14z"/></g><g><path d="m6 19c-1.24-4.15 2.69-8.87 1-12-3.67 4.93-6.52 10.57-6 17 5.64-0.15 8.82 4.98 13 8 1.3-6.54-0.67-12.84-8-13z"/></g><g><path d="m33 7c0.38 5.57 2.86 14.79-7 15v10c4.13-2.88 7.55-7.97 13-8 0.48-6.46-2.29-12.06-6-17z"/></g></svg>';
  9211. const svgAttempt = '<svg width="20" height="20" viewBox="0 0 645 645" xmlns="http://www.w3.org/2000/svg" style="fill: #fff;"><g><path d="m442 26c-8.8 5.43-6.6 21.6-12.01 30.99-2.5 11.49-5.75 22.74-8.99 34.01-40.61-17.87-92.26-15.55-133.32-0.32-72.48 27.31-121.88 100.19-142.68 171.32 10.95-4.49 19.28-14.97 29.3-21.7 50.76-37.03 121.21-79.04 183.47-44.07 16.68 5.8 2.57 21.22-0.84 31.7-4.14 12.19-11.44 23.41-13.93 36.07 56.01-17.98 110.53-41.23 166-61-20.49-59.54-46.13-117.58-67-177z"/></g><g><path d="m563 547c23.89-16.34 36.1-45.65 47.68-71.32 23.57-62.18 7.55-133.48-28.38-186.98-15.1-22.67-31.75-47.63-54.3-63.7 1.15 14.03 6.71 26.8 8.22 40.78 12.08 61.99 15.82 148.76-48.15 183.29-10.46-0.54-15.99-16.1-24.32-22.82-8.2-7.58-14.24-19.47-23.75-24.25-4.88 59.04-11.18 117.71-15 177 62.9 5.42 126.11 9.6 189 15-4.84-9.83-17.31-15.4-24.77-24.23-9.02-7.06-17.8-15.13-26.23-22.77z"/></g><g><path d="m276 412c-10.69-15.84-30.13-25.9-43.77-40.23-15.39-12.46-30.17-25.94-45.48-38.52-15.82-11.86-29.44-28.88-46.75-37.25-19.07 24.63-39.96 48.68-60.25 72.75-18.71 24.89-42.41 47.33-58.75 73.25 22.4-2.87 44.99-13.6 66.67-13.67 0.06 22.8 10.69 42.82 20.41 62.59 49.09 93.66 166.6 114.55 261.92 96.08-6.07-9.2-22.11-9.75-31.92-16.08-59.45-26.79-138.88-75.54-127.08-151.92 21.66-2.39 43.42-4.37 65-7z"/></g></svg>';
  9212.  
  9213. this.start = function (battleArgs, battleInfo) {
  9214. battleArg = battleArgs;
  9215. preCalcBattle(battleInfo);
  9216. }
  9217. /**
  9218. * Returns a promise for combat recalculation
  9219. *
  9220. * Возвращает промис для прерасчета боя
  9221. */
  9222. function getBattleInfo(battle) {
  9223. return new Promise(function (resolve) {
  9224. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  9225. Calc(battle).then(e => {
  9226. e.coeff = calcCoeff(e, 'defenders');
  9227. resolve(e);
  9228. });
  9229. });
  9230. }
  9231. /**
  9232. * Battle recalculation
  9233. *
  9234. * Прерасчет боя
  9235. */
  9236. function preCalcBattle(battle) {
  9237. let actions = [];
  9238. const countTestBattle = getInput('countTestBattle');
  9239. for (let i = 0; i < countTestBattle; i++) {
  9240. actions.push(getBattleInfo(battle));
  9241. }
  9242. Promise.all(actions)
  9243. .then(resultPreCalcBattle);
  9244. }
  9245. /**
  9246. * Processing the results of the battle recalculation
  9247. *
  9248. * Обработка результатов прерасчета боя
  9249. */
  9250. async function resultPreCalcBattle(results) {
  9251. let countWin = results.reduce((s, w) => w.result.win + s, 0);
  9252. setProgress(`${I18N('CHANCE_TO_WIN')} ${Math.floor(countWin / results.length * 100)}% (${results.length})`, false, hideProgress);
  9253. if (countWin > 0) {
  9254. isCancalBattle = false;
  9255. startBattle();
  9256. return;
  9257. }
  9258.  
  9259. let minCoeff = 100;
  9260. let maxCoeff = -100;
  9261. let avgCoeff = 0;
  9262. results.forEach(e => {
  9263. if (e.coeff < minCoeff) minCoeff = e.coeff;
  9264. if (e.coeff > maxCoeff) maxCoeff = e.coeff;
  9265. avgCoeff += e.coeff;
  9266. });
  9267. avgCoeff /= results.length;
  9268.  
  9269. if (nameFuncStartBattle == 'invasion_bossStart' ||
  9270. nameFuncStartBattle == 'bossAttack') {
  9271. const result = await popup.confirm(
  9272. I18N('BOSS_VICTORY_IMPOSSIBLE', { battles: results.length }), [
  9273. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  9274. { msg: I18N('BTN_DO_IT'), result: true },
  9275. ])
  9276. if (result) {
  9277. isCancalBattle = false;
  9278. startBattle();
  9279. return;
  9280. }
  9281. setProgress(I18N('NOT_THIS_TIME'), true);
  9282. endAutoBattle('invasion_bossStart');
  9283. return;
  9284. }
  9285.  
  9286. const result = await popup.confirm(
  9287. I18N('VICTORY_IMPOSSIBLE') +
  9288. `<br>${I18N('ROUND_STAT')} ${results.length} ${I18N('BATTLE')}:` +
  9289. `<br>${I18N('MINIMUM')}: ` + minCoeff.toLocaleString() +
  9290. `<br>${I18N('MAXIMUM')}: ` + maxCoeff.toLocaleString() +
  9291. `<br>${I18N('AVERAGE')}: ` + avgCoeff.toLocaleString() +
  9292. `<br>${I18N('FIND_COEFF')} ` + avgCoeff.toLocaleString(), [
  9293. { msg: I18N('BTN_CANCEL'), result: 0, isCancel: true },
  9294. { msg: I18N('BTN_GO'), isInput: true, default: Math.round(avgCoeff * 1000) / 1000 },
  9295. ])
  9296. if (result) {
  9297. findCoeff = result;
  9298. isCancalBattle = false;
  9299. startBattle();
  9300. return;
  9301. }
  9302. setProgress(I18N('NOT_THIS_TIME'), true);
  9303. endAutoBattle(I18N('NOT_THIS_TIME'));
  9304. }
  9305.  
  9306. /**
  9307. * Calculation of the combat result coefficient
  9308. *
  9309. * Расчет коэфициента результата боя
  9310. */
  9311. function calcCoeff(result, packType) {
  9312. let beforeSumFactor = 0;
  9313. const beforePack = result.battleData[packType][0];
  9314. for (let heroId in beforePack) {
  9315. const hero = beforePack[heroId];
  9316. const state = hero.state;
  9317. let factor = 1;
  9318. if (state) {
  9319. const hp = state.hp / state.maxHp;
  9320. const energy = state.energy / 1e3;
  9321. factor = hp + energy / 20;
  9322. }
  9323. beforeSumFactor += factor;
  9324. }
  9325.  
  9326. let afterSumFactor = 0;
  9327. const afterPack = result.progress[0][packType].heroes;
  9328. for (let heroId in afterPack) {
  9329. const hero = afterPack[heroId];
  9330. const stateHp = beforePack[heroId]?.state?.hp || beforePack[heroId]?.stats?.hp;
  9331. const hp = hero.hp / stateHp;
  9332. const energy = hero.energy / 1e3;
  9333. const factor = hp + energy / 20;
  9334. afterSumFactor += factor;
  9335. }
  9336. const resultCoeff = -(afterSumFactor - beforeSumFactor);
  9337. return Math.round(resultCoeff * 1000) / 1000;
  9338. }
  9339. /**
  9340. * Start battle
  9341. *
  9342. * Начало боя
  9343. */
  9344. function startBattle() {
  9345. countBattle++;
  9346. const countMaxBattle = getInput('countAutoBattle');
  9347. // setProgress(countBattle + '/' + countMaxBattle);
  9348. if (countBattle > countMaxBattle) {
  9349. setProgress(`${I18N('RETRY_LIMIT_EXCEEDED')}: ${countMaxBattle}`, true);
  9350. endAutoBattle(`${I18N('RETRY_LIMIT_EXCEEDED')}: ${countMaxBattle}`)
  9351. return;
  9352. }
  9353. send({calls: [{
  9354. name: nameFuncStartBattle,
  9355. args: battleArg,
  9356. ident: "body"
  9357. }]}, calcResultBattle);
  9358. }
  9359. /**
  9360. * Battle calculation
  9361. *
  9362. * Расчет боя
  9363. */
  9364. async function calcResultBattle(e) {
  9365. if ('error' in e) {
  9366. if (e.error.description === 'too many tries') {
  9367. invasionTimer += 100;
  9368. countBattle--;
  9369. countError++;
  9370. console.log(`Errors: ${countError}`, e.error);
  9371. startBattle();
  9372. return;
  9373. }
  9374. const result = await popup.confirm(I18N('ERROR_DURING_THE_BATTLE') + '<br>' + e.error.description, [
  9375. { msg: I18N('BTN_OK'), result: false },
  9376. { msg: I18N('RELOAD_GAME'), result: true },
  9377. ]);
  9378. endAutoBattle('Error', e.error);
  9379. if (result) {
  9380. location.reload();
  9381. }
  9382. return;
  9383. }
  9384. let battle = e.results[0].result.response.battle
  9385. if (nameFuncStartBattle == 'towerStartBattle' ||
  9386. nameFuncStartBattle == 'bossAttack' ||
  9387. nameFuncStartBattle == 'invasion_bossStart') {
  9388. battle = e.results[0].result.response;
  9389. }
  9390. lastBattleInfo = battle;
  9391. BattleCalc(battle, getBattleType(battle.type), resultBattle);
  9392. }
  9393. /**
  9394. * Processing the results of the battle
  9395. *
  9396. * Обработка результатов боя
  9397. */
  9398. function resultBattle(e) {
  9399. const isWin = e.result.win;
  9400. if (isWin) {
  9401. endBattle(e, false);
  9402. return;
  9403. }
  9404. const countMaxBattle = getInput('countAutoBattle');
  9405. if (findCoeff) {
  9406. const coeff = calcCoeff(e, 'defenders');
  9407. setProgress(`${countBattle}/${countMaxBattle}, ${coeff}`);
  9408. if (coeff > findCoeff) {
  9409. endBattle(e, false);
  9410. return;
  9411. }
  9412. } else {
  9413. if (nameFuncStartBattle == 'invasion_bossStart') {
  9414. const bossLvl = lastBattleInfo.typeId >= 130 ? lastBattleInfo.typeId : '';
  9415. const justice = lastBattleInfo?.effects?.attackers?.percentInOutDamageMod_any_99_100_300_99_1000 || 0;
  9416. setProgress(`${svgBoss} ${bossLvl} ${svgJustice} ${justice} <br>${svgAttempt} ${countBattle}/${countMaxBattle}`);
  9417. } else {
  9418. setProgress(`${countBattle}/${countMaxBattle}`);
  9419. }
  9420. }
  9421. if (nameFuncStartBattle == 'towerStartBattle' ||
  9422. nameFuncStartBattle == 'bossAttack' ||
  9423. nameFuncStartBattle == 'invasion_bossStart') {
  9424. startBattle();
  9425. return;
  9426. }
  9427. cancelEndBattle(e);
  9428. }
  9429. /**
  9430. * Cancel fight
  9431. *
  9432. * Отмена боя
  9433. */
  9434. function cancelEndBattle(r) {
  9435. const fixBattle = function (heroes) {
  9436. for (const ids in heroes) {
  9437. hero = heroes[ids];
  9438. hero.energy = random(1, 999);
  9439. if (hero.hp > 0) {
  9440. hero.hp = random(1, hero.hp);
  9441. }
  9442. }
  9443. }
  9444. fixBattle(r.progress[0].attackers.heroes);
  9445. fixBattle(r.progress[0].defenders.heroes);
  9446. endBattle(r, true);
  9447. }
  9448. /**
  9449. * End of the fight
  9450. *
  9451. * Завершение боя */
  9452. function endBattle(battleResult, isCancal) {
  9453. let calls = [{
  9454. name: nameFuncEndBattle,
  9455. args: {
  9456. result: battleResult.result,
  9457. progress: battleResult.progress
  9458. },
  9459. ident: "body"
  9460. }];
  9461.  
  9462. if (nameFuncStartBattle == 'invasion_bossStart') {
  9463. calls[0].args.id = lastBattleArg.id;
  9464. }
  9465.  
  9466. send(JSON.stringify({
  9467. calls
  9468. }), async e => {
  9469. console.log(e);
  9470. if (isCancal) {
  9471. startBattle();
  9472. return;
  9473. }
  9474.  
  9475. setProgress(`${I18N('SUCCESS')}!`, 5000)
  9476. if (nameFuncStartBattle == 'invasion_bossStart' ||
  9477. nameFuncStartBattle == 'bossAttack') {
  9478. const countMaxBattle = getInput('countAutoBattle');
  9479. const bossLvl = lastBattleInfo.typeId >= 130 ? lastBattleInfo.typeId : '';
  9480. const justice = lastBattleInfo?.effects?.attackers?.percentInOutDamageMod_any_99_100_300_99_1000 || 0;
  9481. const result = await popup.confirm(
  9482. I18N('BOSS_HAS_BEEN_DEF_TEXT', {
  9483. bossLvl: `${svgBoss} ${bossLvl} ${svgJustice} ${justice}`,
  9484. countBattle: svgAttempt + ' ' + countBattle,
  9485. countMaxBattle,}),
  9486. [
  9487. { msg: I18N('BTN_OK'), result: 0 },
  9488. { msg: I18N('MAKE_A_SYNC'), result: 1 },
  9489. { msg: I18N('RELOAD_GAME'), result: 2 },
  9490. ]);
  9491. if (result) {
  9492. if (result == 1) {
  9493. cheats.refreshGame();
  9494. }
  9495. if (result == 2) {
  9496. location.reload();
  9497. }
  9498. }
  9499.  
  9500. }
  9501. endAutoBattle(`${I18N('SUCCESS')}!`)
  9502. });
  9503. }
  9504. /**
  9505. * Completing a task
  9506. *
  9507. * Завершение задачи
  9508. */
  9509. function endAutoBattle(reason, info) {
  9510. isCancalBattle = true;
  9511. console.log(reason, info);
  9512. resolve();
  9513. }
  9514. }
  9515.  
  9516. function testDailyQuests() {
  9517. return new Promise((resolve, reject) => {
  9518. const quests = new dailyQuests(resolve, reject);
  9519. quests.init(questsInfo);
  9520. quests.start();
  9521. });
  9522. }
  9523.  
  9524. /**
  9525. * Automatic completion of daily quests
  9526. *
  9527. * Автоматическое выполнение ежедневных квестов
  9528. */
  9529. class dailyQuests {
  9530. /**
  9531. * Send(' {"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}').then(e => console.log(e))
  9532. * Send(' {"calls":[{"name":"heroGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  9533. * Send(' {"calls":[{"name":"titanGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  9534. * Send(' {"calls":[{"name":"inventoryGet","args":{},"ident":"body"}]}').then(e => console.log(e))
  9535. * Send(' {"calls":[{"name":"questGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  9536. * Send(' {"calls":[{"name":"bossGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  9537. */
  9538. callsList = [
  9539. "userGetInfo",
  9540. "heroGetAll",
  9541. "titanGetAll",
  9542. "inventoryGet",
  9543. "questGetAll",
  9544. "bossGetAll",
  9545. ]
  9546.  
  9547. dataQuests = {
  9548. 10001: {
  9549. description: 'Улучши умения героев 3 раза', // ++++++++++++++++
  9550. doItCall: () => {
  9551. const upgradeSkills = this.getUpgradeSkills();
  9552. return upgradeSkills.map(({ heroId, skill }, index) => ({ name: "heroUpgradeSkill", args: { heroId, skill }, "ident": `heroUpgradeSkill_${index}` }));
  9553. },
  9554. isWeCanDo: () => {
  9555. const upgradeSkills = this.getUpgradeSkills();
  9556. let sumGold = 0;
  9557. for (const skill of upgradeSkills) {
  9558. sumGold += this.skillCost(skill.value);
  9559. if (!skill.heroId) {
  9560. return false;
  9561. }
  9562. }
  9563. return this.questInfo['userGetInfo'].gold > sumGold;
  9564. },
  9565. },
  9566. 10002: {
  9567. description: 'Пройди 10 миссий', // --------------
  9568. isWeCanDo: () => false,
  9569. },
  9570. 10003: {
  9571. description: 'Пройди 3 героические миссии', // --------------
  9572. isWeCanDo: () => false,
  9573. },
  9574. 10004: {
  9575. description: 'Сразись 3 раза на Арене или Гранд Арене', // --------------
  9576. isWeCanDo: () => false,
  9577. },
  9578. 10006: {
  9579. description: 'Используй обмен изумрудов 1 раз', // ++++++++++++++++
  9580. doItCall: () => [{
  9581. name: "refillableAlchemyUse",
  9582. args: { multi: false },
  9583. ident: "refillableAlchemyUse"
  9584. }],
  9585. isWeCanDo: () => {
  9586. const starMoney = this.questInfo['userGetInfo'].starMoney;
  9587. return starMoney >= 20;
  9588. },
  9589. },
  9590. 10007: {
  9591. description: 'Соверши 1 призыв в Атриуме Душ', // ++++++++++++++++
  9592. doItCall: () => [{ name: "gacha_open", args: { ident: "heroGacha", free: true, pack: false }, ident: "gacha_open" }],
  9593. isWeCanDo: () => {
  9594. const soulCrystal = this.questInfo['inventoryGet'].coin[38];
  9595. return soulCrystal > 0;
  9596. },
  9597. },
  9598. /*10016: {
  9599. description: 'Отправь подарки согильдийцам', // ++++++++++++++++
  9600. doItCall: () => [{ name: "clanSendDailyGifts", args: {}, ident: "clanSendDailyGifts" }],
  9601. isWeCanDo: () => true,
  9602. },*/
  9603. 10018: {
  9604. description: 'Используй зелье опыта', // ++++++++++++++++
  9605. doItCall: () => {
  9606. const expHero = this.getExpHero();
  9607. return [{
  9608. name: "consumableUseHeroXp",
  9609. args: {
  9610. heroId: expHero.heroId,
  9611. libId: expHero.libId,
  9612. amount: 1
  9613. },
  9614. ident: "consumableUseHeroXp"
  9615. }];
  9616. },
  9617. isWeCanDo: () => {
  9618. const expHero = this.getExpHero();
  9619. return expHero.heroId && expHero.libId;
  9620. },
  9621. },
  9622. 10019: {
  9623. description: 'Открой 1 сундук в Башне',
  9624. doItFunc: testTower,
  9625. isWeCanDo: () => false,
  9626. },
  9627. 10020: {
  9628. description: 'Открой 3 сундука в Запределье', // Готово
  9629. doItCall: () => {
  9630. return this.getOutlandChest();
  9631. },
  9632. isWeCanDo: () => {
  9633. const outlandChest = this.getOutlandChest();
  9634. return outlandChest.length > 0;
  9635. },
  9636. },
  9637. 10021: {
  9638. description: 'Собери 75 Титанита в Подземелье Гильдии',
  9639. isWeCanDo: () => false,
  9640. },
  9641. 10022: {
  9642. description: 'Собери 150 Титанита в Подземелье Гильдии',
  9643. doItFunc: testDungeon,
  9644. isWeCanDo: () => false,
  9645. },
  9646. 10023: {
  9647. description: 'Прокачай Дар Стихий на 1 уровень', // Готово
  9648. doItCall: () => {
  9649. const heroId = this.getHeroIdTitanGift();
  9650. return [
  9651. { name: "heroTitanGiftLevelUp", args: { heroId }, ident: "heroTitanGiftLevelUp" },
  9652. { name: "heroTitanGiftDrop", args: { heroId }, ident: "heroTitanGiftDrop" }
  9653. ]
  9654. },
  9655. isWeCanDo: () => {
  9656. const heroId = this.getHeroIdTitanGift();
  9657. return heroId;
  9658. },
  9659. },
  9660. 10024: {
  9661. description: 'Повысь уровень любого артефакта один раз', // Готово
  9662. doItCall: () => {
  9663. const upArtifact = this.getUpgradeArtifact();
  9664. return [
  9665. {
  9666. name: "heroArtifactLevelUp",
  9667. args: {
  9668. heroId: upArtifact.heroId,
  9669. slotId: upArtifact.slotId
  9670. },
  9671. ident: `heroArtifactLevelUp`
  9672. }
  9673. ];
  9674. },
  9675. isWeCanDo: () => {
  9676. const upgradeArtifact = this.getUpgradeArtifact();
  9677. return upgradeArtifact.heroId;
  9678. },
  9679. },
  9680. 10025: {
  9681. description: 'Начни 1 Экспедицию',
  9682. doItFunc: checkExpedition,
  9683. isWeCanDo: () => false,
  9684. },
  9685. 10026: {
  9686. description: 'Начни 4 Экспедиции', // --------------
  9687. doItFunc: checkExpedition,
  9688. isWeCanDo: () => false,
  9689. },
  9690. 10027: {
  9691. description: 'Победи в 1 бою Турнира Стихий',
  9692. doItFunc: testTitanArena,
  9693. isWeCanDo: () => false,
  9694. },
  9695. 10028: {
  9696. description: 'Повысь уровень любого артефакта титанов', // Готово
  9697. doItCall: () => {
  9698. const upTitanArtifact = this.getUpgradeTitanArtifact();
  9699. return [
  9700. {
  9701. name: "titanArtifactLevelUp",
  9702. args: {
  9703. titanId: upTitanArtifact.titanId,
  9704. slotId: upTitanArtifact.slotId
  9705. },
  9706. ident: `titanArtifactLevelUp`
  9707. }
  9708. ];
  9709. },
  9710. isWeCanDo: () => {
  9711. const upgradeTitanArtifact = this.getUpgradeTitanArtifact();
  9712. return upgradeTitanArtifact.titanId;
  9713. },
  9714. },
  9715. 10029: {
  9716. description: 'Открой сферу артефактов титанов', // ++++++++++++++++
  9717. doItCall: () => [{ name: "titanArtifactChestOpen", args: { amount: 1, free: true }, ident: "titanArtifactChestOpen" }],
  9718. isWeCanDo: () => {
  9719. return this.questInfo['inventoryGet']?.consumable[55] > 0
  9720. },
  9721. },
  9722. 10030: {
  9723. description: 'Улучши облик любого героя 1 раз', // Готово
  9724. doItCall: () => {
  9725. const upSkin = this.getUpgradeSkin();
  9726. return [
  9727. {
  9728. name: "heroSkinUpgrade",
  9729. args: {
  9730. heroId: upSkin.heroId,
  9731. skinId: upSkin.skinId
  9732. },
  9733. ident: `heroSkinUpgrade`
  9734. }
  9735. ];
  9736. },
  9737. isWeCanDo: () => {
  9738. const upgradeSkin = this.getUpgradeSkin();
  9739. return upgradeSkin.heroId;
  9740. },
  9741. },
  9742. 10031: {
  9743. description: 'Победи в 6 боях Турнира Стихий', // --------------
  9744. doItFunc: testTitanArena,
  9745. isWeCanDo: () => false,
  9746. },
  9747. 10043: {
  9748. description: 'Начни или присоеденись к Приключению', // --------------
  9749. isWeCanDo: () => false,
  9750. },
  9751. 10044: {
  9752. description: 'Воспользуйся призывом питомцев 1 раз', // ++++++++++++++++
  9753. doItCall: () => [{ name: "pet_chestOpen", args: { amount: 1, paid: false }, ident: "pet_chestOpen" }],
  9754. isWeCanDo: () => {
  9755. return this.questInfo['inventoryGet']?.consumable[90] > 0
  9756. },
  9757. },
  9758. 10046: {
  9759. /**
  9760. * TODO: Watch Adventure
  9761. * TODO: Смотреть приключение
  9762. */
  9763. description: 'Открой 3 сундука в Приключениях',
  9764. isWeCanDo: () => false,
  9765. },
  9766. 10047: {
  9767. description: 'Набери 150 очков активности в Гильдии', // Готово
  9768. doItCall: () => {
  9769. const enchantRune = this.getEnchantRune();
  9770. return [
  9771. {
  9772. name: "heroEnchantRune",
  9773. args: {
  9774. heroId: enchantRune.heroId,
  9775. tier: enchantRune.tier,
  9776. items: {
  9777. consumable: { [enchantRune.itemId]: 1 }
  9778. }
  9779. },
  9780. ident: `heroEnchantRune`
  9781. }
  9782. ];
  9783. },
  9784. isWeCanDo: () => {
  9785. const userInfo = this.questInfo['userGetInfo'];
  9786. const enchantRune = this.getEnchantRune();
  9787. return enchantRune.heroId && userInfo.gold > 1e3;
  9788. },
  9789. },
  9790. };
  9791.  
  9792. constructor(resolve, reject, questInfo) {
  9793. this.resolve = resolve;
  9794. this.reject = reject;
  9795. }
  9796.  
  9797. init(questInfo) {
  9798. this.questInfo = questInfo;
  9799. this.isAuto = false;
  9800. }
  9801.  
  9802. async autoInit(isAuto) {
  9803. this.isAuto = isAuto || false;
  9804. const quests = {};
  9805. const calls = this.callsList.map(name => ({
  9806. name, args: {}, ident: name
  9807. }))
  9808. const result = await Send(JSON.stringify({ calls })).then(e => e.results);
  9809. for (const call of result) {
  9810. quests[call.ident] = call.result.response;
  9811. }
  9812. this.questInfo = quests;
  9813. }
  9814.  
  9815. async start() {
  9816. const weCanDo = [];
  9817. const selectedActions = getSaveVal('selectedActions', {});
  9818. for (let quest of this.questInfo['questGetAll']) {
  9819. if (quest.id in this.dataQuests && quest.state == 1) {
  9820. if (!selectedActions[quest.id]) {
  9821. selectedActions[quest.id] = {
  9822. checked: false
  9823. }
  9824. }
  9825.  
  9826. const isWeCanDo = this.dataQuests[quest.id].isWeCanDo;
  9827. if (!isWeCanDo.call(this)) {
  9828. continue;
  9829. }
  9830.  
  9831. weCanDo.push({
  9832. name: quest.id,
  9833. label: I18N(`QUEST_${quest.id}`),
  9834. checked: selectedActions[quest.id].checked
  9835. });
  9836. }
  9837. }
  9838.  
  9839. if (!weCanDo.length) {
  9840. this.end(I18N('NOTHING_TO_DO'));
  9841. return;
  9842. }
  9843.  
  9844. console.log(weCanDo);
  9845. let taskList = [];
  9846. if (this.isAuto) {
  9847. taskList = weCanDo;
  9848. } else {
  9849. const answer = await popup.confirm(`${I18N('YOU_CAN_COMPLETE') }:`, [
  9850. { msg: I18N('BTN_DO_IT'), result: true },
  9851. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  9852. ], weCanDo);
  9853. if (!answer) {
  9854. this.end('');
  9855. return;
  9856. }
  9857. taskList = popup.getCheckBoxes();
  9858. taskList.forEach(e => {
  9859. selectedActions[e.name].checked = e.checked;
  9860. });
  9861. setSaveVal('selectedActions', selectedActions);
  9862. }
  9863.  
  9864. const calls = [];
  9865. let countChecked = 0;
  9866. for (const task of taskList) {
  9867. if (task.checked) {
  9868. countChecked++;
  9869. const quest = this.dataQuests[task.name]
  9870. console.log(quest.description);
  9871.  
  9872. if (quest.doItCall) {
  9873. const doItCall = quest.doItCall.call(this);
  9874. calls.push(...doItCall);
  9875. }
  9876. }
  9877. }
  9878.  
  9879. if (!countChecked) {
  9880. this.end(I18N('NOT_QUEST_COMPLETED'));
  9881. return;
  9882. }
  9883.  
  9884. const result = await Send(JSON.stringify({ calls }));
  9885. if (result.error) {
  9886. console.error(result.error, result.error.call)
  9887. }
  9888. this.end(`${I18N('COMPLETED_QUESTS')}: ${countChecked}`);
  9889. }
  9890.  
  9891. errorHandling(error) {
  9892. //console.error(error);
  9893. let errorInfo = error.toString() + '\n';
  9894. try {
  9895. const errorStack = error.stack.split('\n');
  9896. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testDoYourBest");
  9897. errorInfo += errorStack.slice(0, endStack).join('\n');
  9898. } catch (e) {
  9899. errorInfo += error.stack;
  9900. }
  9901. copyText(errorInfo);
  9902. }
  9903.  
  9904. skillCost(lvl) {
  9905. return 573 * lvl ** 0.9 + lvl ** 2.379;
  9906. }
  9907.  
  9908. getUpgradeSkills() {
  9909. const heroes = Object.values(this.questInfo['heroGetAll']);
  9910. const upgradeSkills = [
  9911. { heroId: 0, slotId: 0, value: 130 },
  9912. { heroId: 0, slotId: 0, value: 130 },
  9913. { heroId: 0, slotId: 0, value: 130 },
  9914. ];
  9915. const skillLib = lib.getData('skill');
  9916. /**
  9917. * color - 1 (белый) открывает 1 навык
  9918. * color - 2 (зеленый) открывает 2 навык
  9919. * color - 4 (синий) открывает 3 навык
  9920. * color - 7 (фиолетовый) открывает 4 навык
  9921. */
  9922. const colors = [1, 2, 4, 7];
  9923. for (const hero of heroes) {
  9924. const level = hero.level;
  9925. const color = hero.color;
  9926. for (let skillId in hero.skills) {
  9927. const tier = skillLib[skillId].tier;
  9928. const sVal = hero.skills[skillId];
  9929. if (color < colors[tier] || tier < 1 || tier > 4) {
  9930. continue;
  9931. }
  9932. for (let upSkill of upgradeSkills) {
  9933. if (sVal < upSkill.value && sVal < level) {
  9934. upSkill.value = sVal;
  9935. upSkill.heroId = hero.id;
  9936. upSkill.skill = tier;
  9937. break;
  9938. }
  9939. }
  9940. }
  9941. }
  9942. return upgradeSkills;
  9943. }
  9944.  
  9945. getUpgradeArtifact() {
  9946. const heroes = Object.values(this.questInfo['heroGetAll']);
  9947. const inventory = this.questInfo['inventoryGet'];
  9948. const upArt = { heroId: 0, slotId: 0, level: 100 };
  9949.  
  9950. const heroLib = lib.getData('hero');
  9951. const artifactLib = lib.getData('artifact');
  9952.  
  9953. for (const hero of heroes) {
  9954. const heroInfo = heroLib[hero.id];
  9955. const level = hero.level
  9956. if (level < 20) {
  9957. continue;
  9958. }
  9959.  
  9960. for (let slotId in hero.artifacts) {
  9961. const art = hero.artifacts[slotId];
  9962. /* Текущая звезданость арта */
  9963. const star = art.star;
  9964. if (!star) {
  9965. continue;
  9966. }
  9967. /* Текущий уровень арта */
  9968. const level = art.level;
  9969. if (level >= 100) {
  9970. continue;
  9971. }
  9972. /* Идентификатор арта в библиотеке */
  9973. const artifactId = heroInfo.artifacts[slotId];
  9974. const artInfo = artifactLib.id[artifactId];
  9975. const costNextLevel = artifactLib.type[artInfo.type].levels[level + 1].cost;
  9976.  
  9977. const costСurrency = Object.keys(costNextLevel).pop();
  9978. const costValues = Object.entries(costNextLevel[costСurrency]).pop();
  9979. const costId = costValues[0];
  9980. const costValue = +costValues[1];
  9981.  
  9982. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  9983. if (level < upArt.level && inventory[costСurrency][costId] >= costValue) {
  9984. upArt.level = level;
  9985. upArt.heroId = hero.id;
  9986. upArt.slotId = slotId;
  9987. upArt.costСurrency = costСurrency;
  9988. upArt.costId = costId;
  9989. upArt.costValue = costValue;
  9990. }
  9991. }
  9992. }
  9993. return upArt;
  9994. }
  9995.  
  9996. getUpgradeSkin() {
  9997. const heroes = Object.values(this.questInfo['heroGetAll']);
  9998. const inventory = this.questInfo['inventoryGet'];
  9999. const upSkin = { heroId: 0, skinId: 0, level: 60, cost: 1500 };
  10000.  
  10001. const skinLib = lib.getData('skin');
  10002.  
  10003. for (const hero of heroes) {
  10004. const level = hero.level
  10005. if (level < 20) {
  10006. continue;
  10007. }
  10008.  
  10009. for (let skinId in hero.skins) {
  10010. /* Текущий уровень скина */
  10011. const level = hero.skins[skinId];
  10012. if (level >= 60) {
  10013. continue;
  10014. }
  10015. /* Идентификатор скина в библиотеке */
  10016. const skinInfo = skinLib[skinId];
  10017. if (!skinInfo.statData.levels?.[level + 1]) {
  10018. continue;
  10019. }
  10020. const costNextLevel = skinInfo.statData.levels[level + 1].cost;
  10021.  
  10022. const costСurrency = Object.keys(costNextLevel).pop();
  10023. const costСurrencyId = Object.keys(costNextLevel[costСurrency]).pop();
  10024. const costValue = +costNextLevel[costСurrency][costСurrencyId];
  10025.  
  10026. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  10027. if (level < upSkin.level &&
  10028. costValue < upSkin.cost &&
  10029. inventory[costСurrency][costСurrencyId] >= costValue) {
  10030. upSkin.cost = costValue;
  10031. upSkin.level = level;
  10032. upSkin.heroId = hero.id;
  10033. upSkin.skinId = skinId;
  10034. upSkin.costСurrency = costСurrency;
  10035. upSkin.costСurrencyId = costСurrencyId;
  10036. }
  10037. }
  10038. }
  10039. return upSkin;
  10040. }
  10041.  
  10042. getUpgradeTitanArtifact() {
  10043. const titans = Object.values(this.questInfo['titanGetAll']);
  10044. const inventory = this.questInfo['inventoryGet'];
  10045. const userInfo = this.questInfo['userGetInfo'];
  10046. const upArt = { titanId: 0, slotId: 0, level: 120 };
  10047.  
  10048. const titanLib = lib.getData('titan');
  10049. const artTitanLib = lib.getData('titanArtifact');
  10050.  
  10051. for (const titan of titans) {
  10052. const titanInfo = titanLib[titan.id];
  10053. // const level = titan.level
  10054. // if (level < 20) {
  10055. // continue;
  10056. // }
  10057.  
  10058. for (let slotId in titan.artifacts) {
  10059. const art = titan.artifacts[slotId];
  10060. /* Текущая звезданость арта */
  10061. const star = art.star;
  10062. if (!star) {
  10063. continue;
  10064. }
  10065. /* Текущий уровень арта */
  10066. const level = art.level;
  10067. if (level >= 120) {
  10068. continue;
  10069. }
  10070. /* Идентификатор арта в библиотеке */
  10071. const artifactId = titanInfo.artifacts[slotId];
  10072. const artInfo = artTitanLib.id[artifactId];
  10073. const costNextLevel = artTitanLib.type[artInfo.type].levels[level + 1].cost;
  10074.  
  10075. const costСurrency = Object.keys(costNextLevel).pop();
  10076. let costValue = 0;
  10077. let currentValue = 0;
  10078. if (costСurrency == 'gold') {
  10079. costValue = costNextLevel[costСurrency];
  10080. currentValue = userInfo.gold;
  10081. } else {
  10082. const costValues = Object.entries(costNextLevel[costСurrency]).pop();
  10083. const costId = costValues[0];
  10084. costValue = +costValues[1];
  10085. currentValue = inventory[costСurrency][costId];
  10086. }
  10087.  
  10088. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  10089. if (level < upArt.level && currentValue >= costValue) {
  10090. upArt.level = level;
  10091. upArt.titanId = titan.id;
  10092. upArt.slotId = slotId;
  10093. break;
  10094. }
  10095. }
  10096. }
  10097. return upArt;
  10098. }
  10099.  
  10100. getEnchantRune() {
  10101. const heroes = Object.values(this.questInfo['heroGetAll']);
  10102. const inventory = this.questInfo['inventoryGet'];
  10103. const enchRune = { heroId: 0, tier: 0, exp: 43750, itemId: 0 };
  10104. for (let i = 1; i <= 4; i++) {
  10105. if (inventory.consumable[i] > 0) {
  10106. enchRune.itemId = i;
  10107. break;
  10108. }
  10109. return enchRune;
  10110. }
  10111.  
  10112. const runeLib = lib.getData('rune');
  10113. const runeLvls = Object.values(runeLib.level);
  10114. /**
  10115. * color - 4 (синий) открывает 1 и 2 символ
  10116. * color - 7 (фиолетовый) открывает 3 символ
  10117. * color - 8 (фиолетовый +1) открывает 4 символ
  10118. * color - 9 (фиолетовый +2) открывает 5 символ
  10119. */
  10120. // TODO: кажется надо учесть уровень команды
  10121. const colors = [4, 4, 7, 8, 9];
  10122. for (const hero of heroes) {
  10123. const color = hero.color;
  10124.  
  10125.  
  10126. for (let runeTier in hero.runes) {
  10127. /* Проверка на доступность руны */
  10128. if (color < colors[runeTier]) {
  10129. continue;
  10130. }
  10131. /* Текущий опыт руны */
  10132. const exp = hero.runes[runeTier];
  10133. if (exp >= 43750) {
  10134. continue;
  10135. }
  10136.  
  10137. let level = 0;
  10138. if (exp) {
  10139. for (let lvl of runeLvls) {
  10140. if (exp >= lvl.enchantValue) {
  10141. level = lvl.level;
  10142. } else {
  10143. break;
  10144. }
  10145. }
  10146. }
  10147. /** Уровень героя необходимый для уровня руны */
  10148. const heroLevel = runeLib.level[level].heroLevel;
  10149. if (hero.level < heroLevel) {
  10150. continue;
  10151. }
  10152.  
  10153. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  10154. if (exp < enchRune.exp) {
  10155. enchRune.exp = exp;
  10156. enchRune.heroId = hero.id;
  10157. enchRune.tier = runeTier;
  10158. break;
  10159. }
  10160. }
  10161. }
  10162. return enchRune;
  10163. }
  10164.  
  10165. getOutlandChest() {
  10166. const bosses = this.questInfo['bossGetAll'];
  10167.  
  10168. const calls = [];
  10169.  
  10170. for (let boss of bosses) {
  10171. if (boss.mayRaid) {
  10172. calls.push({
  10173. name: "bossRaid",
  10174. args: {
  10175. bossId: boss.id
  10176. },
  10177. ident: "bossRaid_" + boss.id
  10178. });
  10179. calls.push({
  10180. name: "bossOpenChest",
  10181. args: {
  10182. bossId: boss.id,
  10183. amount: 1,
  10184. starmoney: 0
  10185. },
  10186. ident: "bossOpenChest_" + boss.id
  10187. });
  10188. } else if (boss.chestId == 1) {
  10189. calls.push({
  10190. name: "bossOpenChest",
  10191. args: {
  10192. bossId: boss.id,
  10193. amount: 1,
  10194. starmoney: 0
  10195. },
  10196. ident: "bossOpenChest_" + boss.id
  10197. });
  10198. }
  10199. }
  10200.  
  10201. return calls;
  10202. }
  10203.  
  10204. getExpHero() {
  10205. const heroes = Object.values(this.questInfo['heroGetAll']);
  10206. const inventory = this.questInfo['inventoryGet'];
  10207. const expHero = { heroId: 0, exp: 3625195, libId: 0 };
  10208. /** зелья опыта (consumable 9, 10, 11, 12) */
  10209. for (let i = 9; i <= 12; i++) {
  10210. if (inventory.consumable[i]) {
  10211. expHero.libId = i;
  10212. break;
  10213. }
  10214. }
  10215.  
  10216. for (const hero of heroes) {
  10217. const exp = hero.xp;
  10218. if (exp < expHero.exp) {
  10219. expHero.heroId = hero.id;
  10220. }
  10221. }
  10222. return expHero;
  10223. }
  10224.  
  10225. getHeroIdTitanGift() {
  10226. const heroes = Object.values(this.questInfo['heroGetAll']);
  10227. const inventory = this.questInfo['inventoryGet'];
  10228. const user = this.questInfo['userGetInfo'];
  10229. const titanGiftLib = lib.getData('titanGift');
  10230. /** Искры */
  10231. const titanGift = inventory.consumable[24];
  10232. let heroId = 0;
  10233. let minLevel = 30;
  10234.  
  10235. if (titanGift < 250 || user.gold < 7000) {
  10236. return 0;
  10237. }
  10238.  
  10239. for (const hero of heroes) {
  10240. if (hero.titanGiftLevel >= 30) {
  10241. continue;
  10242. }
  10243.  
  10244. if (!hero.titanGiftLevel) {
  10245. return hero.id;
  10246. }
  10247.  
  10248. const cost = titanGiftLib[hero.titanGiftLevel].cost;
  10249. if (minLevel > hero.titanGiftLevel &&
  10250. titanGift >= cost.consumable[24] &&
  10251. user.gold >= cost.gold
  10252. ) {
  10253. minLevel = hero.titanGiftLevel;
  10254. heroId = hero.id;
  10255. }
  10256. }
  10257.  
  10258. return heroId;
  10259. }
  10260.  
  10261. end(status) {
  10262. setProgress(status, true);
  10263. this.resolve();
  10264. }
  10265. }
  10266.  
  10267. this.questRun = dailyQuests;
  10268.  
  10269. function testDoYourBest() {
  10270. return new Promise((resolve, reject) => {
  10271. const doIt = new doYourBest(resolve, reject);
  10272. doIt.start();
  10273. });
  10274. }
  10275.  
  10276. /**
  10277. * Do everything button
  10278. *
  10279. * Кнопка сделать все
  10280. */
  10281. class doYourBest {
  10282.  
  10283. funcList = [
  10284. //собрать запределье
  10285. {
  10286. name: 'getOutland',
  10287. label: I18N('ASSEMBLE_OUTLAND'),
  10288. checked: false
  10289. },
  10290. //пройти башню
  10291. {
  10292. name: 'testTower',
  10293. label: I18N('PASS_THE_TOWER'),
  10294. checked: false
  10295. },
  10296. //экспедиции
  10297. {
  10298. name: 'checkExpedition',
  10299. label: I18N('CHECK_EXPEDITIONS'),
  10300. checked: false
  10301. },
  10302. //турнир стихий
  10303. {
  10304. name: 'testTitanArena',
  10305. label: I18N('COMPLETE_TOE'),
  10306. checked: false
  10307. },
  10308. //собрать почту
  10309. {
  10310. name: 'mailGetAll',
  10311. label: I18N('COLLECT_MAIL'),
  10312. checked: false
  10313. },
  10314. //Собрать всякую херню
  10315. {
  10316. name: 'collectAllStuff',
  10317. label: I18N('COLLECT_MISC'),
  10318. title: I18N('COLLECT_MISC_TITLE'),
  10319. checked: false
  10320. },
  10321. //ежедневная награда
  10322. {
  10323. name: 'getDailyBonus',
  10324. label: I18N('DAILY_BONUS'),
  10325. checked: false
  10326. },
  10327. //ежедневные квесты удалить наверно есть в настройках
  10328. {
  10329. name: 'dailyQuests',
  10330. label: I18N('DO_DAILY_QUESTS'),
  10331. checked: false
  10332. },
  10333. //Провидец
  10334. {
  10335. name: 'rollAscension',
  10336. label: I18N('SEER_TITLE'),
  10337. checked: false
  10338. },
  10339. //собрать награды за квесты
  10340. {
  10341. name: 'questAllFarm',
  10342. label: I18N('COLLECT_QUEST_REWARDS'),
  10343. checked: false
  10344. },
  10345. // тест отправь подарки согильдийцам
  10346. {
  10347. name: 'testclanSendDailyGifts',
  10348. label: I18N('QUEST_10016'),
  10349. checked: false
  10350. },
  10351. //собрать новогодние подарки
  10352. /*{
  10353. name: 'getGiftNewYear',
  10354. label: I18N('NY_GIFTS'),
  10355. checked: false
  10356. },*/
  10357. // тест сферу титанов
  10358. /*{
  10359. name: 'testtitanArtifactChestOpen',
  10360. label: I18N('QUEST_10029'),
  10361. checked: false
  10362. },
  10363. // тест призыв петов
  10364. {
  10365. name: 'testpet_chestOpen',
  10366. label: I18N('QUEST_10044'),
  10367. checked: false
  10368. },*/
  10369. //пройти подземелье обычное
  10370. {
  10371. name: 'testDungeon',
  10372. label: I18N('COMPLETE_DUNGEON'),
  10373. checked: false
  10374. },
  10375. //пройти подземелье для фуловых титанов
  10376. {
  10377. name: 'DungeonFull',
  10378. label: I18N('COMPLETE_DUNGEON_FULL'),
  10379. checked: false
  10380. },
  10381. //синхронизация
  10382. {
  10383. name: 'synchronization',
  10384. label: I18N('MAKE_A_SYNC'),
  10385. checked: false
  10386. },
  10387. //перезагрузка
  10388. {
  10389. name: 'reloadGame',
  10390. label: I18N('RELOAD_GAME'),
  10391. checked: false
  10392. },
  10393. ];
  10394.  
  10395. functions = {
  10396. getOutland,//собрать запределье
  10397. testTower,//прохождение башни
  10398. checkExpedition,//автоэкспедиции
  10399. testTitanArena,//Автопрохождение Турнира Стихий
  10400. mailGetAll,//Собрать всю почту, кроме писем с энергией и зарядами портала
  10401. //Собрать пасхалки, камни облика, ключи, монеты арены и Хрусталь души
  10402. collectAllStuff: async () => {
  10403. await offerFarmAllReward();
  10404. 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"}]}');
  10405. },
  10406. //Выполнять ежедневные квесты
  10407. dailyQuests: async function () {
  10408. const quests = new dailyQuests(() => { }, () => { });
  10409. await quests.autoInit(true);
  10410. await quests.start();
  10411. },
  10412. rollAscension,//провидец
  10413. getDailyBonus,//ежедневная награда
  10414. questAllFarm,//Собрать все награды за задания
  10415. testclanSendDailyGifts, //отправить подарки
  10416. getGiftNewYear,//собрать новогодние подарки
  10417. testtitanArtifactChestOpen, //открой сферу титанов
  10418. testpet_chestOpen, //Воспользуйся призывом питомцев 1 раз
  10419. testDungeon,//подземка обычная
  10420. DungeonFull,//подземка для фуловых титанов
  10421. synchronization: async () => {
  10422. cheats.refreshGame();
  10423. },
  10424. reloadGame: async () => {
  10425. location.reload();
  10426. },
  10427. }
  10428.  
  10429. constructor(resolve, reject, questInfo) {
  10430. this.resolve = resolve;
  10431. this.reject = reject;
  10432. this.questInfo = questInfo
  10433. }
  10434.  
  10435. async start() {
  10436. const selectedDoIt = getSaveVal('selectedDoIt', {});
  10437.  
  10438. this.funcList.forEach(task => {
  10439. if (!selectedDoIt[task.name]) {
  10440. selectedDoIt[task.name] = {
  10441. checked: task.checked
  10442. }
  10443. } else {
  10444. task.checked = selectedDoIt[task.name].checked
  10445. }
  10446. });
  10447.  
  10448. const answer = await popup.confirm(I18N('RUN_FUNCTION'), [
  10449. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  10450. { msg: I18N('BTN_GO'), result: true },
  10451. ], this.funcList);
  10452.  
  10453. if (!answer) {
  10454. this.end('');
  10455. return;
  10456. }
  10457.  
  10458. const taskList = popup.getCheckBoxes();
  10459. taskList.forEach(task => {
  10460. selectedDoIt[task.name].checked = task.checked;
  10461. });
  10462. setSaveVal('selectedDoIt', selectedDoIt);
  10463. for (const task of popup.getCheckBoxes()) {
  10464. if (task.checked) {
  10465. try {
  10466. setProgress(`${task.label} <br>${I18N('PERFORMED')}!`);
  10467. await this.functions[task.name]();
  10468. setProgress(`${task.label} <br>${I18N('DONE')}!`);
  10469. } catch (error) {
  10470. if (await popup.confirm(`${I18N('ERRORS_OCCURRES')}:<br> ${task.label} <br>${I18N('COPY_ERROR')}?`, [
  10471. { msg: I18N('BTN_NO'), result: false },
  10472. { msg: I18N('BTN_YES'), result: true },
  10473. ])) {
  10474. this.errorHandling(error);
  10475. }
  10476. }
  10477. }
  10478. }
  10479. setTimeout((msg) => {
  10480. this.end(msg);
  10481. }, 2000, I18N('ALL_TASK_COMPLETED'));
  10482. return;
  10483. }
  10484.  
  10485. errorHandling(error) {
  10486. //console.error(error);
  10487. let errorInfo = error.toString() + '\n';
  10488. try {
  10489. const errorStack = error.stack.split('\n');
  10490. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testDoYourBest");
  10491. errorInfo += errorStack.slice(0, endStack).join('\n');
  10492. } catch (e) {
  10493. errorInfo += error.stack;
  10494. }
  10495. copyText(errorInfo);
  10496. }
  10497.  
  10498. end(status) {
  10499. setProgress(status, true);
  10500. this.resolve();
  10501. }
  10502. }
  10503.  
  10504. /**
  10505. * Passing the adventure along the specified route
  10506. *
  10507. * Прохождение приключения по указанному маршруту
  10508. */
  10509. function testAdventure(type) {
  10510. return new Promise((resolve, reject) => {
  10511. const bossBattle = new executeAdventure(resolve, reject);
  10512. bossBattle.start(type);
  10513. });
  10514. }
  10515.  
  10516. //Буря
  10517. function testAdventure2(solo) {
  10518. return new Promise((resolve, reject) => {
  10519. const bossBattle = new executeAdventure2(resolve, reject);
  10520. bossBattle.start(solo);
  10521. });
  10522. }
  10523.  
  10524. /**
  10525. * Passing the adventure along the specified route
  10526. *
  10527. * Прохождение приключения по указанному маршруту
  10528. */
  10529. class executeAdventure {
  10530.  
  10531. type = 'default';
  10532.  
  10533. actions = {
  10534. default: {
  10535. getInfo: "adventure_getInfo",
  10536. startBattle: 'adventure_turnStartBattle',
  10537. endBattle: 'adventure_endBattle',
  10538. collectBuff: 'adventure_turnCollectBuff'
  10539. },
  10540. solo: {
  10541. getInfo: "adventureSolo_getInfo",
  10542. startBattle: 'adventureSolo_turnStartBattle',
  10543. endBattle: 'adventureSolo_endBattle',
  10544. collectBuff: 'adventureSolo_turnCollectBuff'
  10545. }
  10546. }
  10547.  
  10548. terminatеReason = I18N('UNKNOWN');
  10549. callAdventureInfo = {
  10550. name: "adventure_getInfo",
  10551. args: {},
  10552. ident: "adventure_getInfo"
  10553. }
  10554. callTeamGetAll = {
  10555. name: "teamGetAll",
  10556. args: {},
  10557. ident: "teamGetAll"
  10558. }
  10559. callTeamGetFavor = {
  10560. name: "teamGetFavor",
  10561. args: {},
  10562. ident: "teamGetFavor"
  10563. }
  10564. //тест прикла
  10565. defaultWays = {
  10566. //Галахад, 1-я
  10567. "adv_strongford_2pl_easy": {
  10568. first: '1,2,3,5,6',
  10569. second: '1,2,4,7,6',
  10570. third: '1,2,3,5,6'
  10571. },
  10572. //Джинджер, 2-я
  10573. "adv_valley_3pl_easy": {
  10574. first: '1,2,5,8,9,11',
  10575. second: '1,3,6,9,11',
  10576. third: '1,4,7,10,9,11'
  10577. },
  10578. //Орион, 3-я
  10579. "adv_ghirwil_3pl_easy": {
  10580. first: '1,5,6,9,11',
  10581. second: '1,4,12,13,11',
  10582. third: '1,2,3,7,10,11'
  10583. },
  10584. //Тесак, 4-я
  10585. "adv_angels_3pl_easy_fire": {
  10586. first: '1,2,4,7,18,8,12,19,22,23',
  10587. second: '1,3,6,11,17,10,16,21,22,23',
  10588. third: '1,5,24,25,9,14,15,20,22,23'
  10589. },
  10590. //Галахад, 5-я
  10591. "adv_strongford_3pl_normal_2": {
  10592. first: '1,2,7,8,12,16,23,26,25,21,24',
  10593. second: '1,4,6,10,11,15,22,15,19,18,24',
  10594. third: '1,5,9,10,14,17,20,27,25,21,24'
  10595. },
  10596. //Джинджер, 6-я
  10597. "adv_valley_3pl_normal": {
  10598. first: '1,2,4,7,10,13,16,19,24,22,25',
  10599. second: '1,3,6,9,12,15,18,21,26,23,25',
  10600. third: '1,5,7,8,11,14,17,20,22,25'
  10601. },
  10602. //Орион, 7-я
  10603. "adv_ghirwil_3pl_normal_2": {
  10604. first: '1,11,10,11,12,15,12,11,21,25,27',
  10605. second: '1,7,3,4,3,6,13,19,20,24,27',
  10606. third: '1,8,5,9,16,23,22,26,27'
  10607. },
  10608. //Тесак, 8-я
  10609. "adv_angels_3pl_normal": {
  10610. first: '1,3,4,8,7,9,10,13,17,16,20,22,23,31,32',
  10611. second: '1,3,5,7,8,11,14,18,20,22,24,27,30,26,32',
  10612. third: '1,3,2,6,7,9,11,15,19,20,22,21,28,29,25'
  10613. },
  10614. //Галахад, 9-я
  10615. "adv_strongford_3pl_hard_2": {
  10616. first: '1,2,6,10,15,7,16,17,23,22,27,32,35,37,40,45',
  10617. second: '1,3,8,12,11,18,19,28,34,33,38,41,43,46,45',
  10618. third: '1,2,5,9,14,20,26,21,30,36,39,42,44,45'
  10619. },
  10620. //Джинджер, 10-я
  10621. "adv_valley_3pl_hard": {
  10622. first: '1,3,2,6,11,17,25,30,35,34,29,24,21,17,12,7',
  10623. second: '1,4,8,13,18,22,26,31,36,40,45,44,43,38,33,28',
  10624. third: '1,5,9,14,19,23,27,32,37,42,48,51,50,49,46,52'
  10625. },
  10626. //Орион, 11-я
  10627. "adv_ghirwil_3pl_hard": {
  10628. first: '1,2,3,6,8,12,11,15,21,27,36,34,33,35,37',
  10629. second: '1,2,4,6,9,13,18,17,16,22,28,29,30,31,25,19',
  10630. third: '1,2,5,6,10,13,14,20,26,32,38,41,40,39,37'
  10631. },
  10632. //Тесак, 12-я
  10633. "adv_angels_3pl_hard": {
  10634. first: '1,2,8,11,7,4,7,16,23,32,33,25,34,29,35,36',
  10635. second: '1,3,9,13,10,6,10,22,31,30,21,30,15,28,20,27',
  10636. third: '1,5,12,14,24,17,24,25,26,18,19,20,27'
  10637. },
  10638. //Тесак, 13-я
  10639. "adv_angels_3pl_hell": {
  10640. first: '1,2,4,6,16,23,33,34,25,32,29,28,20,27',
  10641. second: '1,7,11,17,24,14,26,18,19,20,27,20,12,8',
  10642. third: '1,9,3,5,10,22,31,36,31,30,15,28,29,30,21,13'
  10643. },
  10644. //Галахад, 13-я
  10645. "adv_strongford_3pl_hell": {
  10646. first: '1,2,5,11,14,20,26,21,30,35,38,41,43,44',
  10647. second: '1,2,6,12,15,7,16,17,23,22,27,42,34,36,39,44',
  10648. third: '1,3,8,9,13,18,19,28,0,33,37,40,32,45,44'
  10649. },
  10650. //Орион, 13-я
  10651. "adv_ghirwil_3pl_hell": {
  10652. first: '1,2,3,6,8,12,11,15,21,27,36,34,33,35,37',
  10653. second: '1,2,4,6,9,13,18,17,16,22,28,29,30,31,25,19',
  10654. third: '1,2,5,6,10,13,14,20,26,32,38,41,40,39,37'
  10655. },
  10656. //Джинджер, 13-я
  10657. "adv_valley_3pl_hell": {
  10658. first: '1,3,2,6,11,17,25,30,35,34,29,24,21,17,12,7',
  10659. second: '1,4,8,13,18,22,26,31,36,40,45,44,43,38,33,28',
  10660. third: '1,5,9,14,19,23,27,32,37,42,48,51,50,49,46,52'
  10661. }
  10662. }
  10663. callStartBattle = {
  10664. name: "adventure_turnStartBattle",
  10665. args: {},
  10666. ident: "body"
  10667. }
  10668. callEndBattle = {
  10669. name: "adventure_endBattle",
  10670. args: {
  10671. result: {},
  10672. progress: {},
  10673. },
  10674. ident: "body"
  10675. }
  10676. callCollectBuff = {
  10677. name: "adventure_turnCollectBuff",
  10678. args: {},
  10679. ident: "body"
  10680. }
  10681.  
  10682. constructor(resolve, reject) {
  10683. this.resolve = resolve;
  10684. this.reject = reject;
  10685. }
  10686.  
  10687. async start(type) {
  10688. //this.type = type || this.type;
  10689. //this.callAdventureInfo.name = this.actions[this.type].getInfo;
  10690. const data = await Send(JSON.stringify({
  10691. calls: [
  10692. this.callAdventureInfo,
  10693. this.callTeamGetAll,
  10694. this.callTeamGetFavor
  10695. ]
  10696. }));
  10697. //тест прикла1
  10698. this.path = await this.getPath(data.results[0].result.response.mapIdent);
  10699. if (!this.path) {
  10700. this.end();
  10701. return;
  10702. }
  10703. return this.checkAdventureInfo(data.results);
  10704. }
  10705.  
  10706. async getPath(mapId) {
  10707. //const oldVal = getSaveVal('adventurePath', '');
  10708. //const keyPath = `adventurePath:${this.mapIdent}`;
  10709. const answer = await popup.confirm(I18N('ENTER_THE_PATH'), [
  10710. {
  10711. msg: I18N('START_ADVENTURE'),
  10712. placeholder: '1,2,3,4,5,6',
  10713. isInput: true,
  10714. //default: getSaveVal(keyPath, oldVal)
  10715. default: getSaveVal('adventurePath', '')
  10716. },
  10717. {
  10718. msg: ' Начать по пути №1! ',
  10719. placeholder: '1,2,3',
  10720. isInput: true,
  10721. default: this.defaultWays[mapId]?.first
  10722. },
  10723. {
  10724. msg: ' Начать по пути №2! ',
  10725. placeholder: '1,2,3',
  10726. isInput: true,
  10727. default: this.defaultWays[mapId]?.second
  10728. },
  10729. {
  10730. msg: ' Начать по пути №3! ',
  10731. placeholder: '1,2,3',
  10732. isInput: true,
  10733. default: this.defaultWays[mapId]?.third
  10734. },
  10735. {
  10736. msg: I18N('BTN_CANCEL'),
  10737. result: false,
  10738. isCancel: true
  10739. },
  10740. ]);
  10741. if (!answer) {
  10742. this.terminatеReason = I18N('BTN_CANCELED');
  10743. return false;
  10744. }
  10745.  
  10746. let path = answer.split(',');
  10747. if (path.length < 2) {
  10748. path = answer.split('-');
  10749. }
  10750. if (path.length < 2) {
  10751. this.terminatеReason = I18N('MUST_TWO_POINTS');
  10752. return false;
  10753. }
  10754.  
  10755. for (let p in path) {
  10756. path[p] = +path[p].trim()
  10757. if (Number.isNaN(path[p])) {
  10758. this.terminatеReason = I18N('MUST_ONLY_NUMBERS');
  10759. return false;
  10760. }
  10761. }
  10762.  
  10763. /*if (!this.checkPath(path)) {
  10764. return false;
  10765. }*/
  10766. //setSaveVal(keyPath, answer);
  10767. setSaveVal('adventurePath', answer);
  10768. return path;
  10769. }
  10770. /*
  10771. checkPath(path) {
  10772. for (let i = 0; i < path.length - 1; i++) {
  10773. const currentPoint = path[i];
  10774. const nextPoint = path[i + 1];
  10775.  
  10776. const isValidPath = this.paths.some(p =>
  10777. (p.from_id === currentPoint && p.to_id === nextPoint) ||
  10778. (p.from_id === nextPoint && p.to_id === currentPoint)
  10779. );
  10780.  
  10781. if (!isValidPath) {
  10782. this.terminatеReason = I18N('INCORRECT_WAY', {
  10783. from: currentPoint,
  10784. to: nextPoint,
  10785. });
  10786. return false;
  10787. }
  10788. }
  10789.  
  10790. return true;
  10791. }
  10792. */
  10793. async checkAdventureInfo(data) {
  10794. this.advInfo = data[0].result.response;
  10795. if (!this.advInfo) {
  10796. this.terminatеReason = I18N('NOT_ON_AN_ADVENTURE') ;
  10797. return this.end();
  10798. }
  10799. const heroesTeam = data[1].result.response.adventure_hero;
  10800. const favor = data[2]?.result.response.adventure_hero;
  10801. const heroes = heroesTeam.slice(0, 5);
  10802. const pet = heroesTeam[5];
  10803. this.args = {
  10804. pet,
  10805. heroes,
  10806. favor,
  10807. path: [],
  10808. broadcast: false
  10809. }
  10810. const advUserInfo = this.advInfo.users[userInfo.id];
  10811. this.turnsLeft = advUserInfo.turnsLeft;
  10812. this.currentNode = advUserInfo.currentNode;
  10813. this.nodes = this.advInfo.nodes;
  10814. //this.paths = this.advInfo.paths;
  10815. //this.mapIdent = this.advInfo.mapIdent;
  10816.  
  10817. /*this.path = await this.getPath();
  10818. if (!this.path) {
  10819. return this.end();
  10820. }*/
  10821.  
  10822. if (this.currentNode == 1 && this.path[0] != 1) {
  10823. this.path.unshift(1);
  10824. }
  10825.  
  10826. return this.loop();
  10827. }
  10828.  
  10829. async loop() {
  10830. const position = this.path.indexOf(+this.currentNode);
  10831. if (!(~position)) {
  10832. this.terminatеReason = I18N('YOU_IN_NOT_ON_THE_WAY');
  10833. return this.end();
  10834. }
  10835. this.path = this.path.slice(position);
  10836. if ((this.path.length - 1) > this.turnsLeft &&
  10837. await popup.confirm(I18N('ATTEMPTS_NOT_ENOUGH'), [
  10838. { msg: I18N('YES_CONTINUE'), result: false },
  10839. { msg: I18N('BTN_NO'), result: true },
  10840. ])) {
  10841. this.terminatеReason = I18N('NOT_ENOUGH_AP');
  10842. return this.end();
  10843. }
  10844. const toPath = [];
  10845. for (const nodeId of this.path) {
  10846. if (!this.turnsLeft) {
  10847. this.terminatеReason = I18N('ATTEMPTS_ARE_OVER');
  10848. return this.end();
  10849. }
  10850. toPath.push(nodeId);
  10851. console.log(toPath);
  10852. if (toPath.length > 1) {
  10853. setProgress(toPath.join(' > ') + ` ${I18N('MOVES')}: ` + this.turnsLeft);
  10854. }
  10855. if (nodeId == this.currentNode) {
  10856. continue;
  10857. }
  10858.  
  10859. const nodeInfo = this.getNodeInfo(nodeId);
  10860. if (nodeInfo.type == 'TYPE_COMBAT') {
  10861. if (nodeInfo.state == 'empty') {
  10862. this.turnsLeft--;
  10863. continue;
  10864. }
  10865.  
  10866. /**
  10867. * Disable regular battle cancellation
  10868. *
  10869. * Отключаем штатную отменую боя
  10870. */
  10871. isCancalBattle = false;
  10872. if (await this.battle(toPath)) {
  10873. this.turnsLeft--;
  10874. toPath.splice(0, toPath.indexOf(nodeId));
  10875. nodeInfo.state = 'empty';
  10876. isCancalBattle = true;
  10877. continue;
  10878. }
  10879. isCancalBattle = true;
  10880. return this.end()
  10881. }
  10882.  
  10883. if (nodeInfo.type == 'TYPE_PLAYERBUFF') {
  10884. const buff = this.checkBuff(nodeInfo);
  10885. if (buff == null) {
  10886. continue;
  10887. }
  10888.  
  10889. if (await this.collectBuff(buff, toPath)) {
  10890. this.turnsLeft--;
  10891. toPath.splice(0, toPath.indexOf(nodeId));
  10892. continue;
  10893. }
  10894. this.terminatеReason = I18N('BUFF_GET_ERROR');
  10895. return this.end();
  10896. }
  10897. }
  10898. this.terminatеReason = I18N('SUCCESS');
  10899. return this.end();
  10900. }
  10901.  
  10902. /**
  10903. * Carrying out a fight
  10904. *
  10905. * Проведение боя
  10906. */
  10907. async battle(path, preCalc = true) {
  10908. const data = await this.startBattle(path);
  10909. try {
  10910. const battle = data.results[0].result.response.battle;
  10911. const result = await Calc(battle);
  10912. if (result.result.win) {
  10913. const info = await this.endBattle(result);
  10914. if (info.results[0].result.response?.error) {
  10915. this.terminatеReason = I18N('BATTLE_END_ERROR');
  10916. return false;
  10917. }
  10918. } else {
  10919. await this.cancelBattle(result);
  10920.  
  10921. if (preCalc && await this.preCalcBattle(battle)) {
  10922. path = path.slice(-2);
  10923. for (let i = 1; i <= getInput('countAutoBattle'); i++) {
  10924. setProgress(`${I18N('AUTOBOT')}: ${i}/${getInput('countAutoBattle')}`);
  10925. const result = await this.battle(path, false);
  10926. if (result) {
  10927. setProgress(I18N('VICTORY'));
  10928. return true;
  10929. }
  10930. }
  10931. this.terminatеReason = I18N('FAILED_TO_WIN_AUTO');
  10932. return false;
  10933. }
  10934. return false;
  10935. }
  10936. } catch (error) {
  10937. console.error(error);
  10938. if (await popup.confirm(I18N('ERROR_OF_THE_BATTLE_COPY'), [
  10939. { msg: I18N('BTN_NO'), result: false },
  10940. { msg: I18N('BTN_YES'), result: true },
  10941. ])) {
  10942. this.errorHandling(error, data);
  10943. }
  10944. this.terminatеReason = I18N('ERROR_DURING_THE_BATTLE');
  10945. return false;
  10946. }
  10947. return true;
  10948. }
  10949.  
  10950. /**
  10951. * Recalculate battles
  10952. *
  10953. * Прерасчтет битвы
  10954. */
  10955. async preCalcBattle(battle) {
  10956. const countTestBattle = getInput('countTestBattle');
  10957. for (let i = 0; i < countTestBattle; i++) {
  10958. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  10959. const result = await Calc(battle);
  10960. if (result.result.win) {
  10961. console.log(i, countTestBattle);
  10962. return true;
  10963. }
  10964. }
  10965. this.terminatеReason = I18N('NO_CHANCE_WIN') + countTestBattle;
  10966. return false;
  10967. }
  10968.  
  10969. /**
  10970. * Starts a fight
  10971. *
  10972. * Начинает бой
  10973. */
  10974. startBattle(path) {
  10975. this.args.path = path;
  10976. this.callStartBattle.name = this.actions[this.type].startBattle;
  10977. this.callStartBattle.args = this.args
  10978. const calls = [this.callStartBattle];
  10979. return Send(JSON.stringify({ calls }));
  10980. }
  10981.  
  10982. cancelBattle(battle) {
  10983. const fixBattle = function (heroes) {
  10984. for (const ids in heroes) {
  10985. const hero = heroes[ids];
  10986. hero.energy = random(1, 999);
  10987. if (hero.hp > 0) {
  10988. hero.hp = random(1, hero.hp);
  10989. }
  10990. }
  10991. }
  10992. fixBattle(battle.progress[0].attackers.heroes);
  10993. fixBattle(battle.progress[0].defenders.heroes);
  10994. return this.endBattle(battle);
  10995. }
  10996.  
  10997. /**
  10998. * Ends the fight
  10999. *
  11000. * Заканчивает бой
  11001. */
  11002. endBattle(battle) {
  11003. this.callEndBattle.name = this.actions[this.type].endBattle;
  11004. this.callEndBattle.args.result = battle.result
  11005. this.callEndBattle.args.progress = battle.progress
  11006. const calls = [this.callEndBattle];
  11007. return Send(JSON.stringify({ calls }));
  11008. }
  11009.  
  11010. /**
  11011. * Checks if you can get a buff
  11012. *
  11013. * Проверяет можно ли получить баф
  11014. */
  11015. checkBuff(nodeInfo) {
  11016. let id = null;
  11017. let value = 0;
  11018. for (const buffId in nodeInfo.buffs) {
  11019. const buff = nodeInfo.buffs[buffId];
  11020. if (buff.owner == null && buff.value > value) {
  11021. id = buffId;
  11022. value = buff.value;
  11023. }
  11024. }
  11025. nodeInfo.buffs[id].owner = 'Я';
  11026. return id;
  11027. }
  11028.  
  11029. /**
  11030. * Collects a buff
  11031. *
  11032. * Собирает баф
  11033. */
  11034. async collectBuff(buff, path) {
  11035. this.callCollectBuff.name = this.actions[this.type].collectBuff;
  11036. this.callCollectBuff.args = { buff, path };
  11037. const calls = [this.callCollectBuff];
  11038. return Send(JSON.stringify({ calls }));
  11039. }
  11040.  
  11041. getNodeInfo(nodeId) {
  11042. return this.nodes.find(node => node.id == nodeId);
  11043. }
  11044.  
  11045. errorHandling(error, data) {
  11046. //console.error(error);
  11047. let errorInfo = error.toString() + '\n';
  11048. try {
  11049. const errorStack = error.stack.split('\n');
  11050. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testAdventure");
  11051. errorInfo += errorStack.slice(0, endStack).join('\n');
  11052. } catch (e) {
  11053. errorInfo += error.stack;
  11054. }
  11055. if (data) {
  11056. errorInfo += '\nData: ' + JSON.stringify(data);
  11057. }
  11058. copyText(errorInfo);
  11059. }
  11060.  
  11061. end() {
  11062. isCancalBattle = true;
  11063. setProgress(this.terminatеReason, true);
  11064. console.log(this.terminatеReason);
  11065. this.resolve();
  11066. }
  11067. }
  11068. class executeAdventure2 {
  11069.  
  11070. type = 'default';
  11071.  
  11072. actions = {
  11073. default: {
  11074. getInfo: "adventure_getInfo",
  11075. startBattle: 'adventure_turnStartBattle',
  11076. endBattle: 'adventure_endBattle',
  11077. collectBuff: 'adventure_turnCollectBuff'
  11078. },
  11079. solo: {
  11080. getInfo: "adventureSolo_getInfo",
  11081. startBattle: 'adventureSolo_turnStartBattle',
  11082. endBattle: 'adventureSolo_endBattle',
  11083. collectBuff: 'adventureSolo_turnCollectBuff'
  11084. }
  11085. }
  11086.  
  11087. terminatеReason = I18N('UNKNOWN');
  11088. callAdventureInfo = {
  11089. name: "adventure_getInfo",
  11090. args: {},
  11091. ident: "adventure_getInfo"
  11092. }
  11093. callTeamGetAll = {
  11094. name: "teamGetAll",
  11095. args: {},
  11096. ident: "teamGetAll"
  11097. }
  11098. callTeamGetFavor = {
  11099. name: "teamGetFavor",
  11100. args: {},
  11101. ident: "teamGetFavor"
  11102. }
  11103. callStartBattle = {
  11104. name: "adventure_turnStartBattle",
  11105. args: {},
  11106. ident: "body"
  11107. }
  11108. callEndBattle = {
  11109. name: "adventure_endBattle",
  11110. args: {
  11111. result: {},
  11112. progress: {},
  11113. },
  11114. ident: "body"
  11115. }
  11116. callCollectBuff = {
  11117. name: "adventure_turnCollectBuff",
  11118. args: {},
  11119. ident: "body"
  11120. }
  11121.  
  11122. constructor(resolve, reject) {
  11123. this.resolve = resolve;
  11124. this.reject = reject;
  11125. }
  11126.  
  11127. async start(type) {
  11128. this.type = type || this.type;
  11129. this.callAdventureInfo.name = this.actions[this.type].getInfo;
  11130. const data = await Send(JSON.stringify({
  11131. calls: [
  11132. this.callAdventureInfo,
  11133. this.callTeamGetAll,
  11134. this.callTeamGetFavor
  11135. ]
  11136. }));
  11137. return this.checkAdventureInfo(data.results);
  11138. }
  11139.  
  11140. async getPath() {
  11141. const oldVal = getSaveVal('adventurePath', '');
  11142. const keyPath = `adventurePath:${this.mapIdent}`;
  11143. const answer = await popup.confirm(I18N('ENTER_THE_PATH'), [
  11144. {
  11145. msg: I18N('START_ADVENTURE'),
  11146. placeholder: '1,2,3,4,5,6',
  11147. isInput: true,
  11148. default: getSaveVal(keyPath, oldVal)
  11149. },
  11150. {
  11151. msg: I18N('BTN_CANCEL'),
  11152. result: false,
  11153. isCancel: true
  11154. },
  11155. ]);
  11156. if (!answer) {
  11157. this.terminatеReason = I18N('BTN_CANCELED');
  11158. return false;
  11159. }
  11160.  
  11161. let path = answer.split(',');
  11162. if (path.length < 2) {
  11163. path = answer.split('-');
  11164. }
  11165. if (path.length < 2) {
  11166. this.terminatеReason = I18N('MUST_TWO_POINTS');
  11167. return false;
  11168. }
  11169.  
  11170. for (let p in path) {
  11171. path[p] = +path[p].trim()
  11172. if (Number.isNaN(path[p])) {
  11173. this.terminatеReason = I18N('MUST_ONLY_NUMBERS');
  11174. return false;
  11175. }
  11176. }
  11177. if (!this.checkPath(path)) {
  11178. return false;
  11179. }
  11180. setSaveVal(keyPath, answer);
  11181. return path;
  11182. }
  11183.  
  11184. checkPath(path) {
  11185. for (let i = 0; i < path.length - 1; i++) {
  11186. const currentPoint = path[i];
  11187. const nextPoint = path[i + 1];
  11188.  
  11189. const isValidPath = this.paths.some(p =>
  11190. (p.from_id === currentPoint && p.to_id === nextPoint) ||
  11191. (p.from_id === nextPoint && p.to_id === currentPoint)
  11192. );
  11193.  
  11194. if (!isValidPath) {
  11195. this.terminatеReason = I18N('INCORRECT_WAY', {
  11196. from: currentPoint,
  11197. to: nextPoint,
  11198. });
  11199. return false;
  11200. }
  11201. }
  11202.  
  11203. return true;
  11204. }
  11205.  
  11206. async checkAdventureInfo(data) {
  11207. this.advInfo = data[0].result.response;
  11208. if (!this.advInfo) {
  11209. this.terminatеReason = I18N('NOT_ON_AN_ADVENTURE') ;
  11210. return this.end();
  11211. }
  11212. const heroesTeam = data[1].result.response.adventure_hero;
  11213. const favor = data[2]?.result.response.adventure_hero;
  11214. const heroes = heroesTeam.slice(0, 5);
  11215. const pet = heroesTeam[5];
  11216. this.args = {
  11217. pet,
  11218. heroes,
  11219. favor,
  11220. path: [],
  11221. broadcast: false
  11222. }
  11223. const advUserInfo = this.advInfo.users[userInfo.id];
  11224. this.turnsLeft = advUserInfo.turnsLeft;
  11225. this.currentNode = advUserInfo.currentNode;
  11226. this.nodes = this.advInfo.nodes;
  11227. this.paths = this.advInfo.paths;
  11228. this.mapIdent = this.advInfo.mapIdent;
  11229.  
  11230. this.path = await this.getPath();
  11231. if (!this.path) {
  11232. return this.end();
  11233. }
  11234.  
  11235. if (this.currentNode == 1 && this.path[0] != 1) {
  11236. this.path.unshift(1);
  11237. }
  11238.  
  11239. return this.loop();
  11240. }
  11241.  
  11242. async loop() {
  11243. const position = this.path.indexOf(+this.currentNode);
  11244. if (!(~position)) {
  11245. this.terminatеReason = I18N('YOU_IN_NOT_ON_THE_WAY');
  11246. return this.end();
  11247. }
  11248. this.path = this.path.slice(position);
  11249. if ((this.path.length - 1) > this.turnsLeft &&
  11250. await popup.confirm(I18N('ATTEMPTS_NOT_ENOUGH'), [
  11251. { msg: I18N('YES_CONTINUE'), result: false },
  11252. { msg: I18N('BTN_NO'), result: true },
  11253. ])) {
  11254. this.terminatеReason = I18N('NOT_ENOUGH_AP');
  11255. return this.end();
  11256. }
  11257. const toPath = [];
  11258. for (const nodeId of this.path) {
  11259. if (!this.turnsLeft) {
  11260. this.terminatеReason = I18N('ATTEMPTS_ARE_OVER');
  11261. return this.end();
  11262. }
  11263. toPath.push(nodeId);
  11264. console.log(toPath);
  11265. if (toPath.length > 1) {
  11266. setProgress(toPath.join(' > ') + ` ${I18N('MOVES')}: ` + this.turnsLeft);
  11267. }
  11268. if (nodeId == this.currentNode) {
  11269. continue;
  11270. }
  11271.  
  11272. const nodeInfo = this.getNodeInfo(nodeId);
  11273. if (nodeInfo.type == 'TYPE_COMBAT') {
  11274. if (nodeInfo.state == 'empty') {
  11275. this.turnsLeft--;
  11276. continue;
  11277. }
  11278.  
  11279. /**
  11280. * Disable regular battle cancellation
  11281. *
  11282. * Отключаем штатную отменую боя
  11283. */
  11284. isCancalBattle = false;
  11285. if (await this.battle(toPath)) {
  11286. this.turnsLeft--;
  11287. toPath.splice(0, toPath.indexOf(nodeId));
  11288. nodeInfo.state = 'empty';
  11289. isCancalBattle = true;
  11290. continue;
  11291. }
  11292. isCancalBattle = true;
  11293. return this.end()
  11294. }
  11295.  
  11296. if (nodeInfo.type == 'TYPE_PLAYERBUFF') {
  11297. const buff = this.checkBuff(nodeInfo);
  11298. if (buff == null) {
  11299. continue;
  11300. }
  11301.  
  11302. if (await this.collectBuff(buff, toPath)) {
  11303. this.turnsLeft--;
  11304. toPath.splice(0, toPath.indexOf(nodeId));
  11305. continue;
  11306. }
  11307. this.terminatеReason = I18N('BUFF_GET_ERROR');
  11308. return this.end();
  11309. }
  11310. }
  11311. this.terminatеReason = I18N('SUCCESS');
  11312. return this.end();
  11313. }
  11314.  
  11315. /**
  11316. * Carrying out a fight
  11317. *
  11318. * Проведение боя
  11319. */
  11320. async battle(path, preCalc = true) {
  11321. const data = await this.startBattle(path);
  11322. try {
  11323. const battle = data.results[0].result.response.battle;
  11324. const result = await Calc(battle);
  11325. if (result.result.win) {
  11326. const info = await this.endBattle(result);
  11327. if (info.results[0].result.response?.error) {
  11328. this.terminatеReason = I18N('BATTLE_END_ERROR');
  11329. return false;
  11330. }
  11331. } else {
  11332. await this.cancelBattle(result);
  11333.  
  11334. if (preCalc && await this.preCalcBattle(battle)) {
  11335. path = path.slice(-2);
  11336. for (let i = 1; i <= getInput('countAutoBattle'); i++) {
  11337. setProgress(`${I18N('AUTOBOT')}: ${i}/${getInput('countAutoBattle')}`);
  11338. const result = await this.battle(path, false);
  11339. if (result) {
  11340. setProgress(I18N('VICTORY'));
  11341. return true;
  11342. }
  11343. }
  11344. this.terminatеReason = I18N('FAILED_TO_WIN_AUTO');
  11345. return false;
  11346. }
  11347. return false;
  11348. }
  11349. } catch (error) {
  11350. console.error(error);
  11351. if (await popup.confirm(I18N('ERROR_OF_THE_BATTLE_COPY'), [
  11352. { msg: I18N('BTN_NO'), result: false },
  11353. { msg: I18N('BTN_YES'), result: true },
  11354. ])) {
  11355. this.errorHandling(error, data);
  11356. }
  11357. this.terminatеReason = I18N('ERROR_DURING_THE_BATTLE');
  11358. return false;
  11359. }
  11360. return true;
  11361. }
  11362.  
  11363. /**
  11364. * Recalculate battles
  11365. *
  11366. * Прерасчтет битвы
  11367. */
  11368. async preCalcBattle(battle) {
  11369. const countTestBattle = getInput('countTestBattle');
  11370. for (let i = 0; i < countTestBattle; i++) {
  11371. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  11372. const result = await Calc(battle);
  11373. if (result.result.win) {
  11374. console.log(i, countTestBattle);
  11375. return true;
  11376. }
  11377. }
  11378. this.terminatеReason = I18N('NO_CHANCE_WIN') + countTestBattle;
  11379. return false;
  11380. }
  11381.  
  11382. /**
  11383. * Starts a fight
  11384. *
  11385. * Начинает бой
  11386. */
  11387. startBattle(path) {
  11388. this.args.path = path;
  11389. this.callStartBattle.name = this.actions[this.type].startBattle;
  11390. this.callStartBattle.args = this.args
  11391. const calls = [this.callStartBattle];
  11392. return Send(JSON.stringify({ calls }));
  11393. }
  11394.  
  11395. cancelBattle(battle) {
  11396. const fixBattle = function (heroes) {
  11397. for (const ids in heroes) {
  11398. const hero = heroes[ids];
  11399. hero.energy = random(1, 999);
  11400. if (hero.hp > 0) {
  11401. hero.hp = random(1, hero.hp);
  11402. }
  11403. }
  11404. }
  11405. fixBattle(battle.progress[0].attackers.heroes);
  11406. fixBattle(battle.progress[0].defenders.heroes);
  11407. return this.endBattle(battle);
  11408. }
  11409.  
  11410. /**
  11411. * Ends the fight
  11412. *
  11413. * Заканчивает бой
  11414. */
  11415. endBattle(battle) {
  11416. this.callEndBattle.name = this.actions[this.type].endBattle;
  11417. this.callEndBattle.args.result = battle.result
  11418. this.callEndBattle.args.progress = battle.progress
  11419. const calls = [this.callEndBattle];
  11420. return Send(JSON.stringify({ calls }));
  11421. }
  11422.  
  11423. /**
  11424. * Checks if you can get a buff
  11425. *
  11426. * Проверяет можно ли получить баф
  11427. */
  11428. checkBuff(nodeInfo) {
  11429. let id = null;
  11430. let value = 0;
  11431. for (const buffId in nodeInfo.buffs) {
  11432. const buff = nodeInfo.buffs[buffId];
  11433. if (buff.owner == null && buff.value > value) {
  11434. id = buffId;
  11435. value = buff.value;
  11436. }
  11437. }
  11438. nodeInfo.buffs[id].owner = 'Я';
  11439. return id;
  11440. }
  11441.  
  11442. /**
  11443. * Collects a buff
  11444. *
  11445. * Собирает баф
  11446. */
  11447. async collectBuff(buff, path) {
  11448. this.callCollectBuff.name = this.actions[this.type].collectBuff;
  11449. this.callCollectBuff.args = { buff, path };
  11450. const calls = [this.callCollectBuff];
  11451. return Send(JSON.stringify({ calls }));
  11452. }
  11453.  
  11454. getNodeInfo(nodeId) {
  11455. return this.nodes.find(node => node.id == nodeId);
  11456. }
  11457.  
  11458. errorHandling(error, data) {
  11459. //console.error(error);
  11460. let errorInfo = error.toString() + '\n';
  11461. try {
  11462. const errorStack = error.stack.split('\n');
  11463. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testAdventure");
  11464. errorInfo += errorStack.slice(0, endStack).join('\n');
  11465. } catch (e) {
  11466. errorInfo += error.stack;
  11467. }
  11468. if (data) {
  11469. errorInfo += '\nData: ' + JSON.stringify(data);
  11470. }
  11471. copyText(errorInfo);
  11472. }
  11473.  
  11474. end() {
  11475. isCancalBattle = true;
  11476. setProgress(this.terminatеReason, true);
  11477. console.log(this.terminatеReason);
  11478. this.resolve();
  11479. }
  11480. }
  11481. /**
  11482. * Passage of brawls
  11483. *
  11484. * Прохождение потасовок
  11485. */
  11486. function testBrawls() {
  11487. return new Promise((resolve, reject) => {
  11488. const brawls = new executeBrawls(resolve, reject);
  11489. brawls.start(brawlsPack);
  11490. });
  11491. }
  11492. /**
  11493. * Passage of brawls
  11494. *
  11495. * Прохождение потасовок
  11496. */
  11497. class executeBrawls {
  11498. callBrawlQuestGetInfo = {
  11499. name: "brawl_questGetInfo",
  11500. args: {},
  11501. ident: "brawl_questGetInfo"
  11502. }
  11503. callBrawlFindEnemies = {
  11504. name: "brawl_findEnemies",
  11505. args: {},
  11506. ident: "brawl_findEnemies"
  11507. }
  11508. callBrawlQuestFarm = {
  11509. name: "brawl_questFarm",
  11510. args: {},
  11511. ident: "brawl_questFarm"
  11512. }
  11513. callUserGetInfo = {
  11514. name: "userGetInfo",
  11515. args: {},
  11516. ident: "userGetInfo"
  11517. }
  11518. callTeamGetMaxUpgrade = {
  11519. name: "teamGetMaxUpgrade",
  11520. args: {},
  11521. ident: "teamGetMaxUpgrade"
  11522. }
  11523. callBrawlGetInfo = {
  11524. name: "brawl_getInfo",
  11525. args: {},
  11526. ident: "brawl_getInfo"
  11527. }
  11528.  
  11529. stats = {
  11530. win: 0,
  11531. loss: 0,
  11532. count: 0,
  11533. }
  11534.  
  11535. stage = {
  11536. '3': 1,
  11537. '7': 2,
  11538. '12': 3,
  11539. }
  11540.  
  11541. attempts = 0;
  11542.  
  11543. constructor(resolve, reject) {
  11544. this.resolve = resolve;
  11545. this.reject = reject;
  11546. }
  11547.  
  11548. async start(args) {
  11549. this.args = args;
  11550. isCancalBattle = false;
  11551. this.brawlInfo = await this.getBrawlInfo();
  11552. this.attempts = this.brawlInfo.attempts;
  11553.  
  11554. if (!this.attempts) {
  11555. this.end(I18N('DONT_HAVE_LIVES'))
  11556. return;
  11557. }
  11558.  
  11559. while (1) {
  11560. if (!isBrawlsAutoStart) {
  11561. this.end(I18N('BTN_CANCELED'))
  11562. return;
  11563. }
  11564.  
  11565. const maxStage = this.brawlInfo.questInfo.stage;
  11566. const stage = this.stage[maxStage];
  11567. const progress = this.brawlInfo.questInfo.progress;
  11568.  
  11569. 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 () {
  11570. isBrawlsAutoStart = false;
  11571. });
  11572.  
  11573. if (this.brawlInfo.questInfo.canFarm) {
  11574. const result = await this.questFarm();
  11575. console.log(result);
  11576. }
  11577.  
  11578. if (this.brawlInfo.questInfo.stage == 12 && this.brawlInfo.questInfo.progress == 12) {
  11579. this.end(I18N('SUCCESS'))
  11580. return;
  11581. }
  11582.  
  11583. if (!this.attempts) {
  11584. this.end(I18N('DONT_HAVE_LIVES'))
  11585. return;
  11586. }
  11587.  
  11588. const enemie = Object.values(this.brawlInfo.findEnemies).shift();
  11589.  
  11590. // Для потасовок брустара
  11591. this.args.heroes = await this.updatePack(enemie.heroes);
  11592.  
  11593. const result = await this.battle(enemie.userId);
  11594. this.brawlInfo = {
  11595. questInfo: result[1].result.response,
  11596. findEnemies: result[2].result.response,
  11597. }
  11598. }
  11599. }
  11600.  
  11601. async updatePack(enemieHeroes) {
  11602. const packs = [
  11603. // 4023 Эдем
  11604. [4020, 4022, 4023, 4042, 4043],
  11605. [4023, 4030, 4033, 4042, 4043],
  11606. [4023, 4040, 4041, 4042, 4043],
  11607. // Разное
  11608. [4003, 4010, 4011, 4012, 4013],
  11609. [4030, 4032, 4033, 4040, 4043],
  11610. [4033, 4040, 4041, 4042, 4043],
  11611. [4030, 4031, 4033, 4040, 4043],
  11612. [4030, 4033, 4040, 4042, 4043],
  11613. [4001, 4032, 4033, 4040, 4043],
  11614. [4010, 4012, 4013, 4040, 4043],
  11615. [4001, 4002, 4003, 4040, 4043],
  11616. // 4003 Гиперион
  11617. [4000, 4001, 4003, 4033, 4043],
  11618. [4000, 4001, 4003, 4023, 4030],
  11619. [4000, 4001, 4003, 4023, 4033],
  11620. [4000, 4001, 4003, 4013, 4033],
  11621. [4003, 4010, 4012, 4013, 4043],
  11622. [4003, 4010, 4012, 4013, 4033],
  11623. [4003, 4030, 4032, 4042, 4043],
  11624. [4003, 4030, 4031, 4032, 4033],
  11625. [4003, 4040, 4041, 4042, 4043],
  11626. [4003, 4030, 4033, 4040, 4043],
  11627. // 4013 Араджи
  11628. [4010, 4011, 4012, 4013, 4033],
  11629. [4010, 4011, 4012, 4013, 4043],
  11630. [4010, 4011, 4013, 4042, 4043],
  11631. [4010, 4011, 4013, 4033, 4043],
  11632. [4001, 4010, 4011, 4013, 4033],
  11633. [4010, 4011, 4013, 4030, 4033],
  11634. [4010, 4011, 4013, 4040, 4043],
  11635. [4013, 4030, 4033, 4040, 4043],
  11636. [4013, 4030, 4033, 4042, 4043],
  11637. [4013, 4020, 4022, 4023, 4033],
  11638. ].filter(p => p.includes(this.mandatoryId))
  11639.  
  11640. const bestPack = {
  11641. pack: packs[0],
  11642. countWin: 0,
  11643. }
  11644.  
  11645. for (const pack of packs) {
  11646. const attackers = this.maxUpgrade
  11647. .filter(e => pack.includes(e.id))
  11648. .reduce((obj, e) => ({ ...obj, [e.id]: e }), {});
  11649. const battle = {
  11650. attackers,
  11651. defenders: [enemieHeroes],
  11652. type: "brawl_titan",
  11653. }
  11654.  
  11655. let countWinBattles = 0;
  11656. let countTestBattle = 10;
  11657. for (let i = 0; i < countTestBattle; i++) {
  11658. battle.seed = Math.floor(Date.now() / 1000) + Math.random() * 1000;
  11659. const result = await Calc(battle);
  11660. if (result.result.win) {
  11661. countWinBattles++;
  11662. }
  11663. if (countWinBattles > 7) {
  11664. console.log(pack)
  11665. return pack;
  11666. }
  11667. }
  11668. if (countWinBattles > bestPack.countWin) {
  11669. bestPack.countWin = countWinBattles;
  11670. bestPack.pack = pack;
  11671. }
  11672. }
  11673.  
  11674. console.log(bestPack);
  11675. return bestPack.pack;
  11676. }
  11677.  
  11678. async questFarm() {
  11679. const calls = [this.callBrawlQuestFarm];
  11680. const result = await Send(JSON.stringify({ calls }));
  11681. return result.results[0].result.response;
  11682. }
  11683.  
  11684. async getBrawlInfo() {
  11685. const data = await Send(JSON.stringify({
  11686. calls: [
  11687. this.callUserGetInfo,
  11688. this.callBrawlQuestGetInfo,
  11689. this.callBrawlFindEnemies,
  11690. this.callTeamGetMaxUpgrade,
  11691. this.callBrawlGetInfo,
  11692. ]
  11693. }));
  11694.  
  11695. let attempts = data.results[0].result.response.refillable.find(n => n.id == 48);
  11696. this.maxUpgrade = Object.values(data.results[3].result.response.titan);
  11697. this.info = data.results[4].result.response;
  11698. this.mandatoryId = lib.data.brawl.promoHero[this.info.id].promoHero;
  11699. return {
  11700. attempts: attempts.amount,
  11701. questInfo: data.results[1].result.response,
  11702. findEnemies: data.results[2].result.response,
  11703. }
  11704. }
  11705.  
  11706. /**
  11707. * Carrying out a fight
  11708. *
  11709. * Проведение боя
  11710. */
  11711. async battle(userId) {
  11712. this.stats.count++;
  11713. const battle = await this.startBattle(userId, this.args);
  11714. const result = await Calc(battle);
  11715. console.log(result.result);
  11716. if (result.result.win) {
  11717. this.stats.win++;
  11718. } else {
  11719. this.stats.loss++;
  11720. this.attempts--;
  11721. }
  11722. return await this.endBattle(result);
  11723. // return await this.cancelBattle(result);
  11724. }
  11725.  
  11726. /**
  11727. * Starts a fight
  11728. *
  11729. * Начинает бой
  11730. */
  11731. async startBattle(userId, args) {
  11732. const call = {
  11733. name: "brawl_startBattle",
  11734. args,
  11735. ident: "brawl_startBattle"
  11736. }
  11737. call.args.userId = userId;
  11738. const calls = [call];
  11739. const result = await Send(JSON.stringify({ calls }));
  11740. return result.results[0].result.response;
  11741. }
  11742.  
  11743. cancelBattle(battle) {
  11744. const fixBattle = function (heroes) {
  11745. for (const ids in heroes) {
  11746. const hero = heroes[ids];
  11747. hero.energy = random(1, 999);
  11748. if (hero.hp > 0) {
  11749. hero.hp = random(1, hero.hp);
  11750. }
  11751. }
  11752. }
  11753. fixBattle(battle.progress[0].attackers.heroes);
  11754. fixBattle(battle.progress[0].defenders.heroes);
  11755. return this.endBattle(battle);
  11756. }
  11757.  
  11758. /**
  11759. * Ends the fight
  11760. *
  11761. * Заканчивает бой
  11762. */
  11763. async endBattle(battle) {
  11764. battle.progress[0].attackers.input = ['auto', 0, 0, 'auto', 0, 0];
  11765. const calls = [{
  11766. name: "brawl_endBattle",
  11767. args: {
  11768. result: battle.result,
  11769. progress: battle.progress
  11770. },
  11771. ident: "brawl_endBattle"
  11772. },
  11773. this.callBrawlQuestGetInfo,
  11774. this.callBrawlFindEnemies,
  11775. ];
  11776. const result = await Send(JSON.stringify({ calls }));
  11777. return result.results;
  11778. }
  11779.  
  11780. end(endReason) {
  11781. isCancalBattle = true;
  11782. isBrawlsAutoStart = false;
  11783. setProgress(endReason, true);
  11784. console.log(endReason);
  11785. this.resolve();
  11786. }
  11787. }
  11788.  
  11789. // подземку вконце впихнул
  11790. function DungeonFull() {
  11791. return new Promise((resolve, reject) => {
  11792. const dung = new executeDungeon2(resolve, reject);
  11793. const titanit = getInput('countTitanit');
  11794. dung.start(titanit);
  11795. });
  11796. }
  11797. /** Прохождение подземелья */
  11798. function executeDungeon2(resolve, reject) {
  11799. let dungeonActivity = 0;
  11800. let startDungeonActivity = 0;
  11801. let maxDungeonActivity = 150;
  11802. let limitDungeonActivity = 30180;
  11803. let countShowStats = 1;
  11804. //let fastMode = isChecked('fastMode');
  11805. let end = false;
  11806.  
  11807. let countTeam = [];
  11808. let timeDungeon = {
  11809. all: new Date().getTime(),
  11810. findAttack: 0,
  11811. attackNeutral: 0,
  11812. attackEarthOrFire: 0
  11813. }
  11814.  
  11815. let titansStates = {};
  11816. let bestBattle = {};
  11817.  
  11818. let teams = {
  11819. neutral: [],
  11820. water: [],
  11821. earth: [],
  11822. fire: [],
  11823. hero: []
  11824. }
  11825.  
  11826. let callsExecuteDungeon = {
  11827. calls: [{
  11828. name: "dungeonGetInfo",
  11829. args: {},
  11830. ident: "dungeonGetInfo"
  11831. }, {
  11832. name: "teamGetAll",
  11833. args: {},
  11834. ident: "teamGetAll"
  11835. }, {
  11836. name: "teamGetFavor",
  11837. args: {},
  11838. ident: "teamGetFavor"
  11839. }, {
  11840. name: "clanGetInfo",
  11841. args: {},
  11842. ident: "clanGetInfo"
  11843. }]
  11844. }
  11845.  
  11846. this.start = async function(titanit) {
  11847. //maxDungeonActivity = titanit > limitDungeonActivity ? limitDungeonActivity : titanit;
  11848. maxDungeonActivity = titanit || getInput('countTitanit');
  11849. send(JSON.stringify(callsExecuteDungeon), startDungeon);
  11850. }
  11851.  
  11852. /** Получаем данные по подземелью */
  11853. function startDungeon(e) {
  11854. stopDung = false; // стоп подземка
  11855. let res = e.results;
  11856. let dungeonGetInfo = res[0].result.response;
  11857. if (!dungeonGetInfo) {
  11858. endDungeon('noDungeon', res);
  11859. return;
  11860. }
  11861. console.log("Начинаем копать на фулл: ", new Date());
  11862. let teamGetAll = res[1].result.response;
  11863. let teamGetFavor = res[2].result.response;
  11864. dungeonActivity = res[3].result.response.stat.todayDungeonActivity;
  11865. startDungeonActivity = res[3].result.response.stat.todayDungeonActivity;
  11866. titansStates = dungeonGetInfo.states.titans;
  11867.  
  11868. teams.hero = {
  11869. favor: teamGetFavor.dungeon_hero,
  11870. heroes: teamGetAll.dungeon_hero.filter(id => id < 6000),
  11871. teamNum: 0,
  11872. }
  11873. let heroPet = teamGetAll.dungeon_hero.filter(id => id >= 6000).pop();
  11874. if (heroPet) {
  11875. teams.hero.pet = heroPet;
  11876. }
  11877. teams.neutral = getTitanTeam('neutral');
  11878. teams.water = {
  11879. favor: {},
  11880. heroes: getTitanTeam('water'),
  11881. teamNum: 0,
  11882. };
  11883. teams.earth = {
  11884. favor: {},
  11885. heroes: getTitanTeam('earth'),
  11886. teamNum: 0,
  11887. };
  11888. teams.fire = {
  11889. favor: {},
  11890. heroes: getTitanTeam('fire'),
  11891. teamNum: 0,
  11892. };
  11893.  
  11894. checkFloor(dungeonGetInfo);
  11895. }
  11896.  
  11897. function getTitanTeam(type) {
  11898. switch (type) {
  11899. case 'neutral':
  11900. return [4023, 4022, 4012, 4021, 4011, 4010, 4020];
  11901. case 'water':
  11902. return [4000, 4001, 4002, 4003]
  11903. .filter(e => !titansStates[e]?.isDead);
  11904. case 'earth':
  11905. return [4020, 4022, 4021, 4023]
  11906. .filter(e => !titansStates[e]?.isDead);
  11907. case 'fire':
  11908. return [4010, 4011, 4012, 4013]
  11909. .filter(e => !titansStates[e]?.isDead);
  11910. }
  11911. }
  11912.  
  11913. /** Создать копию объекта */
  11914. function clone(a) {
  11915. return JSON.parse(JSON.stringify(a));
  11916. }
  11917.  
  11918. /** Находит стихию на этаже */
  11919. function findElement(floor, element) {
  11920. for (let i in floor) {
  11921. if (floor[i].attackerType === element) {
  11922. return i;
  11923. }
  11924. }
  11925. return undefined;
  11926. }
  11927.  
  11928. /** Проверяем этаж */
  11929. async function checkFloor(dungeonInfo) {
  11930. if (!('floor' in dungeonInfo) || dungeonInfo.floor?.state == 2) {
  11931. saveProgress();
  11932. return;
  11933. }
  11934. // console.log(dungeonInfo, dungeonActivity);
  11935. setProgress(`${I18N('DUNGEON2')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity}`);
  11936. //setProgress('Dungeon: Титанит ' + dungeonActivity + '/' + maxDungeonActivity);
  11937. if (dungeonActivity >= maxDungeonActivity) {
  11938. endDungeon('Стоп подземка,', 'набрано титанита: ' + dungeonActivity + '/' + maxDungeonActivity);
  11939. return;
  11940. }
  11941. let activity = dungeonActivity - startDungeonActivity;
  11942. titansStates = dungeonInfo.states.titans;
  11943. if (stopDung){
  11944. endDungeon('Стоп подземка,', 'набрано титанита: ' + dungeonActivity + '/' + maxDungeonActivity);
  11945. return;
  11946. }
  11947. /*if (activity / 1000 > countShowStats) {
  11948. countShowStats++;
  11949. showStats();
  11950. }*/
  11951. bestBattle = {};
  11952. let floorChoices = dungeonInfo.floor.userData;
  11953. if (floorChoices.length > 1) {
  11954. for (let element in teams) {
  11955. let teamNum = findElement(floorChoices, element);
  11956. if (!!teamNum) {
  11957. if (element == 'earth') {
  11958. teamNum = await chooseEarthOrFire(floorChoices);
  11959. if (teamNum < 0) {
  11960. endDungeon('Невозможно победить без потери Титана!', dungeonInfo);
  11961. return;
  11962. }
  11963. }
  11964. chooseElement(floorChoices[teamNum].attackerType, teamNum);
  11965. return;
  11966. }
  11967. }
  11968. } else {
  11969. chooseElement(floorChoices[0].attackerType, 0);
  11970. }
  11971. }
  11972.  
  11973. /** Выбираем огнем или землей атаковать */
  11974. async function chooseEarthOrFire(floorChoices) {
  11975. bestBattle.recovery = -11;
  11976. let selectedTeamNum = -1;
  11977. for (let attempt = 0; selectedTeamNum < 0 && attempt < 4; attempt++) {
  11978. for (let teamNum in floorChoices) {
  11979. let attackerType = floorChoices[teamNum].attackerType;
  11980. selectedTeamNum = await attemptAttackEarthOrFire(teamNum, attackerType, attempt);
  11981. }
  11982. }
  11983. console.log("Выбор команды огня или земли: ", selectedTeamNum < 0 ? "не сделан" : floorChoices[selectedTeamNum].attackerType);
  11984. return selectedTeamNum;
  11985. }
  11986.  
  11987. /** Попытка атаки землей и огнем */
  11988. async function attemptAttackEarthOrFire(teamNum, attackerType, attempt) {
  11989. let start = new Date();
  11990. let team = clone(teams[attackerType]);
  11991. let startIndex = team.heroes.length + attempt - 4;
  11992. if (startIndex >= 0) {
  11993. team.heroes = team.heroes.slice(startIndex);
  11994. let recovery = await getBestRecovery(teamNum, attackerType, team, 25);
  11995. if (recovery > bestBattle.recovery) {
  11996. bestBattle.recovery = recovery;
  11997. bestBattle.selectedTeamNum = teamNum;
  11998. bestBattle.team = team;
  11999. }
  12000. }
  12001. let workTime = new Date().getTime() - start.getTime();
  12002. timeDungeon.attackEarthOrFire += workTime;
  12003. if (bestBattle.recovery < -10) {
  12004. return -1;
  12005. }
  12006. return bestBattle.selectedTeamNum;
  12007. }
  12008.  
  12009. /** Выбираем стихию для атаки */
  12010. async function chooseElement(attackerType, teamNum) {
  12011. let result;
  12012. switch (attackerType) {
  12013. case 'hero':
  12014. case 'water':
  12015. result = await startBattle(teamNum, attackerType, teams[attackerType]);
  12016. break;
  12017. case 'earth':
  12018. case 'fire':
  12019. result = await attackEarthOrFire(teamNum, attackerType);
  12020. break;
  12021. case 'neutral':
  12022. result = await attackNeutral(teamNum, attackerType);
  12023. }
  12024. if (!!result && attackerType != 'hero') {
  12025. let recovery = (!!!bestBattle.recovery ? 10 * getRecovery(result) : bestBattle.recovery) * 100;
  12026. let titans = result.progress[0].attackers.heroes;
  12027. console.log("Проведен бой: " + attackerType +
  12028. ", recovery = " + (recovery > 0 ? "+" : "") + Math.round(recovery) + "% \r\n", titans);
  12029. }
  12030. endBattle(result);
  12031. }
  12032.  
  12033. /** Атакуем Землей или Огнем */
  12034. async function attackEarthOrFire(teamNum, attackerType) {
  12035. if (!!!bestBattle.recovery) {
  12036. bestBattle.recovery = -11;
  12037. let selectedTeamNum = -1;
  12038. for (let attempt = 0; selectedTeamNum < 0 && attempt < 4; attempt++) {
  12039. selectedTeamNum = await attemptAttackEarthOrFire(teamNum, attackerType, attempt);
  12040. }
  12041. if (selectedTeamNum < 0) {
  12042. endDungeon('Невозможно победить без потери Титана!', attackerType);
  12043. return;
  12044. }
  12045. }
  12046. return findAttack(teamNum, attackerType, bestBattle.team);
  12047. }
  12048.  
  12049. /** Находим подходящий результат для атаки */
  12050. async function findAttack(teamNum, attackerType, team) {
  12051. let start = new Date();
  12052. let recovery = -1000;
  12053. let iterations = 0;
  12054. let result;
  12055. let correction = 0.01;
  12056. for (let needRecovery = bestBattle.recovery; recovery < needRecovery; needRecovery -= correction, iterations++) {
  12057. result = await startBattle(teamNum, attackerType, team);
  12058. recovery = getRecovery(result);
  12059. }
  12060. bestBattle.recovery = recovery;
  12061. let workTime = new Date().getTime() - start.getTime();
  12062. timeDungeon.findAttack += workTime;
  12063. return result;
  12064. }
  12065.  
  12066. /** Атакуем Нейтральной командой */
  12067. async function attackNeutral(teamNum, attackerType) {
  12068. let start = new Date();
  12069. let factors = calcFactor();
  12070. bestBattle.recovery = -0.2;
  12071. await findBestBattleNeutral(teamNum, attackerType, factors, true)
  12072. if (bestBattle.recovery < 0 || (bestBattle.recovery < 0.2 && factors[0].value < 0.5)) {
  12073. let recovery = 100 * bestBattle.recovery;
  12074. console.log("Не удалось найти удачный бой в быстром режиме: " + attackerType +
  12075. ", recovery = " + (recovery > 0 ? "+" : "") + Math.round(recovery) + "% \r\n", bestBattle.attackers);
  12076. await findBestBattleNeutral(teamNum, attackerType, factors, false)
  12077. }
  12078. let workTime = new Date().getTime() - start.getTime();
  12079. timeDungeon.attackNeutral += workTime;
  12080. if (!!bestBattle.attackers) {
  12081. let team = getTeam(bestBattle.attackers);
  12082. return findAttack(teamNum, attackerType, team);
  12083. }
  12084. endDungeon('Не удалось найти удачный бой!', attackerType);
  12085. return undefined;
  12086. }
  12087.  
  12088. /** Находит лучшую нейтральную команду */
  12089. async function findBestBattleNeutral(teamNum, attackerType, factors, mode) {
  12090. let countFactors = factors.length < 4 ? factors.length : 4;
  12091. let aradgi = !titansStates['4013']?.isDead;
  12092. let edem = !titansStates['4023']?.isDead;
  12093. let dark = [4032, 4033].filter(e => !titansStates[e]?.isDead);
  12094. let light = [4042].filter(e => !titansStates[e]?.isDead);
  12095. let actions = [];
  12096. if (mode) {
  12097. for (let i = 0; i < countFactors; i++) {
  12098. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(factors[i].id)));
  12099. }
  12100. if (countFactors > 1) {
  12101. let firstId = factors[0].id;
  12102. let secondId = factors[1].id;
  12103. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4001, secondId)));
  12104. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4002, secondId)));
  12105. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4003, secondId)));
  12106. }
  12107. if (aradgi) {
  12108. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(4013)));
  12109. if (countFactors > 0) {
  12110. let firstId = factors[0].id;
  12111. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4000, 4013)));
  12112. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4001, 4013)));
  12113. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4002, 4013)));
  12114. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4003, 4013)));
  12115. }
  12116. if (edem) {
  12117. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(4023, 4000, 4013)));
  12118. }
  12119. }
  12120. } else {
  12121. if (mode) {
  12122. for (let i = 0; i < factors.length; i++) {
  12123. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(factors[i].id)));
  12124. }
  12125. } else {
  12126. countFactors = factors.length < 2 ? factors.length : 2;
  12127. }
  12128. for (let i = 0; i < countFactors; i++) {
  12129. let mainId = factors[i].id;
  12130. if (aradgi && (mode || i > 0)) {
  12131. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4000, 4013)));
  12132. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4001, 4013)));
  12133. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4002, 4013)));
  12134. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4003, 4013)));
  12135. }
  12136. for (let i = 0; i < dark.length; i++) {
  12137. let darkId = dark[i];
  12138. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4001, darkId)));
  12139. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4002, darkId)));
  12140. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4003, darkId)));
  12141. }
  12142. for (let i = 0; i < light.length; i++) {
  12143. let lightId = light[i];
  12144. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4001, lightId)));
  12145. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4002, lightId)));
  12146. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4003, lightId)));
  12147. }
  12148. let isFull = mode || i > 0;
  12149. for (let j = isFull ? i + 1 : 2; j < factors.length; j++) {
  12150. let extraId = factors[j].id;
  12151. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4000, extraId)));
  12152. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4001, extraId)));
  12153. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4002, extraId)));
  12154. }
  12155. }
  12156. if (aradgi) {
  12157. if (mode) {
  12158. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(4013)));
  12159. }
  12160. for (let i = 0; i < dark.length; i++) {
  12161. let darkId = dark[i];
  12162. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(darkId, 4001, 4013)));
  12163. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(darkId, 4002, 4013)));
  12164. }
  12165. for (let i = 0; i < light.length; i++) {
  12166. let lightId = light[i];
  12167. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(lightId, 4001, 4013)));
  12168. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(lightId, 4002, 4013)));
  12169. }
  12170. }
  12171. for (let i = 0; i < dark.length; i++) {
  12172. let firstId = dark[i];
  12173. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId)));
  12174. for (let j = i + 1; j < dark.length; j++) {
  12175. let secondId = dark[j];
  12176. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4001, secondId)));
  12177. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4002, secondId)));
  12178. }
  12179. }
  12180. for (let i = 0; i < light.length; i++) {
  12181. let firstId = light[i];
  12182. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId)));
  12183. for (let j = i + 1; j < light.length; j++) {
  12184. let secondId = light[j];
  12185. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4001, secondId)));
  12186. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4002, secondId)));
  12187. }
  12188. }
  12189. }
  12190. for (let result of await Promise.all(actions)) {
  12191. let recovery = getRecovery(result);
  12192. if (recovery > bestBattle.recovery) {
  12193. bestBattle.recovery = recovery;
  12194. bestBattle.attackers = result.progress[0].attackers.heroes;
  12195. }
  12196. }
  12197. }
  12198.  
  12199. /** Получаем нейтральную команду */
  12200. function getNeutralTeam(id, swapId, addId) {
  12201. let neutralTeam = clone(teams.water);
  12202. let neutral = neutralTeam.heroes;
  12203. if (neutral.length == 4) {
  12204. if (!!swapId) {
  12205. for (let i in neutral) {
  12206. if (neutral[i] == swapId) {
  12207. neutral[i] = addId;
  12208. }
  12209. }
  12210. }
  12211. } else if (!!addId) {
  12212. neutral.push(addId);
  12213. }
  12214. neutral.push(id);
  12215. return neutralTeam;
  12216. }
  12217.  
  12218. /** Получить команду титанов */
  12219. function getTeam(titans) {
  12220. return {
  12221. favor: {},
  12222. heroes: Object.keys(titans).map(id => parseInt(id)),
  12223. teamNum: 0,
  12224. };
  12225. }
  12226.  
  12227. /** Вычисляем фактор боеготовности титанов */
  12228. function calcFactor() {
  12229. let neutral = teams.neutral;
  12230. let factors = [];
  12231. for (let i in neutral) {
  12232. let titanId = neutral[i];
  12233. let titan = titansStates[titanId];
  12234. let factor = !!titan ? titan.hp / titan.maxHp + titan.energy / 10000.0 : 1;
  12235. if (factor > 0) {
  12236. factors.push({id: titanId, value: factor});
  12237. }
  12238. }
  12239. factors.sort(function(a, b) {
  12240. return a.value - b.value;
  12241. });
  12242. return factors;
  12243. }
  12244.  
  12245. /** Возвращает наилучший результат из нескольких боев */
  12246. async function getBestRecovery(teamNum, attackerType, team, countBattle) {
  12247. let bestRecovery = -1000;
  12248. let actions = [];
  12249. for (let i = 0; i < countBattle; i++) {
  12250. actions.push(startBattle(teamNum, attackerType, team));
  12251. }
  12252. for (let result of await Promise.all(actions)) {
  12253. let recovery = getRecovery(result);
  12254. if (recovery > bestRecovery) {
  12255. bestRecovery = recovery;
  12256. }
  12257. }
  12258. return bestRecovery;
  12259. }
  12260.  
  12261. /** Возвращает разницу в здоровье атакующей команды после и до битвы и проверяет здоровье титанов на необходимый минимум*/
  12262. function getRecovery(result) {
  12263. if (result.result.stars < 3) {
  12264. return -100;
  12265. }
  12266. let beforeSumFactor = 0;
  12267. let afterSumFactor = 0;
  12268. let beforeTitans = result.battleData.attackers;
  12269. let afterTitans = result.progress[0].attackers.heroes;
  12270. for (let i in afterTitans) {
  12271. let titan = afterTitans[i];
  12272. let percentHP = titan.hp / beforeTitans[i].hp;
  12273. let energy = titan.energy;
  12274. let factor = checkTitan(i, energy, percentHP) ? getFactor(i, energy, percentHP) : -100;
  12275. afterSumFactor += factor;
  12276. }
  12277. for (let i in beforeTitans) {
  12278. let titan = beforeTitans[i];
  12279. let state = titan.state;
  12280. beforeSumFactor += !!state ? getFactor(i, state.energy, state.hp / titan.hp) : 1;
  12281. }
  12282. return afterSumFactor - beforeSumFactor;
  12283. }
  12284.  
  12285. /** Возвращает состояние титана*/
  12286. function getFactor(id, energy, percentHP) {
  12287. let elemantId = id.slice(2, 3);
  12288. let isEarthOrFire = elemantId == '1' || elemantId == '2';
  12289. let energyBonus = id == '4020' && energy == 1000 ? 0.1 : energy / 20000.0;
  12290. let factor = percentHP + energyBonus;
  12291. return isEarthOrFire ? factor : factor / 10;
  12292. }
  12293.  
  12294. /** Проверяет состояние титана*/
  12295. function checkTitan(id, energy, percentHP) {
  12296. switch (id) {
  12297. case '4020':
  12298. return percentHP > 0.25 || (energy == 1000 && percentHP > 0.05);
  12299. break;
  12300. case '4010':
  12301. return percentHP + energy / 2000.0 > 0.63;
  12302. break;
  12303. case '4000':
  12304. return percentHP > 0.62 || (energy < 1000 && (
  12305. (percentHP > 0.45 && energy >= 400) ||
  12306. (percentHP > 0.3 && energy >= 670)));
  12307. }
  12308. return true;
  12309. }
  12310.  
  12311.  
  12312. /** Начинаем бой */
  12313. function startBattle(teamNum, attackerType, args) {
  12314. return new Promise(function (resolve, reject) {
  12315. args.teamNum = teamNum;
  12316. let startBattleCall = {
  12317. calls: [{
  12318. name: "dungeonStartBattle",
  12319. args,
  12320. ident: "body"
  12321. }]
  12322. }
  12323. send(JSON.stringify(startBattleCall), resultBattle, {
  12324. resolve,
  12325. teamNum,
  12326. attackerType
  12327. });
  12328. });
  12329. }
  12330.  
  12331. /** Возращает результат боя в промис */
  12332. /*function resultBattle(resultBattles, args) {
  12333. if (!!resultBattles && !!resultBattles.results) {
  12334. let battleData = resultBattles.results[0].result.response;
  12335. let battleType = "get_tower";
  12336. if (battleData.type == "dungeon_titan") {
  12337. battleType = "get_titan";
  12338. }
  12339. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];//тест подземка правки
  12340. BattleCalc(battleData, battleType, function (result) {
  12341. result.teamNum = args.teamNum;
  12342. result.attackerType = args.attackerType;
  12343. args.resolve(result);
  12344. });
  12345. } else {
  12346. endDungeon('Потеряна связь с сервером игры!', 'break');
  12347. }
  12348. }*/
  12349. function resultBattle(resultBattles, args) {
  12350. battleData = resultBattles.results[0].result.response;
  12351. battleType = "get_tower";
  12352. if (battleData.type == "dungeon_titan") {
  12353. battleType = "get_titan";
  12354. }
  12355. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  12356. BattleCalc(battleData, battleType, function (result) {
  12357. result.teamNum = args.teamNum;
  12358. result.attackerType = args.attackerType;
  12359. args.resolve(result);
  12360. });
  12361. }
  12362.  
  12363. /** Заканчиваем бой */
  12364.  
  12365. ////
  12366. async function endBattle(battleInfo) {
  12367. if (!!battleInfo) {
  12368. const args = {
  12369. result: battleInfo.result,
  12370. progress: battleInfo.progress,
  12371. }
  12372. if (battleInfo.result.stars < 3) {
  12373. endDungeon('Герой или Титан мог погибнуть в бою!', battleInfo);
  12374. return;
  12375. }
  12376. if (countPredictionCard > 0) {
  12377. args.isRaid = true;
  12378. } else {
  12379. const timer = getTimer(battleInfo.battleTime);
  12380. console.log(timer);
  12381. await countdownTimer(timer, `${I18N('DUNGEON2')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity}`);
  12382. }
  12383. const calls = [{
  12384. name: "dungeonEndBattle",
  12385. args,
  12386. ident: "body"
  12387. }];
  12388. lastDungeonBattleData = null;
  12389. send(JSON.stringify({ calls }), resultEndBattle);
  12390. } else {
  12391. endDungeon('dungeonEndBattle win: false\n', battleInfo);
  12392. }
  12393. }
  12394. /** Получаем и обрабатываем результаты боя */
  12395. function resultEndBattle(e) {
  12396. if (!!e && !!e.results) {
  12397. let battleResult = e.results[0].result.response;
  12398. if ('error' in battleResult) {
  12399. endDungeon('errorBattleResult', battleResult);
  12400. return;
  12401. }
  12402. let dungeonGetInfo = battleResult.dungeon ?? battleResult;
  12403. dungeonActivity += battleResult.reward.dungeonActivity ?? 0;
  12404. checkFloor(dungeonGetInfo);
  12405. } else {
  12406. endDungeon('Потеряна связь с сервером игры!', 'break');
  12407. }
  12408. }
  12409.  
  12410. /** Добавить команду титанов в общий список команд */
  12411. function addTeam(team) {
  12412. for (let i in countTeam) {
  12413. if (equalsTeam(countTeam[i].team, team)) {
  12414. countTeam[i].count++;
  12415. return;
  12416. }
  12417. }
  12418. countTeam.push({team: team, count: 1});
  12419. }
  12420.  
  12421. /** Сравнить команды на равенство */
  12422. function equalsTeam(team1, team2) {
  12423. if (team1.length == team2.length) {
  12424. for (let i in team1) {
  12425. if (team1[i] != team2[i]) {
  12426. return false;
  12427. }
  12428. }
  12429. return true;
  12430. }
  12431. return false;
  12432. }
  12433.  
  12434. function saveProgress() {
  12435. let saveProgressCall = {
  12436. calls: [{
  12437. name: "dungeonSaveProgress",
  12438. args: {},
  12439. ident: "body"
  12440. }]
  12441. }
  12442. send(JSON.stringify(saveProgressCall), resultEndBattle);
  12443. }
  12444.  
  12445.  
  12446. /** Выводит статистику прохождения подземелья */
  12447. function showStats() {
  12448. let activity = dungeonActivity - startDungeonActivity;
  12449. let workTime = clone(timeDungeon);
  12450. workTime.all = new Date().getTime() - workTime.all;
  12451. for (let i in workTime) {
  12452. workTime[i] = (workTime[i] / 1000).round(0);
  12453. }
  12454. countTeam.sort(function(a, b) {
  12455. return b.count - a.count;
  12456. });
  12457. console.log(titansStates);
  12458. console.log("Собрано титанита: ", activity);
  12459. console.log("Скорость сбора: " + (3600 * activity / workTime.all).round(0) + " титанита/час");
  12460. console.log("Время раскопок: ");
  12461. for (let i in workTime) {
  12462. let timeNow = workTime[i];
  12463. console.log(i + ": ", (timeNow / 3600).round(0) + " ч. " + (timeNow % 3600 / 60).round(0) + " мин. " + timeNow % 60 + " сек.");
  12464. }
  12465. console.log("Частота использования команд: ");
  12466. for (let i in countTeam) {
  12467. let teams = countTeam[i];
  12468. console.log(teams.team + ": ", teams.count);
  12469. }
  12470. }
  12471.  
  12472. /** Заканчиваем копать подземелье */
  12473. function endDungeon(reason, info) {
  12474. if (!end) {
  12475. end = true;
  12476. console.log(reason, info);
  12477. showStats();
  12478. if (info == 'break') {
  12479. setProgress('Dungeon stoped: Титанит ' + dungeonActivity + '/' + maxDungeonActivity +
  12480. "\r\nПотеряна связь с сервером игры!", false, hideProgress);
  12481. } else {
  12482. setProgress('Dungeon completed: Титанит ' + dungeonActivity + '/' + maxDungeonActivity, false, hideProgress);
  12483. }
  12484. setTimeout(cheats.refreshGame, 1000);
  12485. resolve();
  12486. }
  12487. }
  12488. }
  12489.  
  12490. //дарим подарки участникам других гильдий не выходя из своей гильдии
  12491. function NewYearGift_Clan() {
  12492. console.log('NewYearGift_Clan called...');
  12493. const userID = getInput('userID');
  12494. const AmontID = getInput('AmontID');
  12495. const GiftNum = getInput('GiftNum');
  12496.  
  12497. const data = {
  12498. "calls": [{
  12499. "name": "newYearGiftSend",
  12500. "args": {
  12501. "userId": userID,
  12502. "amount": AmontID,
  12503. "giftNum": GiftNum,
  12504. "users": {
  12505. [userID]: AmontID
  12506. }
  12507. },
  12508. "ident": "body"
  12509. }
  12510. ]
  12511. }
  12512.  
  12513. const dataJson = JSON.stringify(data);
  12514.  
  12515. SendRequest(dataJson, e => {
  12516. let userInfo = e.results[0].result.response;
  12517. console.log(userInfo);
  12518. });
  12519. setProgress(I18N('SEND_GIFT'), true);
  12520. }
  12521. })();
  12522.  
  12523. /**
  12524. * TODO:
  12525. * Получение всех уровней при сборе всех наград (квест на титанит и на энку) +-
  12526. * Добивание на арене титанов
  12527. * Закрытие окошек по Esc +-
  12528. * Починить работу скрипта на уровне команды ниже 10 +-
  12529. * Написать номальную синхронизацию
  12530. * Добавить дополнительные настройки автопокупки в "Тайном богатстве"
  12531. */

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址