Advertisement
Guest User

Untitled

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