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

@ -5,4 +5,26 @@ CONSTANTS = {
//Time (ms) it takes to run one operation in Netscript. //Time (ms) it takes to run one operation in Netscript.
CodeInstructionRunTime: 1500, 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 //Netburner Player class
function PlayerObject() {
var Player = { //Skills and stats
//Skills and stats this.hacking_skill = 1;
hacking_skill: 1,
//Fighting
//Fighting this.strength = 1; //Damage dealt
strength: 1, //Damage dealt this.defense = 1; //Damage received
defense: 1, //Damage received this.dexterity = 1; //Accuracy
dexterity: 1, //Accuracy this.agility = 1; //Dodge %
agility: 1, //Dodge %
//Labor stats
//Labor stats this.charisma = 1;
charisma: 1,
//Hacking multipliers
//Hacking multipliers this.hacking_chance_multiplier = 2; //Increase through ascensions/augmentations
hacking_chance_multiplier: 2, //Increase through ascensions/augmentations //this.hacking_speed_multiplier = 5; //Decrease through ascensions/augmentations
//hacking_speed_multiplier: 5, //Decrease through ascensions/augmentations this.hacking_speed_multiplier = 1; //Make it faster for debugging
hacking_speed_multiplier: 1, //Make it faster for debugging this.hacking_money_multiplier = .01; //Increase through ascensions/augmentations. Can't go above 1
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
//Note: "Lifetime" refers to current ascension, "total" refers to the entire game history //Accumulative stats and skills
//Accumulative stats and skills this.total_hacking = 1;
total_hacking: 1, this.total_strength = 1;
total_strength: 1, this.total_defense = 1;
total_defense: 1, this.total_dexterity = 1;
total_dexterity: 1, this.total_agility = 1;
total_agility: 1, this.total_charisma = 1;
total_charisma: 1, this.lifetime_hacking = 1;
lifetime_hacking: 1, this.lifetime_strength = 1;
lifetime_strength: 1, this.lifetime_defense = 1;
lifetime_defense: 1, this.lifetime_dexterity = 1;
lifetime_dexterity: 1, this.lifetime_agility = 1;
lifetime_agility: 1, this.lifetime_charisma = 1;
lifetime_charisma: 1,
//Experience and multipliers
//Experience and multipliers this.hacking_exp = 0;
hacking_exp: 0, this.strength_exp = 0;
strength_exp: 0, this.defense_exp = 0;
defense_exp: 0, this.dexterity_exp = 0;
dexterity_exp: 0, this.agility_exp = 0;
agility_exp: 0, this.charisma_exp = 0;
charisma_exp: 0,
this.hacking_exp_mult = 1;
hacking_exp_mult: 1, this.strength_exp_mult = 1;
strength_exp_mult: 1, this.defense_exp_mult = 1;
defense_exp_mult: 1, this.dexterity_exp_mult = 1;
dexterity_exp_mult: 1, this.agility_exp_mult = 1;
agility_exp_mult: 1, this.charisma_exp_mult = 1;
charisma_exp_mult: 1,
this.company_rep_mult = 1; //Multiplier for how fast the player gains reputation at a company
company_rep_mult: 1, //Multiplier for how fast the player gains reputation at a company
//Money
//Money this.money = 0;
money: 0, this.total_money = 0;
total_money: 0, this.lifetime_money = 0;
lifetime_money: 0,
//Starting (home) computer
//Starting (home) computer this.homeComputer = null;
homeComputer: new Server(),
//Servers
//Servers this.currentServer = null; //Server currently being accessed through terminal
currentServer: null, //Server currently being accessed through terminal this.discoveredServers = []; //Secret servers not in the network that you have discovered
discoveredServers: [], this.purchasedServers = [];
purchasedServers: [],
//Achievements and achievement progress
//Achievements and achievement progress
//Flag to let the engine know the player is starting a hack
//Flag to let the engine know the player is starting a hack this.startAction = false;
startAction: false, this.actionTime = 0;
actionTime: 0, };
PlayerObject.prototype.init = function() {
init: function() { /* Initialize Player's home computer */
/* Initialize properties of Player's home computer */ var t_homeComp = new Server();
Player.homeComputer.init("19.42.93.219", "home", "Home PC", true, true, true, true, 1); t_homeComp.init(createRandomIp(), "home", "Home PC", true, true, true, true, 1);
Player.currentServer = Player.homeComputer; this.homeComputer = t_homeComp.ip;
this.currentServer = t_homeComp.ip;
Player.homeComputer.programs.push("PortHack.exe"); AddToAllServers(t_homeComp);
var NetworkGroup1 = [ForeignServers.IronGym, ForeignServers.FoodNStuff, ForeignServers.SigmaCosmetics, ForeignServers.JoesGuns, ForeignServers.HongFangTeaHouse, ForeignServers.HaraKiriSushiBar]; this.getHomeComputer().programs.push("PortHack.exe");
for (var i = 0; i < NetworkGroup1.length; i++) { }
Player.homeComputer.serversOnNetwork.push(NetworkGroup1[i]);
NetworkGroup1[i].serversOnNetwork.push(Player.homeComputer); PlayerObject.prototype.getCurrentServer = function() {
} return AllServers[this.currentServer];
}, }
//Calculates skill level based on experience. The same formula will be used for every skill PlayerObject.prototype.getHomeComputer = function() {
// At the maximum possible exp (MAX_INT = 9007199254740991), the hacking skill will be 1796 return AllServers[this.homeComputer];
// 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 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
//Calculates the chance of hacking a server PlayerObject.prototype.calculateSkill = function(exp) {
//The formula is: return Math.max(Math.floor(50 * log(9007199254740991+ 2.270) - 40), 1);
// (hacking_chance_multiplier * hacking_skill - requiredLevel) 100 - difficulty },
// ----------------------------------------------------------- * -----------------
// (hacking_chance_multiplier * hacking_skill) 100 //Calculates the chance of hacking a server
calculateHackingChance: function() { //The formula is:
var difficultyMult = (100 - Player.currentServer.hackDifficulty) / 100; // (hacking_chance_multiplier * hacking_skill - requiredLevel) 100 - difficulty
var skillMult = (Player.hacking_chance_multiplier * Player.hacking_skill); // ----------------------------------------------------------- * -----------------
var skillChance = (skillMult - Player.currentServer.requiredHackingSkill) / skillMult; // (hacking_chance_multiplier * hacking_skill) 100
return (skillChance * difficultyMult); PlayerObject.prototype.calculateHackingChance = function() {
}, var difficultyMult = (100 - this.getCurrentServer().hackDifficulty) / 100;
var skillMult = (this.hacking_chance_multiplier * this.hacking_skill);
//Calculate the time it takes to hack a server in seconds. Returns the time var skillChance = (skillMult - this.getCurrentServer().requiredHackingSkill) / skillMult;
//The formula is: return (skillChance * difficultyMult);
// (requiredLevel * difficulty) },
// ------------------------------- * hacking_speed_multiplier
// hacking_skill //Calculate the time it takes to hack a server in seconds. Returns the time
calculateHackingTime: function() { //The formula is:
var difficultyMult = Player.currentServer.requiredHackingSkill * Player.currentServer.hackDifficulty; // (requiredLevel * difficulty)
var skillFactor = difficultyMult / Player.hacking_skill; // ------------------------------- * hacking_speed_multiplier
return skillFactor * Player.hacking_speed_multiplier; // hacking_skill
}, PlayerObject.prototype.calculateHackingTime = function() {
var difficultyMult = this.getCurrentServer().requiredHackingSkill * this.getCurrentServer().hackDifficulty;
//Calculates the PERCENTAGE of a server's money that the player will hack from the server if successful var skillFactor = difficultyMult / this.hacking_skill;
//The formula is: return skillFactor * this.hacking_speed_multiplier;
// (hacking_skill - (requiredLevel-1)) 100 - difficulty }
// --------------------------------------* ----------------------- * hacking_money_multiplier
// hacking_skill 100 //Calculates the PERCENTAGE of a server's money that the player will hack from the server if successful
calculatePercentMoneyHacked: function() { //The formula is:
var difficultyMult = (100 - Player.currentServer.hackDifficulty) / 100; // (hacking_skill - (requiredLevel-1)) 100 - difficulty
var skillMult = (Player.hacking_skill - (Player.currentServer.requiredHackingSkill - 1)) / Player.hacking_skill; // --------------------------------------* ----------------------- * hacking_money_multiplier
var percentMoneyHacked = difficultyMult * skillMult * Player.hacking_money_multiplier; // hacking_skill 100
console.log("Percent money hacked calculated to be: " + percentMoneyHacked); PlayerObject.prototype.calculatePercentMoneyHacked = function() {
return percentMoneyHacked; 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;
//Returns how much EXP the player gains on a successful hack console.log("Percent money hacked calculated to be: " + percentMoneyHacked);
//The formula is: return percentMoneyHacked;
// difficulty * requiredLevel * hacking_multiplier }
//
// Note: Keep it at an integer for now, //Returns how much EXP the player gains on a successful hack
calculateExpGain: function() { //The formula is:
return Math.round(Player.currentServer.hackDifficulty * Player.currentServer.requiredHackingSkill * Player.hacking_exp_mult); // difficulty * requiredLevel * hacking_multiplier
}, //
// Note: Keep it at an integer for now,
//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 PlayerObject.prototype.calculateExpGain = function() {
//This assumes that the server being hacked is not purchased by the player, that the player's hacking skill is greater than the return Math.round(this.getCurrentServer().hackDifficulty * this.getCurrentServer().requiredHackingSkill * this.hacking_exp_mult);
//required hacking skill and that the player has admin rights. }
hack: function() {
Player.actionTime = Player.calculateHackingTime(); //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
console.log("Hacking time: " + Player.actionTime); //This assumes that the server being hacked is not purchased by the player, that the player's hacking skill is greater than the
//Set the startHack flag so the engine starts the hacking process //required hacking skill and that the player has admin rights.
Player.startAction = true; 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"; filename += ".script";
//If the current script matches one thats currently running, throw an error //If the current script matches one thats currently running, throw an error
for (var i = 0; i < Player.currentServer.runningScripts.length; i++) { for (var i = 0; i < Player.getCurrentServer().runningScripts.length; i++) {
if (filename == Player.currentServer.runningScripts[i].filename) { if (filename == Player.getCurrentServer().runningScripts[i].filename) {
postScriptEditorStatus("Cannot write to script that is currently running!"); postScriptEditorStatus("Cannot write to script that is currently running!");
return; return;
} }
} }
//If the current script already exists on the server, overwrite it //If the current script already exists on the server, overwrite it
for (var i = 0; i < Player.currentServer.scripts.length; i++) { for (var i = 0; i < Player.getCurrentServer().scripts.length; i++) {
if (filename == Player.currentServer.scripts[i].filename) { if (filename == Player.getCurrentServer().scripts[i].filename) {
Player.currentServer.scripts[i].saveScript(); Player.getCurrentServer().scripts[i].saveScript();
Engine.loadTerminalContent(); Engine.loadTerminalContent();
return; return;
} }
@ -35,7 +35,7 @@ $(document).keydown(function(e) {
//If the current script does NOT exist, create a new one //If the current script does NOT exist, create a new one
var script = new Script(); var script = new Script();
script.saveScript(); script.saveScript();
Player.currentServer.scripts.push(script); Player.getCurrentServer().scripts.push(script);
Engine.loadTerminalContent(); Engine.loadTerminalContent();
} }
} }
@ -62,16 +62,11 @@ function postScriptEditorStatus(text) {
}, 3000); }, 3000);
} }
function Script() { 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 = [];
this.filename = ""; this.filename = "";
this.code = ""; this.code = "";
this.ramUsage = 0; 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 */ /* 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. //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() { function TestObj() {
this.value = 1; this.num = 1;
} }
TestObj.prototype.setValue = function(val) { 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(); var testObj = new TestObj();
//Terminal //Terminal
@ -83,9 +95,9 @@ var Terminal = {
var expGainedOnFailure = Math.round(expGainedOnSuccess / 4); var expGainedOnFailure = Math.round(expGainedOnSuccess / 4);
if (rand < hackChance) { //Success! if (rand < hackChance) { //Success!
var moneyGained = Player.calculatePercentMoneyHacked(); 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.money += moneyGained;
Player.hacking_exp += expGainedOnSuccess; Player.hacking_exp += expGainedOnSuccess;
@ -94,7 +106,7 @@ var Terminal = {
} else { //Failure } else { //Failure
//Player only gains 25% exp for failure? TODO Can change this later to balance //Player only gains 25% exp for failure? TODO Can change this later to balance
Player.hacking_exp += expGainedOnFailure; 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 //Rename the progress bar so that the next hacks dont trigger it. Re-enable terminal
@ -107,38 +119,38 @@ var Terminal = {
}, },
finishAnalyze: function() { finishAnalyze: function() {
post(Player.currentServer.hostname + ": "); post(Player.getCurrentServer().hostname + ": ");
post("Required hacking skill: " + Player.currentServer.requiredHackingSkill); post("Required hacking skill: " + Player.getCurrentServer().requiredHackingSkill);
//TODO Make these actual estimates by adding a random offset to result? //TODO Make these actual estimates by adding a random offset to result?
//TODO Change the text to sound better //TODO Change the text to sound better
post("Estimated chance to hack: " + Math.round(Player.calculateHackingChance() * 100) + "%"); post("Estimated chance to hack: " + Math.round(Player.calculateHackingChance() * 100) + "%");
post("Estimated time to hack: " + Math.round(Player.calculateHackingTime()) + " seconds"); post("Estimated time to hack: " + Math.round(Player.calculateHackingTime()) + " seconds");
post("Required number of open ports for PortHack: " +Player.currentServer.numOpenPortsRequired); post("Required number of open ports for PortHack: " +Player.getCurrentServer().numOpenPortsRequired);
if (Player.currentServer.sshPortOpen) { if (Player.getCurrentServer().sshPortOpen) {
post("SSH port: Open") post("SSH port: Open")
} else { } else {
post("SSH port: Closed") post("SSH port: Closed")
} }
if (Player.currentServer.ftpPortOpen) { if (Player.getCurrentServer().ftpPortOpen) {
post("FTP port: Open") post("FTP port: Open")
} else { } else {
post("FTP port: Closed") post("FTP port: Closed")
} }
if (Player.currentServer.smtpPortOpen) { if (Player.getCurrentServer().smtpPortOpen) {
post("SMTP port: Open") post("SMTP port: Open")
} else { } else {
post("SMTP port: Closed") post("SMTP port: Closed")
} }
if (Player.currentServer.httpPortOpen) { if (Player.getCurrentServer().httpPortOpen) {
post("HTTP port: Open") post("HTTP port: Open")
} else { } else {
post("HTTP port: Closed") post("HTTP port: Closed")
} }
if (Player.currentServer.sqlPortOpen) { if (Player.getCurrentServer().sqlPortOpen) {
post("SQL port: Open") post("SQL port: Open")
} else { } else {
post("SQL port: Closed") post("SQL port: Closed")
@ -196,10 +208,10 @@ var Terminal = {
var ip = commandArray[1]; var ip = commandArray[1];
for (var i = 0; i < Player.currentServer.serversOnNetwork.length; i++) { for (var i = 0; i < Player.getCurrentServer().serversOnNetwork.length; i++) {
if (Player.currentServer.serversOnNetwork[i].ip == ip || Player.currentServer.serversOnNetwork[i].hostname == ip) { if (Player.getCurrentServer().getServerOnNetwork(i).ip == ip || Player.getCurrentServer().getServerOnNetwork(i).hostname == ip) {
Player.currentServer.isConnectedTo = false; Player.getCurrentServer().isConnectedTo = false;
Player.currentServer = Player.currentServer.serversOnNetwork[i]; Player.currentServer = Player.getCurrentServer().getServerOnNetwork(i).ip;
post("Connected to " + ip); post("Connected to " + ip);
return; return;
} }
@ -207,14 +219,14 @@ var Terminal = {
post("Host not found"); post("Host not found");
break; break;
case "df": case "free":
if (commandArray.length != 1) { if (commandArray.length != 1) {
post("Incorrect usage of df command. Usage: df"); return; post("Incorrect usage of df command. Usage: df"); return;
} }
console.log("df terminal command called"); console.log("df terminal command called");
post("Total: " + Player.currentServer.maxRam.toString() + " GB"); post("Total: " + Player.getCurrentServer().maxRam.toString() + " GB");
post("Used: " + Player.currentServer.ramUsed.toString() + " GB"); post("Used: " + Player.getCurrentServer().ramUsed.toString() + " GB");
post("Available: " + (Player.currentServer.maxRam - Player.currentServer.ramUsed).toString() + " GB"); post("Available: " + (Player.getCurrentServer().maxRam - Player.getCurrentServer().ramUsed).toString() + " GB");
break; break;
case "hack": case "hack":
if (commandArray.length != 1) { if (commandArray.length != 1) {
@ -222,11 +234,11 @@ var Terminal = {
} }
//Hack the current PC (usually for money) //Hack the current PC (usually for money)
//You can't hack your home pc or servers you purchased //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"); 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"); 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"); post("Your hacking skill is not high enough to attempt hacking this machine. Try analyzing the machine to determine the required hacking skill");
} else { } else {
Terminal.hackFlag = true; Terminal.hackFlag = true;
@ -248,14 +260,14 @@ var Terminal = {
post("Incorrect usage of hostname command. Usage: hostname"); return; post("Incorrect usage of hostname command. Usage: hostname"); return;
} }
//Print the hostname of current system //Print the hostname of current system
post(Player.currentServer.hostname); post(Player.getCurrentServer().hostname);
break; break;
case "ifconfig": case "ifconfig":
if (commandArray.length != 1) { if (commandArray.length != 1) {
post("Incorrect usage of ifconfig command. Usage: ifconfig"); return; post("Incorrect usage of ifconfig command. Usage: ifconfig"); return;
} }
//Print the IP address of the current system //Print the IP address of the current system
post(Player.currentServer.ip); post(Player.getCurrentServer().ip);
break; break;
case "kill": case "kill":
//TODO //TODO
@ -269,11 +281,11 @@ var Terminal = {
var allFiles = []; var allFiles = [];
//Get all of the programs and scripts on the machine into one temporary array //Get all of the programs and scripts on the machine into one temporary array
for (var i = 0; i < Player.currentServer.programs.length; i++) { for (var i = 0; i < Player.getCurrentServer().programs.length; i++) {
allFiles.push(Player.currentServer.programs[i]); allFiles.push(Player.getCurrentServer().programs[i]);
} }
for (var i = 0; i < Player.currentServer.scripts.length; i++) { for (var i = 0; i < Player.getCurrentServer().scripts.length; i++) {
allFiles.push(Player.currentServer.scripts[i].filename); allFiles.push(Player.getCurrentServer().scripts[i].filename);
} }
//Sort the files alphabetically then print each //Sort the files alphabetically then print each
@ -299,16 +311,16 @@ var Terminal = {
var scriptname = filename.substr(0, filename.indexOf(".script")); var scriptname = filename.substr(0, filename.indexOf(".script"));
//Cannot edit scripts that are currently running //Cannot edit scripts that are currently running
for (var i = 0; i < Player.currentServer.runningScripts.length; i++) { for (var i = 0; i < Player.getCurrentServer().runningScripts.length; i++) {
if (filename == Player.currentServer.runningScripts[i].filename) { if (filename == Player.getCurrentServer().runningScripts[i].filename) {
post("Cannot open/edit scripts that are currently running!"); return; post("Cannot open/edit scripts that are currently running!"); return;
} }
} }
//Check if the script already exists //Check if the script already exists
for (var i = 0; i < Player.currentServer.scripts.length; i++) { for (var i = 0; i < Player.getCurrentServer().scripts.length; i++) {
if (filename == Player.currentServer.scripts[i].filename) { if (filename == Player.getCurrentServer().scripts[i].filename) {
Engine.loadScriptEditorContent(scriptname, Player.currentServer.scripts[i].code); Engine.loadScriptEditorContent(scriptname, Player.getCurrentServer().scripts[i].code);
return; return;
} }
} }
@ -322,24 +334,24 @@ var Terminal = {
//Displays available network connections using TCP //Displays available network connections using TCP
console.log("netstat/scan terminal command called"); console.log("netstat/scan terminal command called");
post("Hostname IP Root Access"); 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 //Add hostname
var entry = Player.currentServer.serversOnNetwork[i].hostname; var entry = Player.getCurrentServer().getServerOnNetwork(i).hostname;
//Calculate padding and add IP //Calculate padding and add IP
var numSpaces = 21 - entry.length; var numSpaces = 21 - entry.length;
var spaces = Array(numSpaces+1).join(" "); var spaces = Array(numSpaces+1).join(" ");
entry += spaces; entry += spaces;
entry += Player.currentServer.serversOnNetwork[i].ip; entry += Player.getCurrentServer().getServerOnNetwork(i).ip;
//Calculate padding and add root access info //Calculate padding and add root access info
var hasRoot; var hasRoot;
if (Player.currentServer.serversOnNetwork[i].hasAdminRights) { if (Player.getCurrentServer().getServerOnNetwork(i).hasAdminRights) {
hasRoot = 'Y'; hasRoot = 'Y';
} else { } else {
hasRoot = 'N'; hasRoot = 'N';
} }
numSpaces = 21 - Player.currentServer.serversOnNetwork[i].ip.length; numSpaces = 21 - Player.getCurrentServer().getServerOnNetwork(i).ip.length;
spaces = Array(numSpaces+1).join(" "); spaces = Array(numSpaces+1).join(" ");
entry += spaces; entry += spaces;
entry += hasRoot; entry += hasRoot;
@ -373,13 +385,15 @@ var Terminal = {
case "scp": case "scp":
//TODO //TODO
break; break;
case "top":
//TODO List each's script RAM usage
break;
case "test": case "test":
post(testObj.value.toString()); post(testObj.num.toString());
testObj.setValue(testObj.value + 1); testObj.setValue(testObj.num + 1);
break; break;
case "testSave": case "testSave":
var testSave = JSONfn.stringify(testObj); var testSave = JSON.stringify(testObj);
window.localStorage.setItem("netburnerTest", testSave); window.localStorage.setItem("netburnerTest", testSave);
console.log("Netburner TestSave saved"); console.log("Netburner TestSave saved");
break; break;
@ -387,8 +401,9 @@ var Terminal = {
if (!window.localStorage.getItem("netburnerTest")) { if (!window.localStorage.getItem("netburnerTest")) {
console.log("No TestSave file to load"); console.log("No TestSave file to load");
} else { } else {
console.log("Here");
var testSave = window.localStorage.getItem("netburnerTest"); var testSave = window.localStorage.getItem("netburnerTest");
testObj = JSONfn.parse(testSave); testObj = JSON.parse(testSave, Reviver);
console.log("TestSave loaded"); console.log("TestSave loaded");
} }
break; break;
@ -410,8 +425,8 @@ var Terminal = {
runProgram: function(programName) { runProgram: function(programName) {
//Check if you have the program on your computer. If you do, execute it, otherwise //Check if you have the program on your computer. If you do, execute it, otherwise
//display an error message //display an error message
for (var i = 0; i < Player.homeComputer.programs.length; i++) { for (var i = 0; i < Player.getHomeComputer().programs.length; i++) {
if (Player.homeComputer.programs[i] == programName) { if (Player.getHomeComputer().programs[i] == programName) {
Terminal.executeProgram(programName); Terminal.executeProgram(programName);
return; return;
} }
@ -423,13 +438,13 @@ var Terminal = {
executeProgram: function(programName) { executeProgram: function(programName) {
switch (programName) { switch (programName) {
case "PortHack.exe": 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"); post("You already have root access to this computer. There is no reason to run PortHack.exe");
} else { } else {
console.log("Running PortHack executable"); console.log("Running PortHack executable");
if (Player.currentServer.openPortCount >= Player.currentServer.numOpenPortsRequired) { if (Player.getCurrentServer().openPortCount >= Player.getCurrentServer().numOpenPortsRequired) {
Player.currentServer.hasAdminRights = true; Player.getCurrentServer().hasAdminRights = true;
post("PortHack successful! Gained root access to " + Player.currentServer.hostname); post("PortHack successful! Gained root access to " + Player.getCurrentServer().hostname);
//TODO Make this take time rather than be instant //TODO Make this take time rather than be instant
} else { } else {
post("PortHack unsuccessful. Not enough ports have been opened"); post("PortHack unsuccessful. Not enough ports have been opened");
@ -444,29 +459,29 @@ var Terminal = {
runScript: function(scriptName) { runScript: function(scriptName) {
//Check if this script is already running //Check if this script is already running
for (var i = 0; i < Player.currentServer.runningScripts.length; i++) { for (var i = 0; i < Player.getCurrentServer().runningScripts.length; i++) {
if (Player.currentServer.runningScripts[i] == scriptName) { if (Player.getCurrentServer().runningScripts[i] == scriptName) {
post("ERROR: This script is already running. Cannot run multiple instances"); post("ERROR: This script is already running. Cannot run multiple instances");
return; return;
} }
} }
//Check if the script exists and if it does run it //Check if the script exists and if it does run it
for (var i = 0; i < Player.currentServer.scripts.length; i++) { for (var i = 0; i < Player.getCurrentServer().scripts.length; i++) {
if (Player.currentServer.scripts[i].filename == scriptName) { if (Player.getCurrentServer().scripts[i].filename == scriptName) {
if (Player.currentServer.hasAdminRights == false) { if (Player.getCurrentServer().hasAdminRights == false) {
post("Need root access to run script"); post("Need root access to run script");
} else { } else {
var filename = Player.currentServer.scripts[i].filename; var filename = Player.getCurrentServer().scripts[i].filename;
//Add to current server's runningScripts //Add to current server's runningScripts
Player.currentServer.runningScripts.push(filename) Player.getCurrentServer().runningScripts.push(filename)
//Create WorkerScript //Create WorkerScript
var s = new WorkerScript(); var s = new WorkerScript();
s.name = filename; s.name = filename;
s.code = Player.currentServer.scripts[i].code; s.code = Player.getCurrentServer().scripts[i].code;
s.hostname = Player.currentServer.hostname; s.hostname = Player.getCurrentServer().hostname;
workerScripts.push(s); workerScripts.push(s);
console.log("Pushed script onto workerScripts"); console.log("Pushed script onto workerScripts");
return; return;

@ -12,15 +12,12 @@ var Engine = {
Clickables: { Clickables: {
hackButton: null, hackButton: null,
//Load, save, and delete
saveButton: null,
loadButton: null,
deleteButton: null,
//Main menu buttons //Main menu buttons
terminalMainMenuButton: null, terminalMainMenuButton: null,
characterMainMenuButton: null, characterMainMenuButton: null,
scriptEditorMainMenuButton: null, scriptEditorMainMenuButton: null,
saveMainMenuButton: null,
deleteMainMenuButton: null,
}, },
//Display objects //Display objects
@ -61,11 +58,11 @@ var Engine = {
//Save function //Save function
saveGame: function() { saveGame: function() {
var PlayerSave = JSON.stringify(Player); var PlayerSave = JSON.stringify(Player);
var ForeignServersSave = JSON.stringify(ForeignServers); var AllServersSave = JSON.stringify(AllServers);
//TODO Add factions + companies here when they're done //TODO Add factions + companies here when they're done
window.localStorage.setItem("netburnerPlayerSave", PlayerSave); window.localStorage.setItem("netburnerPlayerSave", PlayerSave);
window.localStorage.setItem("netburnerForeignServersSave", ForeignServersSave) window.localStorage.setItem("netburnerAllServersSave", AllServersSave);
console.log("Game saved to local storage"); console.log("Game saved to local storage");
}, },
@ -75,14 +72,14 @@ var Engine = {
if (!window.localStorage.getItem("netburnerPlayerSave")) { if (!window.localStorage.getItem("netburnerPlayerSave")) {
console.log("No Player save to load"); console.log("No Player save to load");
return false; return false;
} else if (!window.localStorage.getItem("netburnerForeignServersSave")) { } else if (!window.localStorage.getItem("netburnerAllServersSave")) {
console.log("No ForeignServers save to load"); console.log("No AllServers save to load");
return false; return false;
} else { } else {
var PlayerSave = window.localStorage.getItem("netburnerPlayerSave"); var PlayerSave = window.localStorage.getItem("netburnerPlayerSave");
var ForeignServersSave = window.localStorage.getItem("netburnerForeignServersSave"); var AllServersSave = window.localStorage.getItem("netburnerAllServersSave");
Player = JSON.parse(PlayerSave); Player = JSON.parse(PlayerSave, Reviver);
ForeignServers = JSON.parse(ForeignServersSave); AllServers = JSON.parse(AllServersSave, Reviver);
return true; return true;
} }
}, },
@ -92,12 +89,11 @@ var Engine = {
if (!window.localStorage.getItem("netburnerPlayerSave")) { if (!window.localStorage.getItem("netburnerPlayerSave")) {
console.log("No Player Save to delete"); console.log("No Player Save to delete");
return false; return false;
} else if (!window.localStorage.getItem("netburnerForeignServersSave")) { } else if (!window.localStorage.getItem("netburnerAllServersSave")) {
console.log("No ForeignServers Save to delete"); console.log("No AllServers Save to delete");
return false;
} else { } else {
window.localStorage.removeItem("netburnerPlayerSave"); window.localStorage.removeItem("netburnerPlayerSave");
window.localStorage.removeItem("netburnerForeignServersSave"); window.localStorage.removeItem("netburnerAllServersSave");
console.log("Deleted saves") console.log("Deleted saves")
return true; return true;
} }
@ -231,33 +227,12 @@ var Engine = {
//No save found, start new game //No save found, start new game
console.log("Initializing new game"); console.log("Initializing new game");
Player.init(); Player.init();
ForeignServers.init(); initForeignServers();
Companies.init(); Companies.init();
CompanyPositions.init(); CompanyPositions.init();
} }
//if (window.Worker) { PrintAllServers();
// 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;
//});
//Main menu buttons and content //Main menu buttons and content
Engine.Clickables.terminalMainMenuButton = document.getElementById("terminal-menu-link"); Engine.Clickables.terminalMainMenuButton = document.getElementById("terminal-menu-link");
@ -278,6 +253,18 @@ var Engine = {
return false; 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.Display.terminalContent = document.getElementById("terminal-container");
Engine.currentPage = Engine.Page.Terminal; Engine.currentPage = Engine.Page.Terminal;
Engine.Display.characterContent = document.getElementById("character-container"); 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 // constructor that has a `fromJSON` property on it, it hands
// off to that `fromJSON` fuunction, passing in the value. // off to that `fromJSON` fuunction, passing in the value.
function Reviver(key, value) { function Reviver(key, value) {
var ctor; var ctor;
//console.log("Reviver called with key: " + key + ", and value: " + value);
if (typeof value === "object" && if (typeof value === "object" &&
typeof value.ctor === "string" && typeof value.ctor === "string" &&
typeof value.data !== "undefined") { typeof value.data !== "undefined") {
ctor = Reviver.constructors[value.ctor] || window[value.ctor]; ctor = Reviver.constructors[value.ctor] || window[value.ctor];
if (typeof ctor === "function" && if (typeof ctor === "function" &&
typeof ctor.fromJSON === "function") { typeof ctor.fromJSON === "function") {
return ctor.fromJSON(value);
} return ctor.fromJSON(value);
} }
return value; }
return value;
} }
Reviver.constructors = {}; // A list of constructors the smart reviver should know about 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) { function Generic_toJSON(ctorName, obj, keys) {
var data, index, key; var data, index, key;
console.log("Generic_toJSON() called");
if (!keys) { if (!keys) {
keys = Object.keys(obj); // Only "own" properties are included keys = Object.keys(obj); // Only "own" properties are included
} }
@ -62,4 +64,4 @@ function Generic_fromJSON(ctor, data) {
obj[name] = data[name]; obj[name] = data[name];
} }
return obj; return obj;
} }