Merge pull request #955 from Daniferrito/import-autoreload

Import autoreload
This commit is contained in:
hydroflame 2021-05-15 11:16:24 -04:00 committed by GitHub
commit a75efd9c62
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 19 additions and 112 deletions

@ -8,16 +8,10 @@ import { Companies, loadCompanies } from "./Company/Companies";
import { CONSTANTS } from "./Constants"; import { CONSTANTS } from "./Constants";
import { Engine } from "./engine"; import { Engine } from "./engine";
import { Factions, loadFactions } from "./Faction/Factions"; import { Factions, loadFactions } from "./Faction/Factions";
import { processPassiveFactionRepGain } from "./Faction/FactionHelpers";
import { loadFconf } from "./Fconf/Fconf"; import { loadFconf } from "./Fconf/Fconf";
import { FconfSettings } from "./Fconf/FconfSettings"; import { FconfSettings } from "./Fconf/FconfSettings";
import { loadAllGangs, AllGangs } from "./Gang"; import { loadAllGangs, AllGangs } from "./Gang";
import {
hasHacknetServers,
processHacknetEarnings,
} from "./Hacknet/HacknetHelpers";
import { loadMessages, initMessages, Messages } from "./Message/MessageHelpers"; import { loadMessages, initMessages, Messages } from "./Message/MessageHelpers";
import { loadAllRunningScripts } from "./NetscriptWorker";
import { Player, loadPlayer } from "./Player"; import { Player, loadPlayer } from "./Player";
import { AllServers, loadAllServers } from "./Server/AllServers"; import { AllServers, loadAllServers } from "./Server/AllServers";
import { Settings } from "./Settings/Settings"; import { Settings } from "./Settings/Settings";
@ -34,17 +28,12 @@ import { setTimeoutRef } from "./utils/SetTimeoutRef";
import { LastExportBonus } from "./ExportBonus"; import { LastExportBonus } from "./ExportBonus";
import { dialogBoxCreate } from "../utils/DialogBox"; import { dialogBoxCreate } from "../utils/DialogBox";
import { gameOptionsBoxClose } from "../utils/GameOptions";
import { convertTimeMsToTimeElapsedString } from "../utils/StringHelperFunctions";
import { clearEventListeners } from "../utils/uiHelpers/clearEventListeners"; import { clearEventListeners } from "../utils/uiHelpers/clearEventListeners";
import { import {
Reviver, Reviver,
Generic_toJSON, Generic_toJSON,
Generic_fromJSON, Generic_fromJSON,
} from "../utils/JSONReviver"; } from "../utils/JSONReviver";
import { createElement } from "../utils/uiHelpers/createElement";
import { createPopup } from "../utils/uiHelpers/createPopup";
import { removeElementById } from "../utils/uiHelpers/removeElementById";
import Decimal from "decimal.js"; import Decimal from "decimal.js";
@ -288,22 +277,11 @@ function loadGame(saveString) {
function loadImportedGame(saveObj, saveString) { function loadImportedGame(saveObj, saveString) {
var tempSaveObj = null; var tempSaveObj = null;
var tempPlayer = null; var tempPlayer = null;
var tempAllServers = null;
var tempCompanies = null;
var tempFactions = null;
var tempSpecialServerIps = null;
var tempAliases = null;
var tempGlobalAliases = null;
var tempMessages = null;
var tempStockMarket = null;
var tempAllGangs = null;
let tempCorporationResearchTrees = null;
// Check to see if the imported save file can be parsed. If any // Check to see if the imported save file can be parsed. If any
// errors are caught it will fail // errors are caught it will fail
try { try {
var decodedSaveString = decodeURIComponent(escape(atob(saveString))); var decodedSaveString = decodeURIComponent(escape(atob(saveString)));
tempSaveObj = new BitburnerSaveObject();
tempSaveObj = JSON.parse(decodedSaveString, Reviver); tempSaveObj = JSON.parse(decodedSaveString, Reviver);
tempPlayer = JSON.parse(tempSaveObj.PlayerSave, Reviver); tempPlayer = JSON.parse(tempSaveObj.PlayerSave, Reviver);
@ -311,33 +289,27 @@ function loadImportedGame(saveObj, saveString) {
// Parse Decimal.js objects // Parse Decimal.js objects
tempPlayer.money = new Decimal(tempPlayer.money); tempPlayer.money = new Decimal(tempPlayer.money);
tempAllServers = JSON.parse(tempSaveObj.AllServersSave, Reviver); JSON.parse(tempSaveObj.AllServersSave, Reviver);
tempCompanies = JSON.parse(tempSaveObj.CompaniesSave, Reviver); JSON.parse(tempSaveObj.CompaniesSave, Reviver);
tempFactions = JSON.parse(tempSaveObj.FactionsSave, Reviver); JSON.parse(tempSaveObj.FactionsSave, Reviver);
tempSpecialServerIps = JSON.parse(tempSaveObj.SpecialServerIpsSave, Reviver); JSON.parse(tempSaveObj.SpecialServerIpsSave, Reviver);
if (tempSaveObj.hasOwnProperty("AliasesSave")) { if (tempSaveObj.hasOwnProperty("AliasesSave")) {
try { try {
tempAliases = JSON.parse(tempSaveObj.AliasesSave, Reviver); JSON.parse(tempSaveObj.AliasesSave, Reviver);
} catch(e) { } catch(e) {
console.error(`Parsing Aliases save failed: ${e}`); console.error(`Parsing Aliases save failed: ${e}`);
tempAliases = {};
} }
} else {
tempAliases = {};
} }
if (tempSaveObj.hasOwnProperty("GlobalAliases")) { if (tempSaveObj.hasOwnProperty("GlobalAliases")) {
try { try {
tempGlobalAliases = JSON.parse(tempSaveObj.AliasesSave, Reviver); JSON.parse(tempSaveObj.AliasesSave, Reviver);
} catch(e) { } catch(e) {
console.error(`Parsing Global Aliases save failed: ${e}`); console.error(`Parsing Global Aliases save failed: ${e}`);
tempGlobalAliases = {};
} }
} else {
tempGlobalAliases = {};
} }
if (tempSaveObj.hasOwnProperty("MessagesSave")) { if (tempSaveObj.hasOwnProperty("MessagesSave")) {
try { try {
tempMessages = JSON.parse(tempSaveObj.MessagesSave, Reviver); JSON.parse(tempSaveObj.MessagesSave, Reviver);
} catch(e) { } catch(e) {
console.error(`Parsing Messages save failed: ${e}`); console.error(`Parsing Messages save failed: ${e}`);
initMessages(); initMessages();
@ -347,13 +319,10 @@ function loadImportedGame(saveObj, saveString) {
} }
if (saveObj.hasOwnProperty("StockMarketSave")) { if (saveObj.hasOwnProperty("StockMarketSave")) {
try { try {
tempStockMarket = JSON.parse(tempSaveObj.StockMarketSave, Reviver); JSON.parse(tempSaveObj.StockMarketSave, Reviver);
} catch(e) { } catch(e) {
console.error(`Parsing StockMarket save failed: ${e}`); console.error(`Parsing StockMarket save failed: ${e}`);
tempStockMarket = {};
} }
} else {
tempStockMarket = {};
} }
if (tempSaveObj.hasOwnProperty("VersionSave")) { if (tempSaveObj.hasOwnProperty("VersionSave")) {
try { try {
@ -362,7 +331,6 @@ function loadImportedGame(saveObj, saveString) {
} catch(e) { } catch(e) {
console.error("Parsing Version save failed: " + e); console.error("Parsing Version save failed: " + e);
} }
} else {
} }
if (tempPlayer.inGang() && tempSaveObj.hasOwnProperty("AllGangsSave")) { if (tempPlayer.inGang() && tempSaveObj.hasOwnProperty("AllGangsSave")) {
try { try {
@ -460,71 +428,8 @@ function loadImportedGame(saveObj, saveString) {
console.error("ERROR: Failed to parse AllGangsSave: " + e); console.error("ERROR: Failed to parse AllGangsSave: " + e);
} }
} }
saveObject.saveGame(Engine.indexedDb);
var popupId = "import-game-restart-game-notice"; location.reload();
var txt = createElement("p", {
innerText:"Imported game! You need to SAVE the game and then RELOAD the page " +
"to make sure everything runs smoothly",
});
var gotitBtn = createElement("a", {
class:"a-link-button", float:"right", padding:"6px", innerText:"Got it!",
clickListener:() => {
removeElementById(popupId);
},
});
createPopup(popupId, [txt, gotitBtn]);
gameOptionsBoxClose();
// Re-start game
Engine.setDisplayElements(); // Sets variables for important DOM elements
Engine.init(); // Initialize buttons, work, etc.
// Calculate the number of cycles have elapsed while offline
Engine._lastUpdate = new Date().getTime();
var lastUpdate = Player.lastUpdate;
var numCyclesOffline = Math.floor((Engine._lastUpdate - lastUpdate) / Engine._idleSpeed);
// Process offline progress
var offlineProductionFromScripts = loadAllRunningScripts(); // This also takes care of offline production for those scripts
if (Player.isWorking) {
if (Player.workType == CONSTANTS.WorkTypeFaction) {
Player.workForFaction(numCyclesOffline);
} else if (Player.workType == CONSTANTS.WorkTypeCreateProgram) {
Player.createProgramWork(numCyclesOffline);
} else if (Player.workType == CONSTANTS.WorkTypeStudyClass) {
Player.takeClass(numCyclesOffline);
} else if (Player.workType == CONSTANTS.WorkTypeCrime) {
Player.commitCrime(numCyclesOffline);
} else if (Player.workType == CONSTANTS.WorkTypeCompanyPartTime) {
Player.workPartTime(numCyclesOffline);
} else {
Player.work(numCyclesOffline);
}
}
// Hacknet Nodes offline progress
var offlineProductionFromHacknetNodes = processHacknetEarnings(numCyclesOffline);
// Passive faction rep gain offline
processPassiveFactionRepGain(numCyclesOffline);
// Update total playtime
var time = numCyclesOffline * Engine._idleSpeed;
if (Player.totalPlaytime == null) {Player.totalPlaytime = 0;}
if (Player.playtimeSinceLastAug == null) {Player.playtimeSinceLastAug = 0;}
if (Player.playtimeSinceLastBitnode == null) {Player.playtimeSinceLastBitnode = 0;}
Player.totalPlaytime += time;
Player.playtimeSinceLastAug += time;
Player.playtimeSinceLastBitnode += time;
// Re-apply augmentations
Player.reapplyAllAugmentations();
// Clear terminal
$("#terminal tr:not(:last)").remove();
Player.lastUpdate = Engine._lastUpdate;
Engine.start(); // Run main game loop and Scripts loop
return true; return true;
} }

@ -236,6 +236,8 @@ const Engine = {
characterInfo: null, characterInfo: null,
}, },
indexedDb: undefined,
// Time variables (milliseconds unix epoch time) // Time variables (milliseconds unix epoch time)
_lastUpdate: new Date().getTime(), _lastUpdate: new Date().getTime(),
_idleSpeed: 200, // Speed (in ms) at which the main loop is updated _idleSpeed: 200, // Speed (in ms) at which the main loop is updated
@ -815,7 +817,7 @@ const Engine = {
Engine.Counters.autoSaveCounter = Infinity; Engine.Counters.autoSaveCounter = Infinity;
} else { } else {
Engine.Counters.autoSaveCounter = Settings.AutosaveInterval * 5; Engine.Counters.autoSaveCounter = Settings.AutosaveInterval * 5;
saveObject.saveGame(indexedDb); saveObject.saveGame(Engine.indexedDb);
} }
} }
@ -1468,13 +1470,13 @@ const Engine = {
// Save, Delete, Import/Export buttons // Save, Delete, Import/Export buttons
Engine.Clickables.saveMainMenuButton = document.getElementById("save-game-link"); Engine.Clickables.saveMainMenuButton = document.getElementById("save-game-link");
Engine.Clickables.saveMainMenuButton.addEventListener("click", function() { Engine.Clickables.saveMainMenuButton.addEventListener("click", function() {
saveObject.saveGame(indexedDb); saveObject.saveGame(Engine.indexedDb);
return false; return false;
}); });
Engine.Clickables.deleteMainMenuButton = document.getElementById("delete-game-link"); Engine.Clickables.deleteMainMenuButton = document.getElementById("delete-game-link");
Engine.Clickables.deleteMainMenuButton.addEventListener("click", function() { Engine.Clickables.deleteMainMenuButton.addEventListener("click", function() {
saveObject.deleteGame(indexedDb); saveObject.deleteGame(Engine.indexedDb);
return false; return false;
}); });
@ -1485,7 +1487,7 @@ const Engine = {
// Character Overview buttons // Character Overview buttons
document.getElementById("character-overview-save-button").addEventListener("click", function() { document.getElementById("character-overview-save-button").addEventListener("click", function() {
saveObject.saveGame(indexedDb); saveObject.saveGame(Engine.indexedDb);
return false; return false;
}); });
@ -1597,7 +1599,7 @@ const Engine = {
}, },
}; };
var indexedDb, indexedDbRequest; var indexedDbRequest;
window.onload = function() { window.onload = function() {
if (!window.indexedDB) { if (!window.indexedDB) {
return Engine.load(null); // Will try to load from localstorage return Engine.load(null); // Will try to load from localstorage
@ -1617,8 +1619,8 @@ window.onload = function() {
}; };
indexedDbRequest.onsuccess = function(e) { indexedDbRequest.onsuccess = function(e) {
indexedDb = e.target.result; Engine.indexedDb = e.target.result;
var transaction = indexedDb.transaction(["savestring"]); var transaction = Engine.indexedDb.transaction(["savestring"]);
var objectStore = transaction.objectStore("savestring"); var objectStore = transaction.objectStore("savestring");
var request = objectStore.get("save"); var request = objectStore.get("save");
request.onerror = function(e) { request.onerror = function(e) {