Advertisement
Dapi34

Bot Steam 2018

Jun 24th, 2018
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 26.62 KB | None | 0 0
  1. // This is the zone you want to attack (Optional, otherwise picks one for you).
  2. var target_zone = -1;
  3.  
  4. // Variables. Don't change these unless you know what you're doing.
  5. var real_round_length = 120; // Round Length of a real game (In Seconds, for calculating score)
  6. var resend_frequency = 110; // Frequency at which we can say we finished a round (May be different than real length)
  7. var update_length = 1; // How long to wait between updates (In Seconds)
  8. var loop_rounds = true;
  9. var language = "english"; // Used when POSTing scores
  10. var access_token = "";
  11. var current_game_id = undefined;
  12. var current_game_start = undefined; // Timestamp for when the current game started
  13. var time_passed_ms = 0;
  14. var current_timeout = undefined;
  15. var max_retry = 5; // Max number of retries to send requests
  16. var auto_first_join = true; // Automatically join the best zone at first
  17. var current_planet_id = undefined;
  18. var auto_switch_planet = {
  19. "active": false, // Automatically switch to the best planet available (true : yes, false : no)
  20. "current_difficulty": undefined,
  21. "wanted_difficulty": 3, // Difficulty prefered. Will check planets if the current one differs
  22. "rounds_before_check": 5, // If we're not in a wanted difficulty zone, we start a planets check in this amount of rounds
  23. "current_round": 0,
  24. "coeffScore": {
  25. 1: 1,
  26. 2: 100,
  27. 3: 10000
  28. }
  29. };
  30.  
  31. class BotGUI {
  32. constructor(state) {
  33. console.log('GUI Has been created');
  34.  
  35. this.state = state;
  36.  
  37. this.createStatusWindow();
  38. this.createProgressBar();
  39. }
  40.  
  41. createStatusWindow() {
  42. if(document.getElementById('salienbot_gui')) {
  43. return false;
  44. }
  45.  
  46. var $statusWindow = $J([
  47. '<div id="salienbot_gui" style="background: #191919; z-index: 1; border: 3px solid #83d674; padding: 20px; margin: 15px; width: 300px; transform: translate(0, 0);">',
  48. '<h1><a href="https://github.com/ensingm2/saliengame_idler/">Salien Game Idler</a></h1>',
  49. '<p style="margin-top: -.8em; font-size: .75em"><span id="salienbot_status"></span></p>', // Running or stopped
  50. '<p><b>Task:</b> <span id="salienbot_task">Initializing</span></p>', // Current task
  51. `<p><b>Target Zone:</b> <span id="salienbot_zone">None</span></p>`,
  52. `<p style="display: none;" id="salienbot_zone_difficulty_div"><b>Zone Difficulty:</b> <span id="salienbot_zone_difficulty"></span></p>`,
  53. '<p><b>Level:</b> <span id="salienbot_level">' + this.state.level + '</span> &nbsp;&nbsp;&nbsp;&nbsp; <b>EXP:</b> <span id="salienbot_exp">' + this.state.exp + '</span></p>',
  54. '<p><b>Lvl Up In:</b> <span id="salienbot_esttimlvl"></span></p>',
  55. '<p><input id="disableAnimsBtn" type="button" onclick="INJECT_disable_animations()" value="Disable Animations"/></p>',
  56. '</div>'
  57. ].join(''))
  58.  
  59. $J('#salien_game_placeholder').append( $statusWindow )
  60. }
  61.  
  62. createProgressBar() {
  63. this.progressbar = new CProgressBar(63);
  64. this.progressbar.x = 2
  65. this.progressbar.y = 48
  66. }
  67.  
  68. updateStatus(running) {
  69. const statusTxt = running ? '<span style="color: green;">✓ Running</span>' : '<span style="color: red;">✗ Stopped</span>';
  70.  
  71. $J('#salienbot_status').html(statusTxt);
  72. }
  73.  
  74. updateTask(status, log_to_console) {
  75. if(log_to_console || log_to_console === undefined)
  76. console.log(status);
  77. document.getElementById('salienbot_task').innerText = status;
  78. }
  79.  
  80. updateExp(exp) {
  81. document.getElementById('salienbot_exp').innerText = exp;
  82. }
  83.  
  84. updateLevel(level) {
  85. document.getElementById('salienbot_level').innerText = level;
  86. }
  87.  
  88. updateEstimatedTime(secondsLeft) {
  89. let date = new Date(null);
  90. date.setSeconds(secondsLeft);
  91. var result = date.toISOString().substr(8, 11).split(/[T:]/);
  92.  
  93. var days = result[0]-1;
  94. var hours = result[1];
  95. var minutes = result[2];
  96. var seconds = result[3];
  97.  
  98. var timeTxt = "";
  99. if(days > 0)
  100. timeTxt += days + "d ";
  101. if(hours > 0 || timeTxt.length > 0)
  102. timeTxt += hours + "h ";
  103. if(minutes > 0 || timeTxt.length > 0)
  104. timeTxt += minutes + "m ";
  105.  
  106. timeTxt += seconds + "s";
  107.  
  108. document.getElementById('salienbot_esttimlvl').innerText = timeTxt;
  109. }
  110.  
  111. updateZone(zone, progress, difficulty) {
  112. var printString = zone;
  113. if(progress !== undefined)
  114. printString += " (" + (progress * 100).toFixed(2) + "% Complete)"
  115. if(progress === undefined) {
  116. $J("#salienbot_zone_difficulty_div").hide();
  117. difficulty = "";
  118. }
  119. else {
  120. $J("#salienbot_zone_difficulty_div").show();
  121. gGame.m_State.m_Grid.m_Tiles[target_zone].addChild(this.progressbar)
  122. }
  123.  
  124. document.getElementById('salienbot_zone').innerText = printString;
  125. document.getElementById('salienbot_zone_difficulty').innerText = difficulty;
  126. }
  127. };
  128.  
  129. var gui = new BotGUI({
  130. level: gPlayerInfo.level,
  131. exp: gPlayerInfo.score
  132. });
  133.  
  134. function calculateTimeToNextLevel() {
  135. const nextScoreAmount = get_max_score(target_zone);
  136. const missingExp = Math.ceil((gPlayerInfo.next_level_score - gPlayerInfo.score) / nextScoreAmount) * nextScoreAmount;
  137. const roundTime = resend_frequency + update_length;
  138.  
  139. const secondsLeft = missingExp / nextScoreAmount * roundTime - time_passed_ms / 1000;
  140.  
  141. return secondsLeft;
  142. }
  143.  
  144. // Handle AJAX errors to avoid the script to be locked by a single API error
  145. function ajaxErrorHandling(ajaxObj, params, messagesArray) {
  146. ajaxObj.tryCount++;
  147. if (ajaxObj.tryCount <= ajaxObj.retryLimit) {
  148. var currentTask = "Retrying in 5s to " + messagesArray[0] + " (Retry #" + ajaxObj.tryCount + "). Error: " + params.xhr.status + ": " + params.thrownError;
  149. gui.updateTask(currentTask);
  150. setTimeout(function() { $J.ajax(ajaxObj); }, 5000);
  151. return;
  152. }
  153. var currentTask = "Error " + messagesArray[1] + ": " + params.xhr.status + ": " + params.thrownError + " (Max retries reached).";
  154. gui.updateTask(currentTask);
  155. return;
  156. }
  157.  
  158. // Grab the user's access token
  159. var INJECT_get_access_token = function() {
  160. $J.ajax({
  161. async: false,
  162. type: "GET",
  163. url: "https://steamcommunity.com/saliengame/gettoken",
  164. success: function(data) {
  165. if(data.token != undefined) {
  166. console.log("Got access token: " + data.token);
  167. access_token = data.token;
  168. }
  169. else {
  170. console.log("Failed to retrieve access token.")
  171. access_token = undefined;
  172. }
  173. }
  174. });
  175. }
  176.  
  177. // Make the call to start a round, and kick-off the idle process
  178. var INJECT_start_round = function(zone, access_token, attempt_no) {
  179. if(attempt_no === undefined)
  180. attempt_no = 0;
  181.  
  182. // Leave the game if we're already in one.
  183. if(current_game_id !== undefined) {
  184. gui.updateTask("Previous game detected. Ending it.", true);
  185. INJECT_leave_round();
  186. }
  187.  
  188. // Send the POST to join the game.
  189. $J.ajax({
  190. async: false,
  191. type: "POST",
  192. url: "https://community.steam-api.com/ITerritoryControlMinigameService/JoinZone/v0001/",
  193. data: { access_token: access_token, zone_position: zone },
  194. tryCount : 0,
  195. retryLimit : max_retry,
  196. success: function(data) {
  197. if( $J.isEmptyObject(data.response) ) {
  198. // Check if the zone is completed
  199. INJECT_update_grid();
  200. if(window.gGame.m_State.m_Grid.m_Tiles[target_zone].Info.captured || attempt_no >= max_retry) {
  201. if (auto_switch_planet.active == true)
  202. CheckSwitchBetterPlanet();
  203. else
  204. SwitchNextZone();
  205. }
  206. else {
  207. console.log("Error getting zone response:",data);
  208. gui.updateTask("Waiting 5s and re-sending join attempt(Attempt #" + attempt_no + ").");
  209. setTimeout(function() { INJECT_start_round(zone, access_token, attempt_no+1); }, 5000);
  210. }
  211. }
  212. else {
  213. console.log("Round successfully started in zone #" + zone);
  214. console.log(data);
  215.  
  216. // Set target
  217. target_zone = zone;
  218.  
  219. if (auto_switch_planet.active == true) {
  220. if (auto_switch_planet.current_difficulty != data.response.zone_info.difficulty)
  221. auto_switch_planet.current_round = 0; // Difficulty changed, reset rounds counter before new planet check
  222. auto_switch_planet.current_difficulty = data.response.zone_info.difficulty;
  223. if (auto_switch_planet.current_difficulty < auto_switch_planet.wanted_difficulty) {
  224. if (auto_switch_planet.current_round >= auto_switch_planet.rounds_before_check) {
  225. auto_switch_planet.current_round = 0;
  226. CheckSwitchBetterPlanet(true);
  227. } else {
  228. auto_switch_planet.current_round++;
  229. }
  230. }
  231. }
  232.  
  233. // Update the GUI
  234. gui.updateStatus(true);
  235. gui.updateZone(zone, data.response.zone_info.capture_progress, data.response.zone_info.difficulty);
  236. gui.updateEstimatedTime(calculateTimeToNextLevel());
  237.  
  238. current_game_id = data.response.zone_info.gameid;
  239. current_game_start = new Date().getTime();
  240. INJECT_wait_for_end(resend_frequency);
  241. }
  242. },
  243. error: function (xhr, ajaxOptions, thrownError) {
  244. var messagesArray = ["start the round", "starting round"];
  245. var ajaxParams = {
  246. xhr: xhr,
  247. ajaxOptions: ajaxOptions,
  248. thrownError: thrownError
  249. };
  250. ajaxErrorHandling(this, ajaxParams, messagesArray);
  251. }
  252. });
  253. }
  254.  
  255. // Update time remaining, and wait for the round to complete.
  256. var INJECT_wait_for_end = function() {
  257. var now = new Date().getTime();
  258. time_passed_ms = now - current_game_start;
  259. var time_remaining_ms = (resend_frequency*1000) - time_passed_ms;
  260. var time_remaining = Math.round(time_remaining_ms/1000);
  261.  
  262. // Update GUI
  263. gui.updateTask("Waiting " + Math.max(time_remaining, 0) + "s for round to end", false);
  264. gui.updateStatus(true);
  265. gui.updateEstimatedTime(calculateTimeToNextLevel())
  266. gui.progressbar.SetValue(time_passed_ms/(resend_frequency*1000))
  267.  
  268. // Wait
  269. var wait_time = update_length*1000;;
  270. var callback;
  271.  
  272. // use absolute timestamps to calculate if the game is over, since setTimeout timings are not always reliable
  273. if(time_remaining_ms <= 0) {
  274. callback = function() { INJECT_end_round(); };
  275. }
  276. else {
  277. callback = function() { INJECT_wait_for_end(); };
  278. }
  279.  
  280. // Set the timeout
  281. current_timeout = setTimeout(callback, wait_time);
  282. }
  283.  
  284. // Send the call to end a round, and restart if needed.
  285. var INJECT_end_round = function(attempt_no) {
  286. if(attempt_no === undefined)
  287. attempt_no = 0;
  288.  
  289. // Grab the max score we're allowed to send
  290. var score = get_max_score();
  291.  
  292. // Update gui
  293. gui.updateTask("Ending Round");
  294.  
  295. // Post our "Yay we beat the level" call
  296. $J.ajax({
  297. async: false,
  298. type: "POST",
  299. url: "https://community.steam-api.com/ITerritoryControlMinigameService/ReportScore/v0001/",
  300. data: { access_token: access_token, score: score, language: language },
  301. tryCount : 0,
  302. retryLimit : max_retry,
  303. success: function(data) {
  304. if( $J.isEmptyObject(data.response) ) {
  305. // Check if the zone is completed
  306. INJECT_update_grid();
  307. if(window.gGame.m_State.m_Grid.m_Tiles[target_zone].Info.captured || attempt_no >= max_retry) {
  308. if (auto_switch_planet.active == true)
  309. CheckSwitchBetterPlanet();
  310. else
  311. SwitchNextZone();
  312. }
  313. else {
  314. console.log("Error getting zone response:",data);
  315. gui.updateTask("Waiting 5s and re-sending score(Attempt #" + attempt_no + ").");
  316. setTimeout(function() { INJECT_end_round(attempt_no+1); }, 5000);
  317. }
  318. }
  319. else {
  320. console.log("Successfully finished the round and got expected data back:");
  321. console.log("Level: ", data.response.new_level, "\nEXP: ", data.response.new_score);
  322. console.log(data);
  323.  
  324. gui.updateLevel(data.response.new_level);
  325. gui.updateExp(data.response.new_score);
  326. // When we get a new EXP we also want to recalculate the time for next level.
  327. gui.updateEstimatedTime(calculateTimeToNextLevel())
  328.  
  329. // Update the player info in the UI
  330. INJECT_update_player_info();
  331.  
  332. // Update the GUI
  333. window.gui.updateZone("None");
  334.  
  335. // Restart the round if we have that variable set
  336. if(loop_rounds) {
  337. UpdateNotificationCounts();
  338. current_game_id = undefined;
  339. INJECT_start_round(target_zone, access_token)
  340. }
  341. }
  342. },
  343. error: function (xhr, ajaxOptions, thrownError) {
  344. var messagesArray = ["end the round", "ending round"];
  345. var ajaxParams = {
  346. xhr: xhr,
  347. ajaxOptions: ajaxOptions,
  348. thrownError: thrownError
  349. };
  350. ajaxErrorHandling(this, ajaxParams, messagesArray);
  351. }
  352. });
  353. }
  354.  
  355. // Leave an existing game
  356. var INJECT_leave_round = function() {
  357. if(current_game_id === undefined)
  358. return;
  359.  
  360. console.log("Leaving game: " + current_game_id);
  361.  
  362. // Cancel timeouts
  363. clearTimeout(current_timeout);
  364.  
  365. // POST to the endpoint
  366. $J.ajax({
  367. async: false,
  368. type: "POST",
  369. url: "https://community.steam-api.com/IMiniGameService/LeaveGame/v0001/",
  370. data: { access_token: access_token, gameid: current_game_id },
  371. tryCount : 0,
  372. retryLimit : max_retry,
  373. success: function(data) {},
  374. error: function (xhr, ajaxOptions, thrownError) {
  375. var messagesArray = ["leave the round", "leaving round"];
  376. var ajaxParams = {
  377. xhr: xhr,
  378. ajaxOptions: ajaxOptions,
  379. thrownError: thrownError
  380. };
  381. ajaxErrorHandling(this, ajaxParams, messagesArray);
  382. }
  383. });
  384.  
  385. // Clear the current game ID var
  386. current_game_id = undefined;
  387.  
  388. // Update the GUI
  389. gui.updateTask("Left Zone #" + target_zone);
  390. gui.updateStatus(false);
  391.  
  392. target_zone = -1;
  393. }
  394.  
  395. // returns 0 for easy, 1 for medium, 2 for hard
  396. var INJECT_get_difficulty = function(zone_id) {
  397. return window.gGame.m_State.m_PlanetData.zones[zone_id].difficulty;
  398. }
  399.  
  400. // Updates the player info
  401. // Currently unused. This was meant to hopefully update the UI.
  402. var INJECT_update_player_info = function() {
  403. gServer.GetPlayerInfo(
  404. function( results ) {
  405. gPlayerInfo = results.response;
  406. },
  407. function(){}
  408. );
  409. }
  410.  
  411. // Update the zones of the grid (map) on the current planet
  412. var INJECT_update_grid = function() {
  413. if(current_planet_id === undefined)
  414. return;
  415.  
  416. gui.updateTask('Updating grid', true);
  417.  
  418. // GET to the endpoint
  419. $J.ajax({
  420. async: false,
  421. type: "GET",
  422. url: "https://community.steam-api.com/ITerritoryControlMinigameService/GetPlanet/v0001/",
  423. data: { id: current_planet_id },
  424. tryCount : 0,
  425. retryLimit : max_retry,
  426. success: function(data) {
  427. window.gGame.m_State.m_PlanetData = data.response.planets[0];
  428. window.gGame.m_State.m_PlanetData.zones.forEach( function ( zone ) {
  429. window.gGame.m_State.m_Grid.m_Tiles[zone.zone_position].Info.progress = zone.capture_progress;
  430. window.gGame.m_State.m_Grid.m_Tiles[zone.zone_position].Info.captured = zone.captured;
  431. window.gGame.m_State.m_Grid.m_Tiles[zone.zone_position].Info.difficulty = zone.difficulty;
  432. });
  433. console.log("Successfully updated map data on planet: " + current_planet_id);
  434. },
  435. error: function (xhr, ajaxOptions, thrownError) {
  436. var messagesArray = ["update the grid", "updating the grid"];
  437. var ajaxParams = {
  438. xhr: xhr,
  439. ajaxOptions: ajaxOptions,
  440. thrownError: thrownError
  441. };
  442. ajaxErrorHandling(this, ajaxParams, messagesArray);
  443. }
  444. });
  445. }
  446.  
  447. // Defaults to max score of current zone & full round duration if no params are given
  448. function get_max_score(zone, round_duration) {
  449. // defaults
  450. if(zone === undefined)
  451. zone = target_zone;
  452. if(round_duration === undefined)
  453. round_duration = real_round_length;
  454.  
  455. var difficulty = INJECT_get_difficulty(zone);
  456. var score = 5 * round_duration * Math.pow(2, (difficulty-1));
  457.  
  458. return score;
  459. }
  460.  
  461. // Get the best zone available
  462. function GetBestZone() {
  463. var bestZoneIdx;
  464. var highestDifficulty = -1;
  465.  
  466. gui.updateTask('Getting best zone');
  467.  
  468. for (var idx = 0; idx < window.gGame.m_State.m_Grid.m_Tiles.length; idx++) {
  469. var zone = window.gGame.m_State.m_Grid.m_Tiles[idx].Info;
  470. if (!zone.captured) {
  471. if (zone.boss) {
  472. console.log("Zone " + idx + " with boss. Switching to it.");
  473. return idx;
  474. }
  475.  
  476. if(zone.difficulty > highestDifficulty) {
  477. highestDifficulty = zone.difficulty;
  478. maxProgress = zone.progress;
  479. bestZoneIdx = idx;
  480. } else if(zone.difficulty < highestDifficulty) continue;
  481.  
  482. if(zone.progress < maxProgress) {
  483. maxProgress = zone.progress;
  484. bestZoneIdx = idx;
  485. }
  486. }
  487. }
  488.  
  489. if(bestZoneIdx !== undefined) {
  490. console.log(`${window.gGame.m_State.m_PlanetData.state.name} - Zone ${bestZoneIdx} Progress: ${window.gGame.m_State.m_Grid.m_Tiles[bestZoneIdx].Info.progress} Difficulty: ${window.gGame.m_State.m_Grid.m_Tiles[bestZoneIdx].Info.difficulty}`);
  491. }
  492.  
  493. return bestZoneIdx;
  494. }
  495.  
  496. // Get the best planet available
  497. function GetBestPlanet() {
  498. var bestPlanetId = undefined;
  499. var activePlanetsScore = [];
  500. var maxScore = 0;
  501. var numberErrors = 0;
  502.  
  503. gui.updateStatus('Getting best planet');
  504.  
  505. // GET to the endpoint
  506. $J.ajax({
  507. async: false,
  508. type: "GET",
  509. url: "https://community.steam-api.com/ITerritoryControlMinigameService/GetPlanets/v0001/",
  510. tryCount : 0,
  511. retryLimit : max_retry,
  512. success: function(data) {
  513. data.response.planets.forEach( function(planet) {
  514. if (planet.state.active == true && planet.state.captured == false)
  515. activePlanetsScore[planet.id] = 0;
  516. });
  517. },
  518. error: function (xhr, ajaxOptions, thrownError) {
  519. var messagesArray = ["get active planets", "getting active planets"];
  520. var ajaxParams = {
  521. xhr: xhr,
  522. ajaxOptions: ajaxOptions,
  523. thrownError: thrownError
  524. };
  525. ajaxErrorHandling(this, ajaxParams, messagesArray);
  526. }
  527. });
  528.  
  529. // GET the score of each active planet
  530. Object.keys(activePlanetsScore).forEach ( function (planet_id) {
  531. // GET to the endpoint
  532. $J.ajax({
  533. async: false,
  534. type: "GET",
  535. url: "https://community.steam-api.com/ITerritoryControlMinigameService/GetPlanet/v0001/",
  536. data: { id: planet_id },
  537. success: function(data) {
  538. data.response.planets[0].zones.forEach( function ( zone ) {
  539. if (zone.difficulty >= 1 && zone.difficulty <= 3 && zone.captured == false)
  540. activePlanetsScore[planet_id] += Math.ceil(auto_switch_planet["coeffScore"][zone.difficulty] * (1 - zone.capture_progress));
  541. });
  542. },
  543. error: function() {
  544. numberErrors++;
  545. }
  546. });
  547. if (activePlanetsScore[planet_id] > maxScore) {
  548. maxScore = activePlanetsScore[planet_id];
  549. bestPlanetId = planet_id;
  550. }
  551. });
  552. console.log(activePlanetsScore);
  553. // Prevent a planet switch if there were >= 2 errors while fetching planets or if there's an error while fetching the current planet score
  554. if (numberErrors >= 2 || ((current_planet_id in activePlanetsScore) && activePlanetsScore[current_planet_id] == 0))
  555. return null;
  556.  
  557. return bestPlanetId;
  558. }
  559.  
  560. // Switch to the next zone when one is completed
  561. function SwitchNextZone(attempt_no, planet_call) {
  562. if(attempt_no === undefined)
  563. attempt_no = 0;
  564. if (planet_call === undefined)
  565. planet_call = false;
  566. INJECT_update_grid();
  567. var next_zone = GetBestZone();
  568. if (next_zone !== undefined) {
  569. if (next_zone != target_zone) {
  570. console.log("Found new best zone: " + next_zone);
  571. INJECT_start_round(next_zone, access_token, attempt_no);
  572. } else {
  573. console.log("Current zone #" + target_zone + " is already the best. No need to switch.");
  574. if (planet_call === true)
  575. INJECT_start_round(target_zone, access_token, attempt_no);
  576. }
  577. } else {
  578. if (auto_switch_planet.active == true) {
  579. console.log("There are no more zones, the planet must be completed. Searching a new one.");
  580. CheckSwitchBetterPlanet();
  581. } else {
  582. INJECT_leave_round();
  583. INJECT_update_grid();
  584. console.log("There are no more zones, the planet must be completed. You'll need to choose another planet!");
  585. target_zone = -1;
  586. INJECT_leave_planet();
  587. }
  588. }
  589. }
  590.  
  591. // Check & switch for a potentially better planet, start to the best available zone
  592. function CheckSwitchBetterPlanet(difficulty_call) {
  593. if (difficulty_call === undefined)
  594. difficulty_call = false;
  595. var best_planet = GetBestPlanet();
  596. if (best_planet !== undefined && best_planet !== null && best_planet !== current_planet_id) {
  597. console.log("Planet #" + best_planet + " has higher XP potential. Switching to it. Bye planet #" + current_planet_id);
  598. INJECT_switch_planet(best_planet, function() {
  599. target_zone = GetBestZone();
  600. INJECT_start_round(target_zone, access_token);
  601. });
  602. } else if (best_planet == current_planet_id) {
  603. SwitchNextZone(0, difficulty_call);
  604. } else if (best_planet === null) {
  605. console.log("Too many errors while searching a better planet. Let's continue on the current zone.");
  606. INJECT_start_round(target_zone, access_token);
  607. } else {
  608. console.log("There's no planet better than the current one.");
  609. }
  610. }
  611.  
  612. var INJECT_switch_planet = function(planet_id, callback) {
  613. // ONLY usable from battle selection
  614. if(!(gGame.m_State instanceof CBattleSelectionState))
  615. return;
  616.  
  617. gui.updateTask("Attempting to move to Planet #" + planet_id);
  618.  
  619. function wait_for_state_load() {
  620. if(gGame.m_IsStateLoading || gGame.m_State instanceof CPlanetSelectionState)
  621. setTimeout(function() { wait_for_state_load(); }, 50);
  622. else
  623. callback();
  624. }
  625.  
  626. // Leave our current round if we haven't.
  627. INJECT_leave_round();
  628.  
  629. // Leave the planet
  630. INJECT_leave_planet(function() {
  631.  
  632. // Make sure the planet_id is valid (or we'll error out)
  633. var valid_planets = gGame.m_State.m_rgPlanets;
  634. var found = false;
  635. for(var i=0; i<valid_planets.length; i++)
  636. if (valid_planets[i].id == planet_id)
  637. found = true;
  638. if(!found) {
  639. gui.updateTask("Attempted to switch to an invalid planet. Please choose a new one.");
  640. gui.updateStatus(false);
  641. return;
  642. }
  643.  
  644. // Join Planet
  645. INJECT_join_planet(planet_id,
  646. function ( response ) {
  647. gGame.ChangeState( new CBattleSelectionState( planet_id ) );
  648. wait_for_state_load();
  649. },
  650. function ( response ) {
  651. ShowAlertDialog( 'Join Planet Error', 'Failed to join planet. Please reload your game or try again shortly.' );
  652. });
  653. });
  654.  
  655. }
  656.  
  657. // Leave the planet
  658. var INJECT_leave_planet = function(callback) {
  659. if(typeof callback !== 'function')
  660. callback = function() {};
  661.  
  662. function wait_for_state_load() {
  663. if(gGame.m_IsStateLoading || gGame.m_State instanceof CBattleSelectionState)
  664. setTimeout(function() { wait_for_state_load(); }, 50);
  665. else {
  666. // Clear the current planet ID var
  667. current_planet_id = undefined;
  668.  
  669. INJECT_init();
  670. callback();
  671. }
  672. }
  673.  
  674. // Cancel timeouts
  675. clearTimeout(current_timeout);
  676.  
  677. // Leave our current round if we haven't.
  678. INJECT_leave_round();
  679.  
  680. // (Modified) Default Code
  681. gAudioManager.PlaySound( 'ui_select_backwards' );
  682. gServer.LeaveGameInstance(
  683. gGame.m_State.m_PlanetData.id,
  684. function() {
  685. gGame.ChangeState( new CPlanetSelectionState() );
  686. // Wait for the new state to load, then hook in
  687. wait_for_state_load();
  688. }
  689. );
  690. }
  691.  
  692. var INJECT_join_planet = function(planet_id, success_callback, error_callback) {
  693. if(typeof success_callback !== 'function')
  694. success_callback = function() {};
  695. if(typeof error_callback !== 'function')
  696. error_callback = function() {};
  697. function wait_for_state_load() {
  698. if(gGame.m_IsStateLoading || gGame.m_State instanceof CPlanetSelectionState)
  699. setTimeout(function() { wait_for_state_load(); }, 50);
  700. else {
  701. current_planet_id = planet_id;
  702. INJECT_init();
  703. }
  704. }
  705.  
  706. // Modified Default code
  707. var rgParams = {
  708. id: planet_id,
  709. access_token: access_token
  710. };
  711.  
  712. $J.ajax({
  713. async: false,
  714. url: window.gServer.m_WebAPI.BuildURL( 'ITerritoryControlMinigameService', 'JoinPlanet', true ),
  715. method: 'POST',
  716. data: rgParams
  717. }).success( function( results, textStatus, request ) {
  718. if ( request.getResponseHeader( 'x-eresult' ) == 1 ) {
  719. success_callback( results );
  720. // Wait for the new state to load, then hook in
  721. wait_for_state_load();
  722. }
  723. else {
  724. console.log(results, textStatus, request);
  725. error_callback();
  726. }
  727. }).fail( error_callback );
  728. }
  729. var INJECT_init_battle_selection = function() {
  730. gui.updateStatus(true);
  731. gui.updateTask("Initializing Battle Selection Menu.");
  732. // Auto join best zone at first
  733. if (auto_first_join == true) {
  734. firstJoin();
  735. function firstJoin() {
  736. // Wait for state & access_token
  737. if(access_token === undefined || gGame === undefined || gGame.m_IsStateLoading || gGame.m_State instanceof CPlanetSelectionState) {
  738. setTimeout(function() { firstJoin(); }, 100);
  739. console.log("waiting");
  740. return;
  741. }
  742.  
  743. current_planet_id = window.gGame.m_State.m_PlanetData.id;
  744.  
  745. var first_zone;
  746. if(target_zone === -1)
  747. first_zone = GetBestZone();
  748. else
  749. first_zone = target_zone
  750.  
  751. if(access_token === undefined)
  752. INJECT_get_access_token();
  753.  
  754. INJECT_start_round(first_zone, access_token);
  755. }
  756. }
  757.  
  758. // Overwrite join function so clicking on a grid square will run our code instead
  759. gServer.JoinZone = function (zone_id, callback, error_callback) {
  760. current_planet_id = window.gGame.m_State.m_PlanetData.id;
  761. INJECT_start_round(zone_id, access_token);
  762. }
  763.  
  764. // Hook the Grid click function
  765. var grid_click_default = gGame.m_State.m_Grid.click;
  766. gGame.m_State.m_Grid.click = function(tileX, tileY) {
  767. // Get the selected zone ID
  768. var zoneIdx = _GetTileIdx( tileX, tileY );
  769.  
  770. // Return if it's the current zone (Don't want clicking on same zone to leave/rejoin)
  771. if(target_zone === zoneIdx)
  772. return;
  773.  
  774. // Return if it's a completed zone
  775. if(window.gGame.m_State.m_Grid.m_Tiles[zoneIdx].Info.captured) {
  776. console.log("Manually selected zone already captured. Returning.");
  777. return;
  778. }
  779.  
  780. // Update the GUI
  781. gui.updateTask("Attempting manual switch to Zone #" + zoneIdx);
  782. gui.progressbar.parent.removeChild(gui.progressbar)
  783.  
  784. // Leave existing round
  785. INJECT_leave_round();
  786.  
  787. // Join new round
  788. INJECT_start_round(zoneIdx, access_token);
  789. }
  790.  
  791. // Hook the Leave Planet Button
  792. gGame.m_State.m_LeaveButton.click = function(btn) {
  793. INJECT_leave_planet();
  794. };
  795. }
  796.  
  797. var INJECT_init_planet_selection = function() {
  798. gui.updateStatus(true);
  799. gui.updateTask("Initializing Planet Selection Menu.");
  800.  
  801. // Hook the Join Planet Function
  802. gServer.JoinPlanet = function(planet_id, success_callback, error_callback) {
  803. INJECT_join_planet(planet_id, success_callback, error_callback);
  804. }
  805.  
  806. // Update GUI
  807. gui.updateStatus(false);
  808. gui.updateTask("At Planet Selection");
  809. gui.updateZone("None");
  810. };
  811.  
  812. var INJECT_init = function() {
  813. if (gGame.m_State instanceof CBattleSelectionState)
  814. INJECT_init_battle_selection();
  815. else if (gGame.m_State instanceof CPlanetSelectionState)
  816. INJECT_init_planet_selection();
  817. };
  818.  
  819. var INJECT_disable_animations = function() {
  820. var confirmed = confirm("Disabling animations will vastly reduce resources used, but you will no longer be able to manually swap zones until you refresh. Continue?");
  821.  
  822. if(confirmed) {
  823. requestAnimationFrame = function(){};
  824. $J("#disableAnimsBtn").prop("disabled",true).prop("value", "Animations Disabled.");
  825. }
  826. };
  827.  
  828. // ============= CODE THAT AUTORUNS ON LOAD =============
  829. // Auto-grab the access token
  830. INJECT_get_access_token();
  831.  
  832. // Run the global initializer, which will call the function for whichever screen you're in
  833. INJECT_init();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement