Refactored Code to make Save/Load work. This included re-structuring classes so that they contained only native objects/arrays of native objects and using a Reviver function in the JSON.parse. Cleaned up some code that was no longer needed

This commit is contained in:
Daniel Xie 2016-12-01 16:18:18 -06:00
parent ca9caada67
commit d5d198cbb4
9 changed files with 907 additions and 770 deletions

@ -11,6 +11,11 @@
the Google CDN (Content Delivery Network). -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<!-- Utils -->
<script src="utils/IPAddress.js"></script>
<script src="utils/JSONReviver.js"></script>
<!-- Netscript -->
<script src="src/netscript/NetScriptWorker.js"></script>
<script src="src/netscript/InputStream.js"></script>
<script src="src/netscript/Tokenizer.js"></script>
@ -18,6 +23,7 @@
<script src="src/netscript/Evaluator.js"></script>
<script src="src/netscript/Environment.js"></script>
<!-- Main game files -->
<script src="src/Constants.js"></script>
<script src="src/Server.js"></script>
<script src="src/Player.js"></script>
@ -28,9 +34,6 @@
<script src="src/engine.js"></script>
<!-- Utils -->
<script src="utils/JSONReviver.js"></script>
</head>
<body>
<div id="mainmenu-container">
@ -48,10 +51,6 @@
<a href="#" id="create-script-menu-link"> Create Script </a>
</li>
<li class="gym-tab" style="display:none">
<a href="#" id="gym-menu-link"> Gym </a>
</li>
<li class="world-tab" style="display:none">
<a href="#" id="world-menu-link"> World </a>
</li>
@ -59,6 +58,14 @@
<li class="develop-gui-tab" style="display:none">
<a href="#" id="develop-gui-menu-link"> Develop GUI </a>
</li>
<li class="save-game-tab">
<a href="#" id="save-game-link"> Save Game </a>
</li>
<li class="delete-game-tab">
<a href="#" id="delete-game-link"> Delete Game </a>
</li>
</ul>
</div>

@ -5,4 +5,26 @@ CONSTANTS = {
//Time (ms) it takes to run one operation in Netscript.
CodeInstructionRunTime: 1500,
//Text that is displayed when the 'help' command is ran in Terminal
HelpText: "analyze Get statistics and information about current machine\n" +
"clear Clear all text on the terminal\n" +
"cls See 'clear' command\n" +
"connect [ip/hostname] Connects to the machine given by its IP or hostname\n" +
"free Check the machine's memory usage\n" +
"hack Hack the current machine\n" +
"help Display this list\n" +
"hostname Displays the hostname of the machine\n" +
"ifconfig Displays the IP address of the machine\n" +
"kill [script name] Stops a script that is running\n" +
"ls Displays all programs and scripts on the machine\n" +
"nano [script name] Text editor - Open up and edit a script\n" +
"netstat Displays all available network connections\n" +
"ps Display all scripts that are currently running\n" +
"rm Delete a script/program from the machine. (WARNING: Permanent)\n" +
"run [script/program] Execute a program or a script\n" +
"scan See 'netstat' command\n" +
"telnet [ip/hostname] See 'connect' command\n" +
"top Display all running scripts and their RAM usage\n"
}

@ -1,156 +1,174 @@
//Netburner Player class
var Player = {
//Skills and stats
hacking_skill: 1,
//Fighting
strength: 1, //Damage dealt
defense: 1, //Damage received
dexterity: 1, //Accuracy
agility: 1, //Dodge %
//Labor stats
charisma: 1,
//Hacking multipliers
hacking_chance_multiplier: 2, //Increase through ascensions/augmentations
//hacking_speed_multiplier: 5, //Decrease through ascensions/augmentations
hacking_speed_multiplier: 1, //Make it faster for debugging
hacking_money_multiplier: .01, //Increase through ascensions/augmentations. Can't go above 1
//Note: "Lifetime" refers to current ascension, "total" refers to the entire game history
//Accumulative stats and skills
total_hacking: 1,
total_strength: 1,
total_defense: 1,
total_dexterity: 1,
total_agility: 1,
total_charisma: 1,
lifetime_hacking: 1,
lifetime_strength: 1,
lifetime_defense: 1,
lifetime_dexterity: 1,
lifetime_agility: 1,
lifetime_charisma: 1,
//Experience and multipliers
hacking_exp: 0,
strength_exp: 0,
defense_exp: 0,
dexterity_exp: 0,
agility_exp: 0,
charisma_exp: 0,
hacking_exp_mult: 1,
strength_exp_mult: 1,
defense_exp_mult: 1,
dexterity_exp_mult: 1,
agility_exp_mult: 1,
charisma_exp_mult: 1,
company_rep_mult: 1, //Multiplier for how fast the player gains reputation at a company
//Money
money: 0,
total_money: 0,
lifetime_money: 0,
//Starting (home) computer
homeComputer: new Server(),
//Servers
currentServer: null, //Server currently being accessed through terminal
discoveredServers: [],
purchasedServers: [],
//Achievements and achievement progress
//Flag to let the engine know the player is starting a hack
startAction: false,
actionTime: 0,
init: function() {
/* Initialize properties of Player's home computer */
Player.homeComputer.init("19.42.93.219", "home", "Home PC", true, true, true, true, 1);
Player.currentServer = Player.homeComputer;
Player.homeComputer.programs.push("PortHack.exe");
var NetworkGroup1 = [ForeignServers.IronGym, ForeignServers.FoodNStuff, ForeignServers.SigmaCosmetics, ForeignServers.JoesGuns, ForeignServers.HongFangTeaHouse, ForeignServers.HaraKiriSushiBar];
for (var i = 0; i < NetworkGroup1.length; i++) {
Player.homeComputer.serversOnNetwork.push(NetworkGroup1[i]);
NetworkGroup1[i].serversOnNetwork.push(Player.homeComputer);
}
},
//Calculates skill level based on experience. The same formula will be used for every skill
// At the maximum possible exp (MAX_INT = 9007199254740991), the hacking skill will be 1796
// Gets to level 1000 hacking skill at ~1,100,000,000 exp
calculateSkill: function(exp) {
return Math.max(Math.floor(50 * log(9007199254740991+ 2.270) - 40), 1);
},
//Calculates the chance of hacking a server
//The formula is:
// (hacking_chance_multiplier * hacking_skill - requiredLevel) 100 - difficulty
// ----------------------------------------------------------- * -----------------
// (hacking_chance_multiplier * hacking_skill) 100
calculateHackingChance: function() {
var difficultyMult = (100 - Player.currentServer.hackDifficulty) / 100;
var skillMult = (Player.hacking_chance_multiplier * Player.hacking_skill);
var skillChance = (skillMult - Player.currentServer.requiredHackingSkill) / skillMult;
return (skillChance * difficultyMult);
},
//Calculate the time it takes to hack a server in seconds. Returns the time
//The formula is:
// (requiredLevel * difficulty)
// ------------------------------- * hacking_speed_multiplier
// hacking_skill
calculateHackingTime: function() {
var difficultyMult = Player.currentServer.requiredHackingSkill * Player.currentServer.hackDifficulty;
var skillFactor = difficultyMult / Player.hacking_skill;
return skillFactor * Player.hacking_speed_multiplier;
},
//Calculates the PERCENTAGE of a server's money that the player will hack from the server if successful
//The formula is:
// (hacking_skill - (requiredLevel-1)) 100 - difficulty
// --------------------------------------* ----------------------- * hacking_money_multiplier
// hacking_skill 100
calculatePercentMoneyHacked: function() {
var difficultyMult = (100 - Player.currentServer.hackDifficulty) / 100;
var skillMult = (Player.hacking_skill - (Player.currentServer.requiredHackingSkill - 1)) / Player.hacking_skill;
var percentMoneyHacked = difficultyMult * skillMult * Player.hacking_money_multiplier;
console.log("Percent money hacked calculated to be: " + percentMoneyHacked);
return percentMoneyHacked;
},
//Returns how much EXP the player gains on a successful hack
//The formula is:
// difficulty * requiredLevel * hacking_multiplier
//
// Note: Keep it at an integer for now,
calculateExpGain: function() {
return Math.round(Player.currentServer.hackDifficulty * Player.currentServer.requiredHackingSkill * Player.hacking_exp_mult);
},
//Hack/Analyze a server. Return the amount of time the hack will take. This lets the Terminal object know how long to disable itself for
//This assumes that the server being hacked is not purchased by the player, that the player's hacking skill is greater than the
//required hacking skill and that the player has admin rights.
hack: function() {
Player.actionTime = Player.calculateHackingTime();
console.log("Hacking time: " + Player.actionTime);
//Set the startHack flag so the engine starts the hacking process
Player.startAction = true;
},
function PlayerObject() {
//Skills and stats
this.hacking_skill = 1;
//Fighting
this.strength = 1; //Damage dealt
this.defense = 1; //Damage received
this.dexterity = 1; //Accuracy
this.agility = 1; //Dodge %
//Labor stats
this.charisma = 1;
//Hacking multipliers
this.hacking_chance_multiplier = 2; //Increase through ascensions/augmentations
//this.hacking_speed_multiplier = 5; //Decrease through ascensions/augmentations
this.hacking_speed_multiplier = 1; //Make it faster for debugging
this.hacking_money_multiplier = .01; //Increase through ascensions/augmentations. Can't go above 1
//Note: "Lifetime" refers to current ascension, "total" refers to the entire game history
//Accumulative stats and skills
this.total_hacking = 1;
this.total_strength = 1;
this.total_defense = 1;
this.total_dexterity = 1;
this.total_agility = 1;
this.total_charisma = 1;
this.lifetime_hacking = 1;
this.lifetime_strength = 1;
this.lifetime_defense = 1;
this.lifetime_dexterity = 1;
this.lifetime_agility = 1;
this.lifetime_charisma = 1;
//Experience and multipliers
this.hacking_exp = 0;
this.strength_exp = 0;
this.defense_exp = 0;
this.dexterity_exp = 0;
this.agility_exp = 0;
this.charisma_exp = 0;
this.hacking_exp_mult = 1;
this.strength_exp_mult = 1;
this.defense_exp_mult = 1;
this.dexterity_exp_mult = 1;
this.agility_exp_mult = 1;
this.charisma_exp_mult = 1;
this.company_rep_mult = 1; //Multiplier for how fast the player gains reputation at a company
//Money
this.money = 0;
this.total_money = 0;
this.lifetime_money = 0;
//Starting (home) computer
this.homeComputer = null;
//Servers
this.currentServer = null; //Server currently being accessed through terminal
this.discoveredServers = []; //Secret servers not in the network that you have discovered
this.purchasedServers = [];
//Achievements and achievement progress
//Flag to let the engine know the player is starting a hack
this.startAction = false;
this.actionTime = 0;
};
PlayerObject.prototype.init = function() {
/* Initialize Player's home computer */
var t_homeComp = new Server();
t_homeComp.init(createRandomIp(), "home", "Home PC", true, true, true, true, 1);
this.homeComputer = t_homeComp.ip;
this.currentServer = t_homeComp.ip;
AddToAllServers(t_homeComp);
this.getHomeComputer().programs.push("PortHack.exe");
}
PlayerObject.prototype.getCurrentServer = function() {
return AllServers[this.currentServer];
}
PlayerObject.prototype.getHomeComputer = function() {
return AllServers[this.homeComputer];
}
//Calculates skill level based on experience. The same formula will be used for every skill
// At the maximum possible exp (MAX_INT = 9007199254740991), the hacking skill will be 1796
// Gets to level 1000 hacking skill at ~1,100,000,000 exp
PlayerObject.prototype.calculateSkill = function(exp) {
return Math.max(Math.floor(50 * log(9007199254740991+ 2.270) - 40), 1);
},
//Calculates the chance of hacking a server
//The formula is:
// (hacking_chance_multiplier * hacking_skill - requiredLevel) 100 - difficulty
// ----------------------------------------------------------- * -----------------
// (hacking_chance_multiplier * hacking_skill) 100
PlayerObject.prototype.calculateHackingChance = function() {
var difficultyMult = (100 - this.getCurrentServer().hackDifficulty) / 100;
var skillMult = (this.hacking_chance_multiplier * this.hacking_skill);
var skillChance = (skillMult - this.getCurrentServer().requiredHackingSkill) / skillMult;
return (skillChance * difficultyMult);
},
//Calculate the time it takes to hack a server in seconds. Returns the time
//The formula is:
// (requiredLevel * difficulty)
// ------------------------------- * hacking_speed_multiplier
// hacking_skill
PlayerObject.prototype.calculateHackingTime = function() {
var difficultyMult = this.getCurrentServer().requiredHackingSkill * this.getCurrentServer().hackDifficulty;
var skillFactor = difficultyMult / this.hacking_skill;
return skillFactor * this.hacking_speed_multiplier;
}
//Calculates the PERCENTAGE of a server's money that the player will hack from the server if successful
//The formula is:
// (hacking_skill - (requiredLevel-1)) 100 - difficulty
// --------------------------------------* ----------------------- * hacking_money_multiplier
// hacking_skill 100
PlayerObject.prototype.calculatePercentMoneyHacked = function() {
var difficultyMult = (100 - this.getCurrentServer().hackDifficulty) / 100;
var skillMult = (this.hacking_skill - (this.getCurrentServer().requiredHackingSkill - 1)) / this.hacking_skill;
var percentMoneyHacked = difficultyMult * skillMult * this.hacking_money_multiplier;
console.log("Percent money hacked calculated to be: " + percentMoneyHacked);
return percentMoneyHacked;
}
//Returns how much EXP the player gains on a successful hack
//The formula is:
// difficulty * requiredLevel * hacking_multiplier
//
// Note: Keep it at an integer for now,
PlayerObject.prototype.calculateExpGain = function() {
return Math.round(this.getCurrentServer().hackDifficulty * this.getCurrentServer().requiredHackingSkill * this.hacking_exp_mult);
}
//Hack/Analyze a server. Return the amount of time the hack will take. This lets the Terminal object know how long to disable itself for
//This assumes that the server being hacked is not purchased by the player, that the player's hacking skill is greater than the
//required hacking skill and that the player has admin rights.
PlayerObject.prototype.hack = function() {
this.actionTime = this.calculateHackingTime();
console.log("Hacking time: " + this.actionTime);
//Set the startHack flag so the engine starts the hacking process
this.startAction = true;
}
PlayerObject.prototype.analyze = function() {
//TODO Analyze only takes 5 seconds for now..maybe change this in the future?
this.actionTime = 5;
this.startAction = true;
}
//Functions for saving and loading the Player data
PlayerObject.prototype.toJSON = function() {
return Generic_toJSON("PlayerObject", this);
}
PlayerObject.fromJSON = function(value) {
return Generic_fromJSON(PlayerObject, value.data);
}
Reviver.constructors.PlayerObject = PlayerObject;
Player = new PlayerObject();
analyze: function() {
//TODO Analyze only takes 5 seconds for now..maybe change this in the future?
Player.actionTime = 5;
Player.startAction = true;
}
};

@ -16,17 +16,17 @@ $(document).keydown(function(e) {
filename += ".script";
//If the current script matches one thats currently running, throw an error
for (var i = 0; i < Player.currentServer.runningScripts.length; i++) {
if (filename == Player.currentServer.runningScripts[i].filename) {
for (var i = 0; i < Player.getCurrentServer().runningScripts.length; i++) {
if (filename == Player.getCurrentServer().runningScripts[i].filename) {
postScriptEditorStatus("Cannot write to script that is currently running!");
return;
}
}
//If the current script already exists on the server, overwrite it
for (var i = 0; i < Player.currentServer.scripts.length; i++) {
if (filename == Player.currentServer.scripts[i].filename) {
Player.currentServer.scripts[i].saveScript();
for (var i = 0; i < Player.getCurrentServer().scripts.length; i++) {
if (filename == Player.getCurrentServer().scripts[i].filename) {
Player.getCurrentServer().scripts[i].saveScript();
Engine.loadTerminalContent();
return;
}
@ -35,7 +35,7 @@ $(document).keydown(function(e) {
//If the current script does NOT exist, create a new one
var script = new Script();
script.saveScript();
Player.currentServer.scripts.push(script);
Player.getCurrentServer().scripts.push(script);
Engine.loadTerminalContent();
}
}
@ -62,16 +62,11 @@ function postScriptEditorStatus(text) {
}, 3000);
}
function Script() {
//Function queue that holds the next functions to be
//executed in this script. A function from this queue
//is executed every second (this may change)
this.functionQueue = [];
function Script() {
this.filename = "";
this.code = "";
this.ramUsage = 0;
this.server = null; //Which server this script is on
this.server = null; //IP of server this script is on
/* Properties to calculate offline progress. Only applies for infinitely looping scripts */
@ -111,29 +106,3 @@ Script.prototype.saveScript = function() {
//TODO Calculate/update number of instructions, ram usage, execution time, etc.
}
}
Script.prototype.queueEvaluate = function(exp, env) {
var fooObj = functionObject(evaluate, this, [exp, env]);
this.functionQueue.push(fooObj);
}
/* Wrapper object that wraps a function with its arguments.
* These objects are pushed onto a Script object's function queue.
* The functions can be called with the standard () operator
*
* Example:
* //Define the function
* var fooFunc = function(a1, a2, a3) {
* return a1 + a2 + a3;
* }
* //Wrap the function in the wrapper object
* var fooObj = functionObject(fooFunc, this, [2, 3, 4]);
* //Call the function
* fooObj();
*
*/
function functionObject(fn, context, params) {
return function() {
fn.apply(context, params);
}
}

File diff suppressed because it is too large Load Diff

@ -1,11 +1,23 @@
function TestObj() {
this.value = 1;
this.num = 1;
}
TestObj.prototype.setValue = function(val) {
this.value = val;
this.num = val;
}
TestObj.prototype.toJSON = function() {
console.log("toJSON() called");
return Generic_toJSON("TestObj", this);
}
TestObj.fromJSON = function(value) {
console.log("fromJSON() called");
return Generic_fromJSON(TestObj, value.data);
}
Reviver.constructors.TestObj = TestObj;
var testObj = new TestObj();
//Terminal
@ -83,9 +95,9 @@ var Terminal = {
var expGainedOnFailure = Math.round(expGainedOnSuccess / 4);
if (rand < hackChance) { //Success!
var moneyGained = Player.calculatePercentMoneyHacked();
moneyGained = Math.floor(Player.currentServer.moneyAvailable * moneyGained);
moneyGained = Math.floor(Player.getCurrentServer().moneyAvailable * moneyGained);
Player.currentServer.moneyAvailable -= moneyGained;
Player.getCurrentServer().moneyAvailable -= moneyGained;
Player.money += moneyGained;
Player.hacking_exp += expGainedOnSuccess;
@ -94,7 +106,7 @@ var Terminal = {
} else { //Failure
//Player only gains 25% exp for failure? TODO Can change this later to balance
Player.hacking_exp += expGainedOnFailure;
post("Failed to hack " + Player.currentServer.hostname + ". Gained " + expGainedOnFailure + " hacking EXP");
post("Failed to hack " + Player.getCurrentServer().hostname + ". Gained " + expGainedOnFailure + " hacking EXP");
}
//Rename the progress bar so that the next hacks dont trigger it. Re-enable terminal
@ -107,38 +119,38 @@ var Terminal = {
},
finishAnalyze: function() {
post(Player.currentServer.hostname + ": ");
post("Required hacking skill: " + Player.currentServer.requiredHackingSkill);
post(Player.getCurrentServer().hostname + ": ");
post("Required hacking skill: " + Player.getCurrentServer().requiredHackingSkill);
//TODO Make these actual estimates by adding a random offset to result?
//TODO Change the text to sound better
post("Estimated chance to hack: " + Math.round(Player.calculateHackingChance() * 100) + "%");
post("Estimated time to hack: " + Math.round(Player.calculateHackingTime()) + " seconds");
post("Required number of open ports for PortHack: " +Player.currentServer.numOpenPortsRequired);
if (Player.currentServer.sshPortOpen) {
post("Required number of open ports for PortHack: " +Player.getCurrentServer().numOpenPortsRequired);
if (Player.getCurrentServer().sshPortOpen) {
post("SSH port: Open")
} else {
post("SSH port: Closed")
}
if (Player.currentServer.ftpPortOpen) {
if (Player.getCurrentServer().ftpPortOpen) {
post("FTP port: Open")
} else {
post("FTP port: Closed")
}
if (Player.currentServer.smtpPortOpen) {
if (Player.getCurrentServer().smtpPortOpen) {
post("SMTP port: Open")
} else {
post("SMTP port: Closed")
}
if (Player.currentServer.httpPortOpen) {
if (Player.getCurrentServer().httpPortOpen) {
post("HTTP port: Open")
} else {
post("HTTP port: Closed")
}
if (Player.currentServer.sqlPortOpen) {
if (Player.getCurrentServer().sqlPortOpen) {
post("SQL port: Open")
} else {
post("SQL port: Closed")
@ -196,10 +208,10 @@ var Terminal = {
var ip = commandArray[1];
for (var i = 0; i < Player.currentServer.serversOnNetwork.length; i++) {
if (Player.currentServer.serversOnNetwork[i].ip == ip || Player.currentServer.serversOnNetwork[i].hostname == ip) {
Player.currentServer.isConnectedTo = false;
Player.currentServer = Player.currentServer.serversOnNetwork[i];
for (var i = 0; i < Player.getCurrentServer().serversOnNetwork.length; i++) {
if (Player.getCurrentServer().getServerOnNetwork(i).ip == ip || Player.getCurrentServer().getServerOnNetwork(i).hostname == ip) {
Player.getCurrentServer().isConnectedTo = false;
Player.currentServer = Player.getCurrentServer().getServerOnNetwork(i).ip;
post("Connected to " + ip);
return;
}
@ -207,14 +219,14 @@ var Terminal = {
post("Host not found");
break;
case "df":
case "free":
if (commandArray.length != 1) {
post("Incorrect usage of df command. Usage: df"); return;
}
console.log("df terminal command called");
post("Total: " + Player.currentServer.maxRam.toString() + " GB");
post("Used: " + Player.currentServer.ramUsed.toString() + " GB");
post("Available: " + (Player.currentServer.maxRam - Player.currentServer.ramUsed).toString() + " GB");
post("Total: " + Player.getCurrentServer().maxRam.toString() + " GB");
post("Used: " + Player.getCurrentServer().ramUsed.toString() + " GB");
post("Available: " + (Player.getCurrentServer().maxRam - Player.getCurrentServer().ramUsed).toString() + " GB");
break;
case "hack":
if (commandArray.length != 1) {
@ -222,11 +234,11 @@ var Terminal = {
}
//Hack the current PC (usually for money)
//You can't hack your home pc or servers you purchased
if (Player.currentServer.purchasedByPlayer) {
if (Player.getCurrentServer().purchasedByPlayer) {
post("Cannot hack your own machines! You are currently connected to your home PC or one of your purchased servers");
} else if (Player.currentServer.hasAdminRights == false ) {
} else if (Player.getCurrentServer().hasAdminRights == false ) {
post("You do not have admin rights for this machine! Cannot hack");
} else if (Player.currentServer.requiredHackingSkill > Player.hacking_skill) {
} else if (Player.getCurrentServer().requiredHackingSkill > Player.hacking_skill) {
post("Your hacking skill is not high enough to attempt hacking this machine. Try analyzing the machine to determine the required hacking skill");
} else {
Terminal.hackFlag = true;
@ -248,14 +260,14 @@ var Terminal = {
post("Incorrect usage of hostname command. Usage: hostname"); return;
}
//Print the hostname of current system
post(Player.currentServer.hostname);
post(Player.getCurrentServer().hostname);
break;
case "ifconfig":
if (commandArray.length != 1) {
post("Incorrect usage of ifconfig command. Usage: ifconfig"); return;
}
//Print the IP address of the current system
post(Player.currentServer.ip);
post(Player.getCurrentServer().ip);
break;
case "kill":
//TODO
@ -269,11 +281,11 @@ var Terminal = {
var allFiles = [];
//Get all of the programs and scripts on the machine into one temporary array
for (var i = 0; i < Player.currentServer.programs.length; i++) {
allFiles.push(Player.currentServer.programs[i]);
for (var i = 0; i < Player.getCurrentServer().programs.length; i++) {
allFiles.push(Player.getCurrentServer().programs[i]);
}
for (var i = 0; i < Player.currentServer.scripts.length; i++) {
allFiles.push(Player.currentServer.scripts[i].filename);
for (var i = 0; i < Player.getCurrentServer().scripts.length; i++) {
allFiles.push(Player.getCurrentServer().scripts[i].filename);
}
//Sort the files alphabetically then print each
@ -299,16 +311,16 @@ var Terminal = {
var scriptname = filename.substr(0, filename.indexOf(".script"));
//Cannot edit scripts that are currently running
for (var i = 0; i < Player.currentServer.runningScripts.length; i++) {
if (filename == Player.currentServer.runningScripts[i].filename) {
for (var i = 0; i < Player.getCurrentServer().runningScripts.length; i++) {
if (filename == Player.getCurrentServer().runningScripts[i].filename) {
post("Cannot open/edit scripts that are currently running!"); return;
}
}
//Check if the script already exists
for (var i = 0; i < Player.currentServer.scripts.length; i++) {
if (filename == Player.currentServer.scripts[i].filename) {
Engine.loadScriptEditorContent(scriptname, Player.currentServer.scripts[i].code);
for (var i = 0; i < Player.getCurrentServer().scripts.length; i++) {
if (filename == Player.getCurrentServer().scripts[i].filename) {
Engine.loadScriptEditorContent(scriptname, Player.getCurrentServer().scripts[i].code);
return;
}
}
@ -322,24 +334,24 @@ var Terminal = {
//Displays available network connections using TCP
console.log("netstat/scan terminal command called");
post("Hostname IP Root Access");
for (var i = 0; i < Player.currentServer.serversOnNetwork.length; i++) {
for (var i = 0; i < Player.getCurrentServer().serversOnNetwork.length; i++) {
//Add hostname
var entry = Player.currentServer.serversOnNetwork[i].hostname;
var entry = Player.getCurrentServer().getServerOnNetwork(i).hostname;
//Calculate padding and add IP
var numSpaces = 21 - entry.length;
var spaces = Array(numSpaces+1).join(" ");
entry += spaces;
entry += Player.currentServer.serversOnNetwork[i].ip;
entry += Player.getCurrentServer().getServerOnNetwork(i).ip;
//Calculate padding and add root access info
var hasRoot;
if (Player.currentServer.serversOnNetwork[i].hasAdminRights) {
if (Player.getCurrentServer().getServerOnNetwork(i).hasAdminRights) {
hasRoot = 'Y';
} else {
hasRoot = 'N';
}
numSpaces = 21 - Player.currentServer.serversOnNetwork[i].ip.length;
numSpaces = 21 - Player.getCurrentServer().getServerOnNetwork(i).ip.length;
spaces = Array(numSpaces+1).join(" ");
entry += spaces;
entry += hasRoot;
@ -373,13 +385,15 @@ var Terminal = {
case "scp":
//TODO
break;
case "top":
//TODO List each's script RAM usage
break;
case "test":
post(testObj.value.toString());
testObj.setValue(testObj.value + 1);
post(testObj.num.toString());
testObj.setValue(testObj.num + 1);
break;
case "testSave":
var testSave = JSONfn.stringify(testObj);
var testSave = JSON.stringify(testObj);
window.localStorage.setItem("netburnerTest", testSave);
console.log("Netburner TestSave saved");
break;
@ -387,8 +401,9 @@ var Terminal = {
if (!window.localStorage.getItem("netburnerTest")) {
console.log("No TestSave file to load");
} else {
console.log("Here");
var testSave = window.localStorage.getItem("netburnerTest");
testObj = JSONfn.parse(testSave);
testObj = JSON.parse(testSave, Reviver);
console.log("TestSave loaded");
}
break;
@ -410,8 +425,8 @@ var Terminal = {
runProgram: function(programName) {
//Check if you have the program on your computer. If you do, execute it, otherwise
//display an error message
for (var i = 0; i < Player.homeComputer.programs.length; i++) {
if (Player.homeComputer.programs[i] == programName) {
for (var i = 0; i < Player.getHomeComputer().programs.length; i++) {
if (Player.getHomeComputer().programs[i] == programName) {
Terminal.executeProgram(programName);
return;
}
@ -423,13 +438,13 @@ var Terminal = {
executeProgram: function(programName) {
switch (programName) {
case "PortHack.exe":
if (Player.currentServer.hasAdminRights) {
if (Player.getCurrentServer().hasAdminRights) {
post("You already have root access to this computer. There is no reason to run PortHack.exe");
} else {
console.log("Running PortHack executable");
if (Player.currentServer.openPortCount >= Player.currentServer.numOpenPortsRequired) {
Player.currentServer.hasAdminRights = true;
post("PortHack successful! Gained root access to " + Player.currentServer.hostname);
if (Player.getCurrentServer().openPortCount >= Player.getCurrentServer().numOpenPortsRequired) {
Player.getCurrentServer().hasAdminRights = true;
post("PortHack successful! Gained root access to " + Player.getCurrentServer().hostname);
//TODO Make this take time rather than be instant
} else {
post("PortHack unsuccessful. Not enough ports have been opened");
@ -444,29 +459,29 @@ var Terminal = {
runScript: function(scriptName) {
//Check if this script is already running
for (var i = 0; i < Player.currentServer.runningScripts.length; i++) {
if (Player.currentServer.runningScripts[i] == scriptName) {
for (var i = 0; i < Player.getCurrentServer().runningScripts.length; i++) {
if (Player.getCurrentServer().runningScripts[i] == scriptName) {
post("ERROR: This script is already running. Cannot run multiple instances");
return;
}
}
//Check if the script exists and if it does run it
for (var i = 0; i < Player.currentServer.scripts.length; i++) {
if (Player.currentServer.scripts[i].filename == scriptName) {
if (Player.currentServer.hasAdminRights == false) {
for (var i = 0; i < Player.getCurrentServer().scripts.length; i++) {
if (Player.getCurrentServer().scripts[i].filename == scriptName) {
if (Player.getCurrentServer().hasAdminRights == false) {
post("Need root access to run script");
} else {
var filename = Player.currentServer.scripts[i].filename;
var filename = Player.getCurrentServer().scripts[i].filename;
//Add to current server's runningScripts
Player.currentServer.runningScripts.push(filename)
Player.getCurrentServer().runningScripts.push(filename)
//Create WorkerScript
var s = new WorkerScript();
s.name = filename;
s.code = Player.currentServer.scripts[i].code;
s.hostname = Player.currentServer.hostname;
s.code = Player.getCurrentServer().scripts[i].code;
s.hostname = Player.getCurrentServer().hostname;
workerScripts.push(s);
console.log("Pushed script onto workerScripts");
return;

@ -12,15 +12,12 @@ var Engine = {
Clickables: {
hackButton: null,
//Load, save, and delete
saveButton: null,
loadButton: null,
deleteButton: null,
//Main menu buttons
terminalMainMenuButton: null,
characterMainMenuButton: null,
scriptEditorMainMenuButton: null,
saveMainMenuButton: null,
deleteMainMenuButton: null,
},
//Display objects
@ -61,11 +58,11 @@ var Engine = {
//Save function
saveGame: function() {
var PlayerSave = JSON.stringify(Player);
var ForeignServersSave = JSON.stringify(ForeignServers);
var AllServersSave = JSON.stringify(AllServers);
//TODO Add factions + companies here when they're done
window.localStorage.setItem("netburnerPlayerSave", PlayerSave);
window.localStorage.setItem("netburnerForeignServersSave", ForeignServersSave)
window.localStorage.setItem("netburnerAllServersSave", AllServersSave);
console.log("Game saved to local storage");
},
@ -75,14 +72,14 @@ var Engine = {
if (!window.localStorage.getItem("netburnerPlayerSave")) {
console.log("No Player save to load");
return false;
} else if (!window.localStorage.getItem("netburnerForeignServersSave")) {
console.log("No ForeignServers save to load");
return false;
} else if (!window.localStorage.getItem("netburnerAllServersSave")) {
console.log("No AllServers save to load");
return false;
} else {
var PlayerSave = window.localStorage.getItem("netburnerPlayerSave");
var ForeignServersSave = window.localStorage.getItem("netburnerForeignServersSave");
Player = JSON.parse(PlayerSave);
ForeignServers = JSON.parse(ForeignServersSave);
var AllServersSave = window.localStorage.getItem("netburnerAllServersSave");
Player = JSON.parse(PlayerSave, Reviver);
AllServers = JSON.parse(AllServersSave, Reviver);
return true;
}
},
@ -92,12 +89,11 @@ var Engine = {
if (!window.localStorage.getItem("netburnerPlayerSave")) {
console.log("No Player Save to delete");
return false;
} else if (!window.localStorage.getItem("netburnerForeignServersSave")) {
console.log("No ForeignServers Save to delete");
return false;
} else if (!window.localStorage.getItem("netburnerAllServersSave")) {
console.log("No AllServers Save to delete");
} else {
window.localStorage.removeItem("netburnerPlayerSave");
window.localStorage.removeItem("netburnerForeignServersSave");
window.localStorage.removeItem("netburnerAllServersSave");
console.log("Deleted saves")
return true;
}
@ -231,33 +227,12 @@ var Engine = {
//No save found, start new game
console.log("Initializing new game");
Player.init();
ForeignServers.init();
initForeignServers();
Companies.init();
CompanyPositions.init();
}
//if (window.Worker) {
// Engine._scriptWebWorker = new Worker("netscript/NetscriptWorker.js");
//}
//Load, save, and delete buttons
//Engine.Clickables.saveButton = document.getElementById("save");
//Engine.Clickables.saveButton.addEventListener("click", function() {
// Engine.saveFile();
// return false;
//});
//Engine.Clickables.loadButton = document.getElementById("load");
//Engine.Clickables.loadButton.addEventListener("click", function() {
// Engine.loadSave();
// return false;
//});
//Engine.Clickables.deleteButton = document.getElementById("delete");
//Engine.Clickables.deleteButton.addEventListener("click", function() {
// Engine.deleteSave();
// return false;
//});
PrintAllServers();
//Main menu buttons and content
Engine.Clickables.terminalMainMenuButton = document.getElementById("terminal-menu-link");
@ -278,6 +253,18 @@ var Engine = {
return false;
});
Engine.Clickables.saveMainMenuButton = document.getElementById("save-game-link");
Engine.Clickables.saveMainMenuButton.addEventListener("click", function() {
Engine.saveGame();
return false;
});
Engine.Clickables.deleteMainMenuButton = document.getElementById("delete-game-link");
Engine.Clickables.deleteMainMenuButton.addEventListener("click", function() {
Engine.deleteSave();
return false;
});
Engine.Display.terminalContent = document.getElementById("terminal-container");
Engine.currentPage = Engine.Page.Terminal;
Engine.Display.characterContent = document.getElementById("character-container");

41
utils/IPAddress.js Normal file

@ -0,0 +1,41 @@
/* Functions to deal with manipulating IP addresses*/
//Generate a random IP address
//Will not return an IP address that already exists in the AllServers array
createRandomIp = function() {
var ip = createRandomByte() +'.' +
createRandomByte() +'.' +
createRandomByte() +'.' +
createRandomByte();
//If the Ip already exists, recurse to create a new one
if (ipExists(ip)) {
return createRandomIp();
}
return ip;
}
//Returns true if the IP already exists in one of the game's servers
ipExists = function(ip) {
for (var property in AllServers) {
if (AllServers.hasOwnProperty(property)) {
if (property == ip) {
return true;
}
}
}
return false;
}
createRandomByte = function() {
return Math.round(Math.random()*256);
}
isValidIPAddress = function(ipaddress) {
if (/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(ipaddress))
{
return true;
}
console.log("Invalid IP address");
return false ;
}

@ -6,18 +6,19 @@
// constructor that has a `fromJSON` property on it, it hands
// off to that `fromJSON` fuunction, passing in the value.
function Reviver(key, value) {
var ctor;
if (typeof value === "object" &&
typeof value.ctor === "string" &&
typeof value.data !== "undefined") {
ctor = Reviver.constructors[value.ctor] || window[value.ctor];
if (typeof ctor === "function" &&
typeof ctor.fromJSON === "function") {
return ctor.fromJSON(value);
}
}
return value;
var ctor;
//console.log("Reviver called with key: " + key + ", and value: " + value);
if (typeof value === "object" &&
typeof value.ctor === "string" &&
typeof value.data !== "undefined") {
ctor = Reviver.constructors[value.ctor] || window[value.ctor];
if (typeof ctor === "function" &&
typeof ctor.fromJSON === "function") {
return ctor.fromJSON(value);
}
}
return value;
}
Reviver.constructors = {}; // A list of constructors the smart reviver should know about
@ -35,6 +36,7 @@ Reviver.constructors = {}; // A list of constructors the smart reviver should kn
function Generic_toJSON(ctorName, obj, keys) {
var data, index, key;
console.log("Generic_toJSON() called");
if (!keys) {
keys = Object.keys(obj); // Only "own" properties are included
}
@ -62,4 +64,4 @@ function Generic_fromJSON(ctor, data) {
obj[name] = data[name];
}
return obj;
}
}