diff --git a/src/ActiveScriptsUI.js b/src/ActiveScriptsUI.js
index 910dde947..fd4338aa7 100644
--- a/src/ActiveScriptsUI.js
+++ b/src/ActiveScriptsUI.js
@@ -32,7 +32,7 @@ import { removeElement } from "../utils/uiHelpers/removeElement";
* ...
*/
const ActiveScriptsUI = {};
-const ActiveScriptsTasks = []; //Sequentially schedule the creation/deletion of UI elements
+const ActiveScriptsTasks = []; // Sequentially schedule the creation/deletion of UI elements
const getHeaderHtml = (server) => {
// TODO: calculate the longest hostname length rather than hard coding it
@@ -51,7 +51,7 @@ const updateHeaderHtml = (server) => {
return;
}
- // convert it to a string, as that's how it's stored it will come out of the data attributes
+ // Convert it to a string, as that's how it's stored it will come out of the data attributes
const ramPercentage = '' + roundToTwo(server.ramUsed / server.maxRam);
if (accordion.header.dataset.ramPercentage !== ramPercentage) {
accordion.header.dataset.ramPercentage = ramPercentage;
@@ -84,16 +84,18 @@ function createActiveScriptsServerPanel(server) {
header: hdr,
panel: panel,
panelList: panelScriptList,
- scripts: {}, //Holds references to li elements for each active script
- scriptHdrs: {}, //Holds references to header elements for each active script
- scriptStats: {} //Holds references to the p elements containing text for each active script
+ scripts: {}, // Holds references to li elements for each active script
+ scriptHdrs: {}, // Holds references to header elements for each active script
+ scriptStats: {}, // Holds references to the p elements containing text for each active script
};
return li;
}
-//Deletes the info for a particular server (Dropdown header + Panel with all info)
-//in the Active Scripts page if it exists
+/**
+ * Deletes the info for a particular server (Dropdown header + Panel with all info)
+ * in the Active Scripts page if it exists
+ */
function deleteActiveScriptsServerPanel(server) {
let hostname = server.hostname;
if (ActiveScriptsUI[hostname] == null) {
@@ -101,9 +103,9 @@ function deleteActiveScriptsServerPanel(server) {
return;
}
- //Make sure it's empty
+ // Make sure it's empty
if (Object.keys(ActiveScriptsUI[hostname].scripts).length > 0) {
- console.log("WARNING: Tried to delete Active Scripts Server panel that still has scripts. Aborting");
+ console.warn("Tried to delete Active Scripts Server panel that still has scripts. Aborting");
return;
}
@@ -115,7 +117,7 @@ function deleteActiveScriptsServerPanel(server) {
function addActiveScriptsItem(workerscript) {
var server = getServer(workerscript.serverIp);
if (server == null) {
- console.log("ERROR: Invalid server IP for workerscript in addActiveScriptsItem()");
+ console.warn("Invalid server IP for workerscript in addActiveScriptsItem()");
return;
}
let hostname = server.hostname;
@@ -125,7 +127,7 @@ function addActiveScriptsItem(workerscript) {
createActiveScriptsServerPanel(server);
}
- //Create the unique identifier (key) for this script
+ // Create the unique identifier (key) for this script
var itemNameArray = ["active", "scripts", hostname, workerscript.name];
for (var i = 0; i < workerscript.args.length; ++i) {
itemNameArray.push(String(workerscript.args[i]));
@@ -142,8 +144,10 @@ function addActiveScriptsItem(workerscript) {
panel.classList.remove("accordion-panel");
panel.classList.add("active-scripts-script-panel");
- //Handle the constant elements on the panel that don't change after creation
- //Threads, args, kill/log button
+ /**
+ * Handle the constant elements on the panel that don't change after creation:
+ * Threads, args, kill/log button
+ */
panel.appendChild(createElement("p", {
innerHTML: "Threads: " + workerscript.scriptRef.threads + " " +
"Args: " + arrayToString(workerscript.args)
@@ -176,7 +180,7 @@ function addActiveScriptsItem(workerscript) {
}
}));
- //Append element to list
+ // Append element to list
ActiveScriptsUI[hostname]["panelList"].appendChild(li);
ActiveScriptsUI[hostname].scripts[itemName] = li;
ActiveScriptsUI[hostname].scriptHdrs[itemName] = hdr;
@@ -221,11 +225,13 @@ function deleteActiveScriptsItem(workerscript) {
}.bind(null, workerscript));
}
-//Update the ActiveScriptsItems array
function updateActiveScriptsItems(maxTasks=150) {
- //Run tasks that need to be done sequentially (adding items, creating/deleting server panels)
- //We'll limit this to 150 at a time in case someone decides to start a bunch of scripts all at once...
- let numTasks = Math.min(maxTasks, ActiveScriptsTasks.length);
+ /**
+ * Run tasks that need to be done sequentially (adding items, creating/deleting server panels)
+ * We'll limit this to 150 at a time for performance (in case someone decides to start a
+ * bunch of scripts all at once...)
+ */
+ const numTasks = Math.min(maxTasks, ActiveScriptsTasks.length);
for (let i = 0; i < numTasks; ++i) {
let task = ActiveScriptsTasks.shift();
try {
@@ -236,8 +242,8 @@ function updateActiveScriptsItems(maxTasks=150) {
}
}
- if (!routing.isOn(Page.ActiveScripts)) {return;}
- var total = 0;
+ if (!routing.isOn(Page.ActiveScripts)) { return; }
+ let total = 0;
for (var i = 0; i < workerScripts.length; ++i) {
try {
total += updateActiveScriptsItemContent(workerScripts[i]);
@@ -249,10 +255,10 @@ function updateActiveScriptsItems(maxTasks=150) {
getElementById("active-scripts-total-production-active").innerText = numeralWrapper.formatMoney(total);
getElementById("active-scripts-total-prod-aug-total").innerText = numeralWrapper.formatMoney(Player.scriptProdSinceLastAug);
getElementById("active-scripts-total-prod-aug-avg").innerText = numeralWrapper.formatMoney(Player.scriptProdSinceLastAug / (Player.playtimeSinceLastAug/1000));
+
return total;
}
-//Updates the content of the given item in the Active Scripts list
function updateActiveScriptsItemContent(workerscript) {
var server = getServer(workerscript.serverIp);
if (server == null) {
@@ -261,7 +267,7 @@ function updateActiveScriptsItemContent(workerscript) {
}
let hostname = server.hostname;
if (ActiveScriptsUI[hostname] == null) {
- return; //Hasn't been created yet. We'll skip it
+ return; // Hasn't been created yet. We'll skip it
}
updateHeaderHtml(server);
@@ -273,11 +279,11 @@ function updateActiveScriptsItemContent(workerscript) {
var itemName = itemNameArray.join("-");
if (ActiveScriptsUI[hostname].scriptStats[itemName] == null) {
- return; //Hasn't been fully added yet. We'll skip it
+ return; // Hasn't been fully added yet. We'll skip it
}
var item = ActiveScriptsUI[hostname].scriptStats[itemName];
- //Update the text if necessary. This fn returns the online $/s production
+ // Update the text if necessary. This fn returns the online $/s production
return updateActiveScriptsText(workerscript, item, itemName);
}
@@ -296,7 +302,7 @@ function updateActiveScriptsText(workerscript, item, itemName) {
updateHeaderHtml(server);
var onlineMps = workerscript.scriptRef.onlineMoneyMade / workerscript.scriptRef.onlineRunningTime;
- //Only update if the item is visible
+ // Only update if the item is visible
if (ActiveScriptsUI[hostname].header.classList.contains("active") === false) {return onlineMps;}
if (ActiveScriptsUI[hostname].scriptHdrs[itemName].classList.contains("active") === false) {return onlineMps;}
@@ -305,7 +311,7 @@ function updateActiveScriptsText(workerscript, item, itemName) {
var onlineTime = "Online Time: " + convertTimeMsToTimeElapsedString(workerscript.scriptRef.onlineRunningTime * 1e3);
var offlineTime = "Offline Time: " + convertTimeMsToTimeElapsedString(workerscript.scriptRef.offlineRunningTime * 1e3);
- //Online
+ // Online
var onlineTotalMoneyMade = "Total online production: " + numeralWrapper.formatMoney(workerscript.scriptRef.onlineMoneyMade);
var onlineTotalExpEarned = (Array(26).join(" ") + numeralWrapper.formatBigNumber(workerscript.scriptRef.onlineExpGained) + " hacking exp").replace( / /g, " ");
@@ -313,7 +319,7 @@ function updateActiveScriptsText(workerscript, item, itemName) {
var onlineEps = workerscript.scriptRef.onlineExpGained / workerscript.scriptRef.onlineRunningTime;
var onlineEpsText = (Array(25).join(" ") + numeralWrapper.formatBigNumber(onlineEps) + " hacking exp / second").replace( / /g, " ");
- //Offline
+ // Offline
var offlineTotalMoneyMade = "Total offline production: " + numeralWrapper.formatMoney(workerscript.scriptRef.offlineMoneyMade);
var offlineTotalExpEarned = (Array(27).join(" ") + numeralWrapper.formatBigNumber(workerscript.scriptRef.offlineExpGained) + " hacking exp").replace( / /g, " ");
diff --git a/src/Alias.ts b/src/Alias.ts
index f512fe9c7..2a1ddb3fc 100644
--- a/src/Alias.ts
+++ b/src/Alias.ts
@@ -20,7 +20,7 @@ export function loadGlobalAliases(saveString: string): void {
}
}
-//Print all aliases to terminal
+// Prints all aliases to terminal
export function printAliases(): void {
for (var name in Aliases) {
if (Aliases.hasOwnProperty(name)) {
@@ -34,7 +34,7 @@ export function printAliases(): void {
}
}
-//True if successful, false otherwise
+// Returns true if successful, false otherwise
export function parseAliasDeclaration(dec: string, global: boolean=false) {
var re = /^([_|\w|!|%|,|@]+)="(.+)"$/;
var matches = dec.match(re);
@@ -90,8 +90,10 @@ export function removeAlias(name: string): boolean {
return false;
}
-//Returns the original string with any aliases substituted in
-//Aliases only applied to "whole words", one level deep
+/**
+ * Returns the original string with any aliases substituted in.
+ * Aliases are only applied to "whole words", one level deep
+ */
export function substituteAliases(origCommand: string): string {
const commandArray = origCommand.split(" ");
if (commandArray.length > 0){
diff --git a/src/Bladeburner.js b/src/Bladeburner.js
index b5b36df72..16d5aa976 100644
--- a/src/Bladeburner.js
+++ b/src/Bladeburner.js
@@ -41,57 +41,62 @@ const killIcon = ` " +
"automate [var] [val] [hi/low] Configure simple automation for Bladeburner tasks " +
"clear/cls Clear the console " +
@@ -160,14 +165,10 @@ var consoleHelpText = {
"Stop your current action and go idle",
}
-//Keypresses for Console
+// Keypresses for Console
$(document).keydown(function(event) {
if (routing.isOn(Page.Bladeburner)) {
- //if (DomElems.consoleInput && !event.ctrlKey && !event.shiftKey && !event.altKey) {
- // DomElems.consoleInput.focus();
- //}
-
- if (!(Player.bladeburner instanceof Bladeburner)) {return;}
+ if (!(Player.bladeburner instanceof Bladeburner)) { return; }
let consoleHistory = Player.bladeburner.consoleHistory;
if (event.keyCode === KEY.ENTER) {
@@ -209,7 +210,7 @@ $(document).keydown(function(event) {
consoleHistoryIndex = len;
}
- //Latest command, put nothing
+ // Latest command, put nothing
if (i == len || i == len-1) {
consoleHistoryIndex = len;
DomElems.consoleInput.value = "";
@@ -225,11 +226,11 @@ $(document).keydown(function(event) {
function City(params={}) {
this.name = params.name ? params.name : CityNames[2]; // Sector-12
- //Synthoid population and estimate
+ // Synthoid population and estimate
this.pop = params.pop ? params.pop : getRandomInt(PopulationThreshold, 1.5 * PopulationThreshold);
this.popEst = this.pop * (Math.random() + 0.5);
- //Number of Synthoid communities population and estimate
+ // Number of Synthoid communities population and estimate
this.comms = params.comms ? params.comms : getRandomInt(5, 150);
this.commsEst = this.comms + getRandomInt(-5, 5);
if (this.commsEst < 0) {this.commsEst = 0;}
@@ -247,12 +248,12 @@ City.prototype.improvePopulationEstimateByCount = function(n) {
}
}
-//@p is the percentage, not the multiplier. e.g. pass in p = 5 for 5%
+// @p is the percentage, not the multiplier. e.g. pass in p = 5 for 5%
City.prototype.improvePopulationEstimateByPercentage = function(p, skillMult=1) {
p = p*skillMult;
if (isNaN(p)) {throw new Error("NaN passed into City.improvePopulationEstimateByPercentage()");}
if (this.popEst < this.pop) {
- ++this.popEst; //In case estimate is 0
+ ++this.popEst; // In case estimate is 0
this.popEst *= (1 + (p/100));
if (this.popEst > this.pop) {this.popEst = this.pop;}
} else if (this.popEst > this.pop) {
@@ -272,9 +273,11 @@ City.prototype.improveCommunityEstimate = function(n=1) {
}
}
-//@params options:
-// estChange(int): How much the estimate should change by
-// estOffset(int): Add offset to estimate (offset by percentage)
+/**
+ * @params options:
+ * estChange(int): How much the estimate should change by
+ * estOffset(int): Add offset to estimate (offset by percentage)
+ */
City.prototype.changePopulationByCount = function(n, params={}) {
if (isNaN(n)) {throw new Error("NaN passed into City.changePopulationByCount()");}
this.pop += n;
@@ -285,16 +288,18 @@ City.prototype.changePopulationByCount = function(n, params={}) {
this.popEst = Math.max(this.popEst, 0);
}
-//@p is the percentage, not the multiplier. e.g. pass in p = 5 for 5%
-//@params options:
-// changeEstEqually(bool) - Change the population estimate by an equal amount
-// nonZero (bool) - Set to true to ensure that population always changes by at least 1
+/**
+ * @p is the percentage, not the multiplier. e.g. pass in p = 5 for 5%
+ * @params options:
+ * changeEstEqually(bool) - Change the population estimate by an equal amount
+ * nonZero (bool) - Set to true to ensure that population always changes by at least 1
+ */
City.prototype.changePopulationByPercentage = function(p, params={}) {
if (isNaN(p)) {throw new Error("NaN passed into City.changePopulationByPercentage()");}
if (p === 0) {return;}
var change = Math.round(this.pop * (p/100));
- //Population always changes by at least 1
+ // Population always changes by at least 1
if (params.nonZero && change === 0) {
p > 0 ? change = 1 : change = -1;
}
@@ -314,7 +319,7 @@ City.prototype.changeChaosByCount = function(n) {
if (this.chaos < 0) {this.chaos = 0;}
}
-//@p is the percentage, not the multiplier (e.g. pass in p = 5 for 5%)
+// @p is the percentage, not the multiplier (e.g. pass in p = 5 for 5%)
City.prototype.changeChaosByPercentage = function(p) {
if (isNaN(p)) {throw new Error("NaN passed into City.chaosChaosByPercentage()");}
if (p === 0) {return;}
@@ -342,21 +347,25 @@ function Skill(params={name:"foo", desc:"foo"}) {
} else {
throw new Error("Failed to initialize Bladeburner Skills. No desc was specified in ctor");
}
- this.baseCost = params.baseCost ? params.baseCost : 1; //Cost is in Skill Points
- this.costInc = params.costInc ? params.costInc : 1; //Additive cost increase per level
+ this.baseCost = params.baseCost ? params.baseCost : 1; // Cost is in Skill Points
+ this.costInc = params.costInc ? params.costInc : 1; // Additive cost increase per level
if (params.maxLvl) {this.maxLvl = params.maxLvl;}
- //These benefits are additive. So total multiplier will be level (handled externally) times the
- //effects below
+ /**
+ * These benefits are additive. So total multiplier will be level (handled externally) times the
+ * effects below
+ */
if (params.successChanceAll) {this.successChanceAll = params.successChanceAll;}
if (params.successChanceStealth) {this.successChanceStealth = params.successChanceStealth;}
if (params.successChanceKill) {this.successChanceKill = params.successChanceKill;}
if (params.successChanceContract) {this.successChanceContract = params.successChanceContract;}
if (params.successChanceOperation) {this.successChanceOperation = params.successChanceOperation;}
- //This multiplier affects everything that increases synthoid population/community estimate
- //e.g. Field analysis, Investigation Op, Undercover Op
+ /**
+ * This multiplier affects everything that increases synthoid population/community estimate
+ * e.g. Field analysis, Investigation Op, Undercover Op
+ */
if (params.successChanceEstimate) {this.successChanceEstimate = params.successChanceEstimate;}
if (params.actionTime) {this.actionTime = params.actionTime;}
@@ -379,8 +388,8 @@ function Skill(params={name:"foo", desc:"foo"}) {
Skill.prototype.calculateCost = function(currentLevel) {
return Math.floor((this.baseCost + (currentLevel * this.costInc)) * BitNodeMultipliers.BladeburnerSkillCost);
}
-var Skills = {};
-var SkillNames = {
+const Skills = {};
+const SkillNames = {
BladesIntuition: "Blade's Intuition",
Cloak: "Cloak",
Marksman: "Marksman",
@@ -397,28 +406,25 @@ var SkillNames = {
Hyperdrive: "Hyperdrive",
}
-//Base Class for Contracts, Operations, and BlackOps
+// Base Class for Contracts, Operations, and BlackOps
function Action(params={}) {
this.name = params.name ? params.name : "";
this.desc = params.desc ? params.desc : "";
- //Difficulty scales with level
- //Exact formula is not set in stone
- //Initial design: baseDifficulty * (difficultyFac ^ level)?
- //difficulty Fac is slightly greater than 1
+ // Difficulty scales with level. See getDifficulty() method
this.level = 1;
this.maxLevel = 1;
this.autoLevel = true;
this.baseDifficulty = params.baseDifficulty ? addOffset(params.baseDifficulty, 10) : 100;
this.difficultyFac = params.difficultyFac ? params.difficultyFac : 1.01;
- //Rank increase/decrease is affected by this exponent
+ // Rank increase/decrease is affected by this exponent
this.rewardFac = params.rewardFac ? params.rewardFac : 1.02;
this.successes = 0;
this.failures = 0;
- //All of these scale with level/difficulty
+ // All of these scale with level/difficulty
this.rankGain = params.rankGain ? params.rankGain : 0;
if (params.rankLoss) {this.rankLoss = params.rankLoss;}
if (params.hpLoss) {
@@ -426,22 +432,24 @@ function Action(params={}) {
this.hpLost = 0;
}
- //Action Category. Current categories are stealth and kill
+ // Action Category. Current categories are stealth and kill
this.isStealth = params.isStealth ? true : false;
this.isKill = params.isKill ? true : false;
- //Number of this contract remaining, and its growth rate
- //Growth rate is an integer and the count will increase by that integer every "cycle"
+ /**
+ * Number of this contract remaining, and its growth rate
+ * Growth rate is an integer and the count will increase by that integer every "cycle"
+ */
this.count = params.count ? params.count : getRandomInt(1e3, 25e3);
this.countGrowth = params.countGrowth ? params.countGrowth : getRandomInt(1, 5);
- //Weighting of each stat in determining action success rate
+ // Weighting of each stat in determining action success rate
var defaultWeights = {hack:1/7,str:1/7,def:1/7,dex:1/7,agi:1/7,cha:1/7,int:1/7};
this.weights = params.weights ? params.weights : defaultWeights;
- //Check to make sure weights are summed properly
- var sum = 0;
- for (var weight in this.weights) {
+ // Check to make sure weights are summed properly
+ let sum = 0;
+ for (const weight in this.weights) {
if (this.weights.hasOwnProperty(weight)) {
sum += this.weights[weight];
}
@@ -451,10 +459,10 @@ function Action(params={}) {
". The weights should sum up to 1. They sum up to :" + 1);
}
- //Diminishing returns of stats (stat ^ decay where 0 <= decay <= 1)
- var defaultDecays = {hack:0.9,str:0.9,def:0.9,dex:0.9,agi:0.9,cha:0.9,int:0.9};
- this.decays = params.decays ? params.decays : defaultDecays;
- for (var decay in this.decays) {
+ // Diminishing returns of stats (stat ^ decay where 0 <= decay <= 1)
+ const defaultDecays = { hack: 0.9, str: 0.9, def: 0.9, dex: 0.9, agi: 0.9, cha: 0.9, int: 0.9 };
+ this.decays = params.decays ? params.decays : defaultDecays;
+ for (const decay in this.decays) {
if (this.decays.hasOwnProperty(decay)) {
if (this.decays[decay] > 1) {
throw new Error("Invalid decays when constructing " +
@@ -471,9 +479,11 @@ Action.prototype.getDifficulty = function() {
return difficulty;
}
-//@inst - Bladeburner Object
-//@params - options:
-// est (bool): Get success chance estimate instead of real success chance
+/**
+ * @inst - Bladeburner Object
+ * @params - options:
+ * est (bool): Get success chance estimate instead of real success chance
+ */
Action.prototype.getSuccessChance = function(inst, params={}) {
if (inst == null) {throw new Error("Invalid Bladeburner instance passed into Action.getSuccessChance");}
var difficulty = this.getDifficulty();
@@ -492,7 +502,7 @@ Action.prototype.getSuccessChance = function(inst, params={}) {
}
competence *= inst.calculateStaminaPenalty();
- //For Operations, factor in team members
+ // For Operations, factor in team members
if (this instanceof Operation || this instanceof BlackOperation) {
if (this.teamCount && this.teamCount > 0) {
this.teamCount = Math.min(this.teamCount, inst.teamSize);
@@ -501,7 +511,7 @@ Action.prototype.getSuccessChance = function(inst, params={}) {
}
}
- //Lower city population results in lower chances
+ // Lower city population results in lower chances
if (!(this instanceof BlackOperation)) {
var city = inst.getCurrentCity();
if (params.est) {
@@ -510,20 +520,20 @@ Action.prototype.getSuccessChance = function(inst, params={}) {
competence *= Math.pow((city.pop / PopulationThreshold), PopulationExponent);
}
- //Too high of a chaos results in lower chances
+ // Too high of a chaos results in lower chances
if (city.chaos > ChaosThreshold) {
var diff = 1 + (city.chaos - ChaosThreshold);
var mult = Math.pow(diff, 0.1);
difficulty *= mult;
}
- //For Raid Operations, no communities = fail
+ // For Raid Operations, no communities = fail
if (this instanceof Operation && this.name === "Raid") {
if (city.comms <= 0) {return 0;}
}
}
- //Factor skill multipliers into success chance
+ // Factor skill multipliers into success chance
competence *= inst.skillMultipliers.successChanceAll;
if (this instanceof Operation || this instanceof BlackOperation) {
competence *= inst.skillMultipliers.successChanceOperation;
@@ -538,15 +548,17 @@ Action.prototype.getSuccessChance = function(inst, params={}) {
competence *= inst.skillMultipliers.successChanceKill;
}
- //Augmentation multiplier
+ // Augmentation multiplier
competence *= Player.bladeburner_success_chance_mult;
if (isNaN(competence)) {throw new Error("Competence calculated as NaN in Action.getSuccessChance()");}
return Math.min(1, competence / difficulty);
}
-//Tests for success. Should be called when an action has completed
-// @inst - Bladeburner Object
+/**
+ * Tests for success. Should be called when an action has completed
+ * @param inst {Bladeburner} - Bladeburner instance
+ */
Action.prototype.attempt = function(inst) {
return (Math.random() < this.getSuccessChance(inst));
}
@@ -554,14 +566,14 @@ Action.prototype.attempt = function(inst) {
Action.prototype.getActionTime = function(inst) {
var difficulty = this.getDifficulty();
var baseTime = difficulty / DifficultyToTimeFactor;
- var skillFac = inst.skillMultipliers.actionTime; //Always < 1
+ var skillFac = inst.skillMultipliers.actionTime; // Always < 1
var effAgility = Player.agility * inst.skillMultipliers.effAgi;
var effDexterity = Player.dexterity * inst.skillMultipliers.effDex;
var statFac = 0.5 * (Math.pow(effAgility, EffAgiExponentialFactor) +
Math.pow(effDexterity, EffDexExponentialFactor) +
(effAgility / EffAgiLinearFactor) +
- (effDexterity / EffDexLinearFactor)); //Always > 1
+ (effDexterity / EffDexLinearFactor)); // Always > 1
baseTime = Math.max(1, baseTime * skillFac / statFac);
@@ -593,9 +605,9 @@ Action.fromJSON = function(value) {
return Generic_fromJSON(Action, value.data);
}
Reviver.constructors.Action = Action;
-var GeneralActions = {}; //Training, Field Analysis, Recruitment, etc.
+const GeneralActions = {}; // Training, Field Analysis, Recruitment, etc.
-//Action Identifier
+// Action Identifier enum
const ActionTypes = Object.freeze({
"Idle": 1,
"Contract": 2,
@@ -609,85 +621,102 @@ const ActionTypes = Object.freeze({
"Diplomacy": 8,
"Hyperbolic Regeneration Chamber": 9,
});
+
function ActionIdentifier(params={}) {
if (params.name) {this.name = params.name;}
if (params.type) {this.type = params.type;}
}
+
ActionIdentifier.prototype.toJSON = function() {
return Generic_toJSON("ActionIdentifier", this);
}
+
ActionIdentifier.fromJSON = function(value) {
return Generic_fromJSON(ActionIdentifier, value.data);
}
+
Reviver.constructors.ActionIdentifier = ActionIdentifier;
-//Contracts
+// Contracts
function Contract(params={}) {
Action.call(this, params);
}
+
Contract.prototype = Object.create(Action.prototype);
+
Contract.prototype.toJSON = function() {
return Generic_toJSON("Contract", this);
}
+
Contract.fromJSON = function(value) {
return Generic_fromJSON(Contract, value.data);
}
+
Reviver.constructors.Contract = Contract;
-//Operations
+// Operations
function Operation(params={}) {
Action.call(this, params);
this.reqdRank = params.reqdRank ? params.reqdRank : 100;
this.teamCount = params.teamCount ? params.teamCount : 0; //# of team members to use
}
+
Operation.prototype = Object.create(Action.prototype);
+
Operation.prototype.toJSON = function() {
return Generic_toJSON("Operation", this);
}
+
Operation.fromJSON = function(value) {
return Generic_fromJSON(Operation, value.data);
}
+
Reviver.constructors.Operation = Operation;
-//Black Operations
+// Black Operations
function BlackOperation(params={}) {
Operation.call(this, params);
- //Black ops are one time missions
+ // Black ops are one time missions
this.count = 1;
this.countGrowth = 0;
}
+
BlackOperation.prototype = Object.create(Action.prototype);
+
BlackOperation.prototype.toJSON = function() {
return Generic_toJSON("BlackOperation", this);
}
+
BlackOperation.fromJSON = function(value) {
return Generic_fromJSON(BlackOperation, value.data);
}
+
Reviver.constructors.BlackOperation = BlackOperation;
-var BlackOperations = {};
+
+const BlackOperations = {};
function Bladeburner(params={}) {
- this.numHosp = 0; //Number of hospitalizations
- this.moneyLost = 0; //Money lost due to hospitalizations
+ this.numHosp = 0; // Number of hospitalizations
+ this.moneyLost = 0; // Money lost due to hospitalizations
this.rank = 0;
- this.maxRank = 0; //Used to determine skill points
+ this.maxRank = 0; // Used to determine skill points
this.skillPoints = 0;
this.totalSkillPoints = 0;
- this.teamSize = 0; //Number of team members
- this.teamLost = 0; //Number of team members lost
+ this.teamSize = 0; // Number of team members
+ this.teamLost = 0; // Number of team members lost
this.storedCycles = 0;
- this.randomEventCounter = getRandomInt(240, 600); //4-10 minutes
+ this.randomEventCounter = getRandomInt(240, 600); // 4-10 minutes
- //These times are in seconds
- this.actionTimeToComplete = 0; //0 or -1 is an infinite running action (like training)
+ // These times are in seconds
+ this.actionTimeToComplete = 0; // 0 or -1 is an infinite running action (like training)
this.actionTimeCurrent = 0;
- //ActionIdentifier Object
+ // ActionIdentifier Object
var idleActionType = ActionTypes["Idle"];
this.action = new ActionIdentifier({type:idleActionType});
@@ -697,27 +726,29 @@ function Bladeburner(params={}) {
}
this.city = CityNames[2]; // Sector-12
- //Map of SkillNames -> level
+ // Map of SkillNames -> level
this.skills = {};
this.skillMultipliers = {};
- this.updateSkillMultipliers(); //Calls resetSkillMultipliers()
+ this.updateSkillMultipliers(); // Calls resetSkillMultipliers()
- //Max Stamina is based on stats and Bladeburner-specific bonuses
- this.staminaBonus = 0; //Gained from training
+ // Max Stamina is based on stats and Bladeburner-specific bonuses
+ this.staminaBonus = 0; // Gained from training
this.maxStamina = 0;
this.calculateMaxStamina();
this.stamina = this.maxStamina;
- //Contracts and Operations objects. These objects have unique
- //properties because they are randomized in each instance and have stats like
- //successes/failures, so they need to be saved/loaded by the game.
+ /**
+ * Contracts and Operations objects. These objects have unique
+ * properties because they are randomized in each instance and have stats like
+ * successes/failures, so they need to be saved/loaded by the game.
+ */
this.contracts = {};
this.operations = {};
- //Object that contains name of all Black Operations that have been completed
+ // Object that contains name of all Black Operations that have been completed
this.blackops = {};
- //Flags for whether these actions should be logged to console
+ // Flags for whether these actions should be logged to console
this.logging = {
general:true,
contracts:true,
@@ -726,18 +757,18 @@ function Bladeburner(params={}) {
events:true,
}
- //Simple automation values
+ // Simple automation values
this.automateEnabled = false;
this.automateActionHigh = 0;
this.automateThreshHigh = 0; //Stamina Threshold
this.automateActionLow = 0;
this.automateThreshLow = 0; //Stamina Threshold
- //Console command history
+ // Console command history
this.consoleHistory = [];
this.consoleLogs = [];
- //Initialization
+ // Initialization
initBladeburner();
this.initializeDomElementRefs();
if (params.new) {this.create();}
@@ -871,12 +902,12 @@ Bladeburner.prototype.storeCycles = function(numCycles=1) {
}
Bladeburner.prototype.process = function() {
- //Extreme condition...if Operation Daedalus is complete trigger the BitNode
+ // Edge case condition...if Operation Daedalus is complete trigger the BitNode
if (redPillFlag === false && this.blackops.hasOwnProperty("Operation Daedalus")) {
return hackWorldDaemon(Player.bitNodeN);
}
- //If the Player starts doing some other actions, set action to idle and alert
+ // If the Player starts doing some other actions, set action to idle and alert
if (Augmentations[AugmentationNames.BladesSimulacrum].owned === false && Player.isWorking) {
if (this.action.type !== ActionTypes["Idle"]) {
let msg = "Your Bladeburner action was cancelled because you started doing something else.";
@@ -895,18 +926,18 @@ Bladeburner.prototype.process = function() {
this.resetAction();
}
- //A 'tick' for this mechanic is one second (= 5 game cycles)
+ // A 'tick' for this mechanic is one second (= 5 game cycles)
if (this.storedCycles >= CyclesPerSecond) {
var seconds = Math.floor(this.storedCycles / CyclesPerSecond);
- seconds = Math.min(seconds, 5); //Max of 5 'ticks'
+ seconds = Math.min(seconds, 5); // Max of 5 'ticks'
this.storedCycles -= seconds * CyclesPerSecond;
- //Stamina
+ // Stamina
this.calculateMaxStamina();
this.stamina += (this.calculateStaminaGainPerSecond() * seconds);
this.stamina = Math.min(this.maxStamina, this.stamina);
- //Count increase for contracts/operations
+ // Count increase for contracts/operations
for (var contractName in this.contracts) {
if (this.contracts.hasOwnProperty(contractName)) {
var contract = this.contracts[contractName];
@@ -920,7 +951,7 @@ Bladeburner.prototype.process = function() {
}
}
- //Chaos goes down very slowly
+ // Chaos goes down very slowly
for (var i = 0; i < CityNames.length; ++i) {
var city = this.cities[CityNames[i]];
if (!(city instanceof City)) {throw new Error("Invalid City object when processing passive chaos reduction in Bladeburner.process");}
@@ -928,7 +959,7 @@ Bladeburner.prototype.process = function() {
city.chaos = Math.max(0, city.chaos);
}
- //Random Events
+ // Random Events
this.randomEventCounter -= seconds;
if (this.randomEventCounter <= 0) {
this.randomEvent();
@@ -937,7 +968,7 @@ Bladeburner.prototype.process = function() {
this.processAction(seconds);
- //Automation
+ // Automation
if (this.automateEnabled) {
// Note: Do NOT set this.action = this.automateActionHigh/Low since it creates a reference
if (this.stamina <= this.automateThreshLow) {
@@ -1000,7 +1031,7 @@ Bladeburner.prototype.changeRank = function(change) {
// Gain skill points
var rankNeededForSp = (this.totalSkillPoints+1) * RanksPerSkillPoint;
if (this.maxRank >= rankNeededForSp) {
- //Calculate how many skill points to gain
+ // Calculate how many skill points to gain
var gainedSkillPoints = Math.floor((this.maxRank - rankNeededForSp) / RanksPerSkillPoint + 1);
this.skillPoints += gainedSkillPoints;
this.totalSkillPoints += gainedSkillPoints;
@@ -1067,7 +1098,7 @@ Bladeburner.prototype.updateSkillMultipliers = function() {
}
Bladeburner.prototype.upgradeSkill = function(skill) {
- //This does NOT handle deduction of skill points
+ // This does NOT handle deduction of skill points
var skillName = skill.name;
if (this.skills[skillName]) {
++this.skills[skillName];
@@ -1081,8 +1112,10 @@ Bladeburner.prototype.upgradeSkill = function(skill) {
}
Bladeburner.prototype.getActionObject = function(actionId) {
- //Given an ActionIdentifier object, returns the corresponding
- //GeneralAction, Contract, Operation, or BlackOperation object
+ /**
+ * Given an ActionIdentifier object, returns the corresponding
+ * GeneralAction, Contract, Operation, or BlackOperation object
+ */
switch (actionId.type) {
case ActionTypes["Contract"]:
return this.contracts[actionId.name];
@@ -1102,7 +1135,7 @@ Bladeburner.prototype.getActionObject = function(actionId) {
}
}
-//Sets the player to the "IDLE" action
+// Sets the player to the "IDLE" action
Bladeburner.prototype.resetAction = function() {
this.action = new ActionIdentifier({type:ActionTypes.Idle});
}
@@ -1207,17 +1240,17 @@ Bladeburner.prototype.completeAction = function() {
var difficultyMultiplier = Math.pow(difficulty, DiffMultExponentialFactor) + difficulty / DiffMultLinearFactor;
var rewardMultiplier = Math.pow(action.rewardFac, action.level-1);
- //Stamina loss is based on difficulty
+ // Stamina loss is based on difficulty
this.stamina -= (BaseStaminaLoss * difficultyMultiplier);
if (this.stamina < 0) {this.stamina = 0;}
- //Process Contract/Operation success/failure
+ // Process Contract/Operation success/failure
if (action.attempt(this)) {
this.gainActionStats(action, true);
++action.successes;
--action.count;
- //Earn money for contracts
+ // Earn money for contracts
var moneyGain = 0;
if (!isOperation) {
moneyGain = ContractBaseMoneyGain * rewardMultiplier * this.skillMultipliers.money;
@@ -1267,8 +1300,8 @@ Bladeburner.prototype.completeAction = function() {
}
isOperation ? this.completeOperation(false) : this.completeContract(false);
}
- if (action.autoLevel) {action.level = action.maxLevel;} //Autolevel
- this.startAction(this.action); //Repeat action
+ if (action.autoLevel) {action.level = action.maxLevel;} // Autolevel
+ this.startAction(this.action); // Repeat action
} catch(e) {
exceptionAlert(e);
}
@@ -1283,11 +1316,11 @@ Bladeburner.prototype.completeAction = function() {
var difficulty = action.getDifficulty();
var difficultyMultiplier = Math.pow(difficulty, DiffMultExponentialFactor) + difficulty / DiffMultLinearFactor;
- //Stamina loss is based on difficulty
+ // Stamina loss is based on difficulty
this.stamina -= (BaseStaminaLoss * difficultyMultiplier);
if (this.stamina < 0) {this.stamina = 0;}
- //Team loss variables
+ // Team loss variables
var teamCount = action.teamCount, teamLossMax;
if (action.attempt(this)) {
@@ -1301,7 +1334,7 @@ Bladeburner.prototype.completeAction = function() {
}
teamLossMax = Math.ceil(teamCount/2);
- //Operation Daedalus
+ // Operation Daedalus
if (action.name === "Operation Daedalus") {
this.resetAction();
return hackWorldDaemon(Player.bitNodeN);
@@ -1336,9 +1369,9 @@ Bladeburner.prototype.completeAction = function() {
}
}
- this.resetAction(); //Stop regardless of success or fail
+ this.resetAction(); // Stop regardless of success or fail
- //Calculate team lossses
+ // Calculate team lossses
if (teamCount >= 1) {
var losses = getRandomInt(1, teamLossMax);
this.teamSize -= losses;
@@ -1371,11 +1404,11 @@ Bladeburner.prototype.completeAction = function() {
formatNumber(agiExpGain, 1) + " agi exp, " +
formatNumber(staminaGain, 3) + " max stamina");
}
- this.startAction(this.action); //Repeat action
+ this.startAction(this.action); // Repeat action
break;
case ActionTypes["FieldAnalysis"]:
case ActionTypes["Field Analysis"]:
- //Does not use stamina. Effectiveness depends on hacking, int, and cha
+ // Does not use stamina. Effectiveness depends on hacking, int, and cha
var eff = 0.04 * Math.pow(Player.hacking_skill, 0.3) +
0.04 * Math.pow(Player.intelligence, 0.9) +
0.02 * Math.pow(Player.charisma, 0.3);
@@ -1393,7 +1426,7 @@ Bladeburner.prototype.completeAction = function() {
if (this.logging.general) {
this.log("Field analysis completed. Gained 0.1 rank, " + formatNumber(hackingExpGain, 1) + " hacking exp, and " + formatNumber(charismaExpGain, 1) + " charisma exp");
}
- this.startAction(this.action); //Repeat action
+ this.startAction(this.action); // Repeat action
break;
case ActionTypes["Recruitment"]:
var successChance = this.getRecruitmentSuccessChance();
@@ -1411,7 +1444,7 @@ Bladeburner.prototype.completeAction = function() {
this.log("Failed to recruit a team member. Gained " + formatNumber(expGain, 1) + " charisma exp");
}
}
- this.startAction(this.action); //Repeat action
+ this.startAction(this.action); // Repeat action
break;
case ActionTypes["Diplomacy"]:
var eff = this.getDiplomacyEffectiveness();
@@ -1447,7 +1480,7 @@ Bladeburner.prototype.completeContract = function(success) {
if (success) {
switch (this.action.name) {
case "Tracking":
- //Increase estimate accuracy by a relatively small amount
+ // Increase estimate accuracy by a relatively small amount
city.improvePopulationEstimateByCount(getRandomInt(100, 1e3));
break;
case "Bounty Hunter":
@@ -1473,7 +1506,7 @@ Bladeburner.prototype.completeOperation = function(success) {
throw new Error("Failed to get Contract/Operation Object for: " + this.action.name);
}
- //Calculate team losses
+ // Calculate team losses
var teamCount = action.teamCount, max;
if (teamCount >= 1) {
if (success) {
@@ -1564,14 +1597,18 @@ Bladeburner.prototype.getDiplomacyEffectiveness = function() {
return (100 - charismaEff) / 100;
}
-//Process stat gains from Contracts, Operations, and Black Operations
-//@action(Action obj) - Derived action class
-//@success(bool) - Whether action was successful
+/**
+ * Process stat gains from Contracts, Operations, and Black Operations
+ * @param action(Action obj) - Derived action class
+ * @param success(bool) - Whether action was successful
+ */
Bladeburner.prototype.gainActionStats = function(action, success) {
var difficulty = action.getDifficulty();
- //Gain multiplier based on difficulty. If this changes then the
- //same variable calculated in completeAction() needs to change too
+ /**
+ * Gain multiplier based on difficulty. If this changes then the
+ * same variable calculated in completeAction() needs to change too
+ */
var difficultyMult = Math.pow(difficulty, DiffMultExponentialFactor) + difficulty / DiffMultLinearFactor;
var time = this.actionTimeToComplete;
@@ -1592,7 +1629,7 @@ Bladeburner.prototype.gainActionStats = function(action, success) {
Bladeburner.prototype.randomEvent = function() {
var chance = Math.random();
- //Choose random source/destination city for events
+ // Choose random source/destination city for events
var sourceCityName = CityNames[getRandomInt(0, 5)];
var sourceCity = this.cities[sourceCityName];
if (!(sourceCity instanceof City)) {
@@ -1610,7 +1647,7 @@ Bladeburner.prototype.randomEvent = function() {
}
if (chance <= 0.05) {
- //New Synthoid Community, 5%
+ // New Synthoid Community, 5%
++sourceCity.comms;
var percentage = getRandomInt(10, 20) / 100;
var count = Math.round(sourceCity.pop * percentage);
@@ -1619,9 +1656,9 @@ Bladeburner.prototype.randomEvent = function() {
this.log("Intelligence indicates that a new Synthoid community was formed in a city");
}
} else if (chance <= 0.1) {
- //Synthoid Community Migration, 5%
+ // Synthoid Community Migration, 5%
if (sourceCity.comms <= 0) {
- //If no comms in source city, then instead trigger a new Synthoid community event
+ // If no comms in source city, then instead trigger a new Synthoid community event
++sourceCity.comms;
var percentage = getRandomInt(10, 20) / 100;
var count = Math.round(sourceCity.pop * percentage);
@@ -1633,7 +1670,7 @@ Bladeburner.prototype.randomEvent = function() {
--sourceCity.comms;
++destCity.comms;
- //Change pop
+ // Change pop
var percentage = getRandomInt(10, 20) / 100;
var count = Math.round(sourceCity.pop * percentage);
sourceCity.pop -= count;
@@ -1644,7 +1681,7 @@ Bladeburner.prototype.randomEvent = function() {
}
}
} else if (chance <= 0.3) {
- //New Synthoids (non community), 20%
+ // New Synthoids (non community), 20%
var percentage = getRandomInt(8, 24) / 100;
var count = Math.round(sourceCity.pop * percentage);
sourceCity.pop += count;
@@ -1652,20 +1689,20 @@ Bladeburner.prototype.randomEvent = function() {
this.log("Intelligence indicates that the Synthoid population of " + sourceCityName + " just changed significantly");
}
} else if (chance <= 0.5) {
- //Synthoid migration (non community) 20%
+ // Synthoid migration (non community) 20%
this.triggerMigration(sourceCityName);
if (this.logging.events) {
this.log("Intelligence indicates that a large number of Synthoids migrated from " + sourceCityName + " to some other city");
}
} else if (chance <= 0.7) {
- //Synthoid Riots (+chaos), 20%
+ // Synthoid Riots (+chaos), 20%
sourceCity.chaos += 1;
sourceCity.chaos *= (1 + getRandomInt(5, 20) / 100);
if (this.logging.events) {
this.log("Tensions between Synthoids and humans lead to riots in " + sourceCityName + "! Chaos increased");
}
} else if (chance <= 0.9) {
- //Less Synthoids, 20%
+ // Less Synthoids, 20%
var percentage = getRandomInt(8, 20) / 100;
var count = Math.round(sourceCity.pop * percentage);
sourceCity.pop -= count;
@@ -1696,8 +1733,8 @@ Bladeburner.prototype.triggerMigration = function(sourceCityName) {
}
var rand = Math.random(), percentage = getRandomInt(3, 15) / 100;
- if (rand < 0.05 && sourceCity.comms > 0) { //5% chance for community migration
- percentage *= getRandomInt(2, 4); //Migration increases population change
+ if (rand < 0.05 && sourceCity.comms > 0) { // 5% chance for community migration
+ percentage *= getRandomInt(2, 4); // Migration increases population change
--sourceCity.comms;
++destCity.comms;
}
@@ -1706,31 +1743,31 @@ Bladeburner.prototype.triggerMigration = function(sourceCityName) {
destCity.pop += count;
}
-var DomElems = {};
+let DomElems = {};
Bladeburner.prototype.initializeDomElementRefs = function() {
DomElems = {
bladeburnerDiv: null,
- //Main Divs
+ // Main Divs
overviewConsoleParentDiv: null,
- overviewDiv: null, //Overview of stats that stays fixed on left
- actionAndSkillsDiv: null, //Panel for different sections (contracts, ops, skills)
- currentTab: null, //Contracts, Operations, Black Ops, Skills
+ overviewDiv: null, // Overview of stats that stays fixed on left
+ actionAndSkillsDiv: null, // Panel for different sections (contracts, ops, skills)
+ currentTab: null, // Contracts, Operations, Black Ops, Skills
consoleDiv: null,
consoleTable: null,
- consoleInputRow: null, //tr
- consoleInputCell: null, //td
- consoleInputHeader: null, //"> "
- consoleInput: null, //Actual input element
+ consoleInputRow: null, // tr
+ consoleInputCell: null, // td
+ consoleInputHeader: null, // "> "
+ consoleInput: null, // Actual input element
- //Overview Content
+ // Overview Content
overviewRank: null,
overviewStamina: null,
overviewStaminaHelpTip: null,
- overviewGen1: null, //Stamina Penalty, Team, Hospitalized stats, current city
+ overviewGen1: null, // Stamina Penalty, Team, Hospitalized stats, current city
overviewEstPop: null,
overviewEstPopHelpTip: null,
overviewEstComms: null,
@@ -1742,9 +1779,9 @@ Bladeburner.prototype.initializeDomElementRefs = function() {
overviewAugStaminaGainMult: null,
overviewAugAnalysisMult: null,
- //Actions and Skills Content
+ // Actions and Skills Content
actionsAndSkillsDesc: null,
- actionsAndSkillsList: null, //ul element of all UI elements in this panel
+ actionsAndSkillsList: null, // ul element of all UI elements in this panel
generalActions: {},
contracts: {},
operations: {},
@@ -1759,12 +1796,12 @@ Bladeburner.prototype.createContent = function() {
id:"bladeburner-container", position:"fixed", class:"generic-menupage-container",
});
- //Parent Div for Overview and Console
+ // Parent Div for Overview and Console
DomElems.overviewConsoleParentDiv = createElement("div", {
height:"60%", display:"block", position:"relative",
});
- //Overview and Action/Skill pane
+ // Overview and Action/Skill pane
DomElems.overviewDiv = createElement("div", {
width:"30%", display:"inline-block", border:"1px solid white",
});
@@ -1779,7 +1816,7 @@ Bladeburner.prototype.createContent = function() {
this.createOverviewContent();
this.createActionAndSkillsContent();
- //Console
+ // Console
DomElems.consoleDiv = createElement("div", {
class:"bladeburner-console-div",
clickListener:()=>{
@@ -1949,20 +1986,20 @@ Bladeburner.prototype.createOverviewContent = function() {
DomElems.overviewDiv.appendChild(DomElems.overviewAugStaminaGainMult);
DomElems.overviewDiv.appendChild(DomElems.overviewAugAnalysisMult);
- //Travel to new city button
+ // Travel to new city button
appendLineBreaks(DomElems.overviewDiv, 1);
DomElems.overviewDiv.appendChild(createElement("a", {
innerHTML:"Travel", class:"a-link-button", display:"inline-block",
clickListener:()=>{
var popupId = "bladeburner-travel-popup-cancel-btn";
var popupArguments = [];
- popupArguments.push(createElement("a", { //Cancel Button
+ popupArguments.push(createElement("a", { // Cancel Button
innerText:"Cancel", class:"a-link-button",
clickListener:()=>{
removeElementById(popupId); return false;
}
}))
- popupArguments.push(createElement("p", { //Info Text
+ popupArguments.push(createElement("p", { // Info Text
innerText:"Travel to a different city for your Bladeburner " +
"activities. This does not cost any money. The city you are " +
"in for your Bladeburner duties does not affect " +
@@ -1971,8 +2008,10 @@ Bladeburner.prototype.createOverviewContent = function() {
for (var i = 0; i < CityNames.length; ++i) {
(function(inst, i) {
popupArguments.push(createElement("div", {
- //Reusing this css class...it adds a border and makes it
- //so that background color changes when you hover
+ /**
+ * Reusing this css class...it adds a border and makes it
+ * so that background color changes when you hover
+ */
class:"cmpy-mgmt-find-employee-option",
innerText:CityNames[i],
clickListener:()=>{
@@ -1988,7 +2027,7 @@ Bladeburner.prototype.createOverviewContent = function() {
}
}));
- //Faction button
+ // Faction button
const bladeburnersFactionName = "Bladeburners";
if (factionExists(bladeburnersFactionName)) {
var bladeburnerFac = Factions[bladeburnersFactionName];
@@ -2051,12 +2090,12 @@ Bladeburner.prototype.createActionAndSkillsContent = function() {
}) (buttons, i, this, currTab);
}
- //General info/description for each action
+ // General info/description for each action
DomElems.actionsAndSkillsDesc = createElement("p", {
display:"block", margin:"4px", padding:"4px"
});
- //List for actions/skills
+ // List for actions/skills
removeChildrenFromElement(DomElems.actionsAndSkillsList);
DomElems.actionsAndSkillsList = createElement("ul");
@@ -2171,7 +2210,7 @@ Bladeburner.prototype.createBlackOpsContent = function() {
"Like normal operations, you may use a team for Black Ops. Failing " +
"a black op will incur heavy HP and rank losses.";
- //Put Black Operations in sequence of required rank
+ // Put Black Operations in sequence of required rank
var blackops = [];
for (var blackopName in BlackOperations) {
if (BlackOperations.hasOwnProperty(blackopName)) {
@@ -2197,7 +2236,7 @@ Bladeburner.prototype.createSkillsContent = function() {
"DomElems.actionsAndSkillsList or DomElems.actionsAndSkillsDesc = null");
}
- //Display Current multipliers
+ // Display Current multipliers
DomElems.actionsAndSkillsDesc.innerHTML =
"You will gain one skill point every " + RanksPerSkillPoint + " ranks. " +
"Note that when upgrading a skill, the benefit for that skill is additive. " +
@@ -2260,10 +2299,10 @@ Bladeburner.prototype.createSkillsContent = function() {
DomElems.actionsAndSkillsDesc.innerHTML += "Exp Gain: x" + mult + " ";
break;
case "weaponAbility":
- //DomElems.actionsAndSkillsDesc.innerHTML +=
+ // TODO in the future if items are ever implemented
break;
case "gunAbility":
- //DomElems.actionsAndSkillsDesc.innerHTML
+ // TODO in the future if items are ever implemented
break;
default:
console.log("Warning: Unrecognized SkillMult Key: " + multKeys[i]);
@@ -2272,13 +2311,13 @@ Bladeburner.prototype.createSkillsContent = function() {
}
}
- //Skill Points
+ // Skill Points
DomElems.skillPointsDisplay = createElement("p", {
innerHTML:"Skill Points: " + formatNumber(this.skillPoints, 0) + " "
});
DomElems.actionAndSkillsDiv.appendChild(DomElems.skillPointsDisplay);
- //UI Element for each skill
+ // UI Element for each skill
for (var skillName in Skills) {
if (Skills.hasOwnProperty(skillName)) {
DomElems.skills[skillName] = createElement("div", {
@@ -2411,7 +2450,7 @@ Bladeburner.prototype.updateGeneralActionsUIElement = function(el, action) {
removeChildrenFromElement(el);
var isActive = el.classList.contains(ActiveActionCssClass);
- el.appendChild(createElement("h2", { //Header
+ el.appendChild(createElement("h2", { // Header
innerText:isActive ? action.name + " (IN PROGRESS - " +
formatNumber(this.actionTimeCurrent, 0) + " / " +
formatNumber(this.actionTimeToComplete, 0) + ")"
@@ -2419,14 +2458,14 @@ Bladeburner.prototype.updateGeneralActionsUIElement = function(el, action) {
display:"inline-block",
}));
- if (isActive) { //Progress bar if its active
+ if (isActive) { // Progress bar if its active
var progress = this.actionTimeCurrent / this.actionTimeToComplete;
el.appendChild(createElement("p", {
display:"block",
innerText:createProgressBarText({progress:progress})
}));
} else {
- //Start button
+ // Start button
el.appendChild(createElement("a", {
innerText:"Start", class: "a-link-button",
margin:"3px", padding:"3px",
@@ -2441,7 +2480,7 @@ Bladeburner.prototype.updateGeneralActionsUIElement = function(el, action) {
}
appendLineBreaks(el, 2);
- el.appendChild(createElement("pre", { //Info
+ el.appendChild(createElement("pre", { // Info
innerHTML:action.desc, display:"inline-block"
}));
@@ -2453,7 +2492,7 @@ Bladeburner.prototype.updateContractsUIElement = function(el, action) {
var isActive = el.classList.contains(ActiveActionCssClass);
var estimatedSuccessChance = action.getSuccessChance(this, {est:true});
- el.appendChild(createElement("h2", { //Header
+ el.appendChild(createElement("h2", { // Header
innerText:isActive ? action.name + " (IN PROGRESS - " +
formatNumber(this.actionTimeCurrent, 0) + " / " +
formatNumber(this.actionTimeToComplete, 0) + ")"
@@ -2461,13 +2500,13 @@ Bladeburner.prototype.updateContractsUIElement = function(el, action) {
display:"inline-block"
}));
- if (isActive) { //Progress bar if its active
+ if (isActive) { // Progress bar if its active
var progress = this.actionTimeCurrent / this.actionTimeToComplete;
el.appendChild(createElement("p", {
display:"block",
innerText:createProgressBarText({progress:progress})
}));
- } else { //Start button
+ } else { // Start button
el.appendChild(createElement("a", {
innerText:"Start", class: "a-link-button",
padding:"3px", margin:"3px",
@@ -2481,7 +2520,7 @@ Bladeburner.prototype.updateContractsUIElement = function(el, action) {
}));
}
- //Level and buttons to change level
+ // Level and buttons to change level
var maxLevel = (action.level >= action.maxLevel);
appendLineBreaks(el, 2);
el.appendChild(createElement("pre", {
@@ -2497,7 +2536,7 @@ Bladeburner.prototype.updateContractsUIElement = function(el, action) {
display:"inline",
clickListener:()=>{
++action.level;
- if (isActive) {this.startAction(this.action);} //Restart Action
+ if (isActive) {this.startAction(this.action);} // Restart Action
this.updateContractsUIElement(el, action);
return false;
}
@@ -2509,7 +2548,7 @@ Bladeburner.prototype.updateContractsUIElement = function(el, action) {
display:"inline",
clickListener:()=>{
--action.level;
- if (isActive) {this.startAction(this.action);} //Restart Action
+ if (isActive) {this.startAction(this.action);} // Restart Action
this.updateContractsUIElement(el, action);
return false;
}
@@ -2517,7 +2556,7 @@ Bladeburner.prototype.updateContractsUIElement = function(el, action) {
var actionTime = action.getActionTime(this);
appendLineBreaks(el, 2);
- el.appendChild(createElement("pre", { //Info
+ el.appendChild(createElement("pre", { // Info
display:"inline-block",
innerHTML:action.desc + "\n\n" +
`Estimated success chance: ${formatNumber(estimatedSuccessChance*100, 1)}% ${action.isStealth?stealthIcon:''}${action.isKill?killIcon:''}\n` +
@@ -2528,7 +2567,7 @@ Bladeburner.prototype.updateContractsUIElement = function(el, action) {
"Failures: " + action.failures,
}));
- //Autolevel Checkbox
+ // Autolevel Checkbox
el.appendChild(createElement("br"));
var autolevelCheckboxId = "bladeburner-" + action.name + "-autolevel-checkbox";
el.appendChild(createElement("label", {
@@ -2556,7 +2595,7 @@ Bladeburner.prototype.updateOperationsUIElement = function(el, action) {
removeChildrenFromElement(el);
var isActive = el.classList.contains(ActiveActionCssClass);
var estimatedSuccessChance = action.getSuccessChance(this, {est:true});
- el.appendChild(createElement("h2", { //Header
+ el.appendChild(createElement("h2", { // Header
innerText:isActive ? action.name + " (IN PROGRESS - " +
formatNumber(this.actionTimeCurrent, 0) + " / " +
formatNumber(this.actionTimeToComplete, 0) + ")"
@@ -2564,13 +2603,13 @@ Bladeburner.prototype.updateOperationsUIElement = function(el, action) {
display:"inline-block"
}));
- if (isActive) { //Progress bar if its active
+ if (isActive) { // Progress bar if its active
var progress = this.actionTimeCurrent / this.actionTimeToComplete;
el.appendChild(createElement("p", {
display:"block",
innerText:createProgressBarText({progress:progress})
}));
- } else { //Start button and set Team Size button
+ } else { // Start button and set Team Size button
el.appendChild(createElement("a", {
innerText:"Start", class: "a-link-button",
margin:"3px", padding:"3px",
@@ -2623,7 +2662,7 @@ Bladeburner.prototype.updateOperationsUIElement = function(el, action) {
}));
}
- //Level and buttons to change level
+ // Level and buttons to change level
var maxLevel = (action.level >= action.maxLevel);
appendLineBreaks(el, 2);
el.appendChild(createElement("pre", {
@@ -2639,7 +2678,7 @@ Bladeburner.prototype.updateOperationsUIElement = function(el, action) {
display:"inline",
clickListener:()=>{
++action.level;
- if (isActive) {this.startAction(this.action);} //Restart Action
+ if (isActive) {this.startAction(this.action);} // Restart Action
this.updateOperationsUIElement(el, action);
return false;
}
@@ -2651,13 +2690,13 @@ Bladeburner.prototype.updateOperationsUIElement = function(el, action) {
display:"inline",
clickListener:()=>{
--action.level;
- if (isActive) {this.startAction(this.action);} //Restart Action
+ if (isActive) {this.startAction(this.action);} // Restart Action
this.updateOperationsUIElement(el, action);
return false;
}
}));
- //General Info
+ // General Info
var difficulty = action.getDifficulty();
var actionTime = action.getActionTime(this);
appendLineBreaks(el, 2);
@@ -2671,7 +2710,7 @@ Bladeburner.prototype.updateOperationsUIElement = function(el, action) {
"Failures: " + action.failures,
}));
- //Autolevel Checkbox
+ // Autolevel Checkbox
el.appendChild(createElement("br"));
var autolevelCheckboxId = "bladeburner-" + action.name + "-autolevel-checkbox";
el.appendChild(createElement("label", {
@@ -2704,7 +2743,7 @@ Bladeburner.prototype.updateBlackOpsUIElement = function(el, action) {
var actionTime = action.getActionTime(this);
var hasReqdRank = this.rank >= action.reqdRank;
- //UI for Completed Black Op
+ // UI for Completed Black Op
if (isCompleted) {
el.appendChild(createElement("h2", {
innerText:action.name + " (COMPLETED)", display:"block",
@@ -2712,7 +2751,7 @@ Bladeburner.prototype.updateBlackOpsUIElement = function(el, action) {
return;
}
- el.appendChild(createElement("h2", { //Header
+ el.appendChild(createElement("h2", { // Header
innerText:isActive ? action.name + " (IN PROGRESS - " +
formatNumber(this.actionTimeCurrent, 0) + " / " +
formatNumber(this.actionTimeToComplete, 0) + ")"
@@ -2720,14 +2759,14 @@ Bladeburner.prototype.updateBlackOpsUIElement = function(el, action) {
display:"inline-block",
}));
- if (isActive) { //Progress bar if its active
+ if (isActive) { // Progress bar if its active
var progress = this.actionTimeCurrent / this.actionTimeToComplete;
el.appendChild(createElement("p", {
display:"block",
innerText:createProgressBarText({progress:progress})
}));
} else {
- el.appendChild(createElement("a", { //Start button
+ el.appendChild(createElement("a", { // Start button
innerText:"Start", margin:"3px", padding:"3px",
class:hasReqdRank ? "a-link-button" : "a-link-button-inactive",
clickListener:()=>{
@@ -2738,7 +2777,7 @@ Bladeburner.prototype.updateBlackOpsUIElement = function(el, action) {
return false;
}
}));
- el.appendChild(createElement("a", { //Set Team Size Button
+ el.appendChild(createElement("a", { // Set Team Size Button
innerText:"Set Team Size (Curr Size: " + formatNumber(action.teamCount, 0) + ")", class:"a-link-button",
margin:"3px", padding:"3px",
clickListener:()=>{
@@ -2779,7 +2818,7 @@ Bladeburner.prototype.updateBlackOpsUIElement = function(el, action) {
}));
}
- //Info
+ // Info
appendLineBreaks(el, 2);
el.appendChild(createElement("p", {
display:"inline-block",
@@ -2805,13 +2844,13 @@ Bladeburner.prototype.updateSkillsUIElement = function(el, skill) {
}
var pointCost = skill.calculateCost(currentLevel);
- el.appendChild(createElement("h2", { //Header
+ el.appendChild(createElement("h2", { // Header
innerText:skill.name + " (Lvl " + currentLevel + ")", display:"inline-block"
}));
var canLevel = this.skillPoints >= pointCost;
var maxLvl = skill.maxLvl ? currentLevel >= skill.maxLvl : false;
- el.appendChild(createElement("a", { //Level up button
+ el.appendChild(createElement("a", { // Level up button
innerText:"Level", display:"inline-block",
class: canLevel && !maxLvl ? "a-link-button" : "a-link-button-inactive",
margin:"3px", padding:"3px",
@@ -2835,12 +2874,12 @@ Bladeburner.prototype.updateSkillsUIElement = function(el, skill) {
innerText:"Skill Points required: " + formatNumber(pointCost, 0),
}));
}
- el.appendChild(createElement("p", { //Info/Description
+ el.appendChild(createElement("p", { // Info/Description
innerHTML:skill.desc, display:"inline-block",
}));
}
-//Bladeburner Console Window
+// Bladeburner Console Window
Bladeburner.prototype.postToConsole = function(input, saveToLogs=true) {
const MaxConsoleEntries = 100;
if (saveToLogs === true) {
@@ -2877,14 +2916,14 @@ Bladeburner.prototype.clearConsole = function() {
}
Bladeburner.prototype.log = function(input) {
- //Adds a timestamp and then just calls postToConsole
+ // Adds a timestamp and then just calls postToConsole
this.postToConsole(`[${getTimestamp()}] ${input}`);
}
-//Handles a potential series of commands (comm1; comm2; comm3;)
+// Handles a potential series of commands (comm1; comm2; comm3;)
Bladeburner.prototype.executeConsoleCommands = function(commands) {
try {
- //Console History
+ // Console History
if (this.consoleHistory[this.consoleHistory.length-1] != commands) {
this.consoleHistory.push(commands);
if (this.consoleHistory.length > 50) {
@@ -2902,13 +2941,13 @@ Bladeburner.prototype.executeConsoleCommands = function(commands) {
}
}
-//A single command
+// Execute a single console command
Bladeburner.prototype.executeConsoleCommand = function(command) {
command = command.trim();
- command = command.replace(/\s\s+/g, ' '); //Replace all whitespace w/ a single space
+ command = command.replace(/\s\s+/g, ' '); // Replace all whitespace w/ a single space
var args = this.parseCommandArguments(command);
- if (args.length <= 0) {return;} //Log an error?
+ if (args.length <= 0) {return;} // Log an error?
switch(args[0].toLowerCase()) {
case "automate":
@@ -2940,9 +2979,11 @@ Bladeburner.prototype.executeConsoleCommand = function(command) {
}
Bladeburner.prototype.parseCommandArguments = function(command) {
- //Returns an array with command and its arguments in each index.
- //e.g. skill "blade's intuition" foo returns [skill, blade's intuition, foo]
- //The input to this fn will be trimmed and will have all whitespace replaced w/ a single space
+ /**
+ * Returns an array with command and its arguments in each index.
+ * e.g. skill "blade's intuition" foo returns [skill, blade's intuition, foo]
+ * The input to this fn will be trimmed and will have all whitespace replaced w/ a single space
+ */
const args = [];
let start = 0, i = 0;
while (i < command.length) {
@@ -2954,7 +2995,7 @@ Bladeburner.prototype.parseCommandArguments = function(command) {
if (endQuote === command.length-1) {
start = i = endQuote+1;
} else {
- start = i = endQuote+2; //Skip the space
+ start = i = endQuote+2; // Skip the space
}
continue;
}
@@ -2965,7 +3006,7 @@ Bladeburner.prototype.parseCommandArguments = function(command) {
if (endQuote === command.length-1) {
start = i = endQuote+1;
} else {
- start = i = endQuote+2; //Skip the space
+ start = i = endQuote+2; // Skip the space
}
continue;
}
@@ -2986,7 +3027,7 @@ Bladeburner.prototype.executeAutomateConsoleCommand = function(args) {
return;
}
- //Enable/Disable
+ // Enable/Disable
if (args.length === 2) {
var flag = args[1];
if (flag.toLowerCase() === "status") {
@@ -3015,11 +3056,11 @@ Bladeburner.prototype.executeAutomateConsoleCommand = function(args) {
return;
}
- //Set variables
+ // Set variables
if (args.length === 4) {
var variable = args[1], val = args[2];
- var highLow = false; //True for high, false for low
+ var highLow = false; // True for high, false for low
if (args[3].toLowerCase().includes("hi")) {highLow = true;}
switch (variable) {
@@ -3115,7 +3156,7 @@ Bladeburner.prototype.executeLogConsoleCommand = function(args) {
}
var flag = true;
- if (args[1].toLowerCase().includes("d")) {flag = false;} //d for disable
+ if (args[1].toLowerCase().includes("d")) {flag = false;} // d for disable
switch (args[2].toLowerCase()) {
case "general":
@@ -3165,13 +3206,13 @@ Bladeburner.prototype.executeLogConsoleCommand = function(args) {
Bladeburner.prototype.executeSkillConsoleCommand = function(args) {
switch (args.length) {
case 1:
- //Display Skill Help Command
+ // Display Skill Help Command
this.postToConsole("Invalid usage of 'skill' console command: skill [action] [name]");
this.postToConsole("Use 'help skill' for more info");
break;
case 2:
if (args[1].toLowerCase() === "list") {
- //List all skills and their level
+ // List all skills and their level
this.postToConsole("Skills: ");
var skillNames = Object.keys(Skills);
for(var i = 0; i < skillNames.length; ++i) {
@@ -3234,10 +3275,10 @@ Bladeburner.prototype.executeSkillConsoleCommand = function(args) {
this.postToConsole("Stamina: x" + mult);
break;
case "weaponAbility":
- //DomElems.actionsAndSkillsDesc.innerHTML +=
+ // TODO if items are ever implemented
break;
case "gunAbility":
- //DomElems.actionsAndSkillsDesc.innerHTML
+ // TODO if items are ever implemented
break;
default:
console.log("Warning: Unrecognized SkillMult Key: " + multKeys[i]);
@@ -3851,12 +3892,14 @@ Bladeburner.fromJSON = function(value) {
}
Reviver.constructors.Bladeburner = Bladeburner;
-//This initialized Bladeburner-related data that is NOT saved/loaded
-// eg: Skill Objects, BLack Operations
-//Any data that is saved/loaded should go in Bladeburner object
-// eg: contracts, operations
+/**
+ * This initialized Bladeburner-related data that is NOT saved/loaded
+ * eg: Skill Objects, BLack Operations
+ * Any data that is saved/loaded should go in Bladeburner object
+ * eg: contracts, operations
+ */
function initBladeburner() {
- //Skills
+ // Skills
Skills[SkillNames.BladesIntuition] = new Skill({
name:SkillNames.BladesIntuition,
desc:"Each level of this skill increases your success chance " +
@@ -3872,8 +3915,8 @@ function initBladeburner() {
successChanceStealth:5.5
});
- //TODO Marksman
- //TODO Weapon Proficiency
+ // TODO Marksman - If items are ever implemented
+ // TODO Weapon Proficiency - If items are ever implemented
Skills[SkillNames.ShortCircuit] = new Skill({
name:SkillNames.ShortCircuit,
@@ -3944,7 +3987,7 @@ function initBladeburner() {
expGain: 10,
});
- //General Actions
+ // General Actions
let actionName;
actionName = "Training";
GeneralActions[actionName] = new Action({
@@ -3987,7 +4030,7 @@ function initBladeburner() {
"This will slowly heal your wounds and slightly increase your stamina. ",
});
- //Black Operations
+ // Black Operations
BlackOperations["Operation Typhoon"] = new BlackOperation({
name:"Operation Typhoon",
desc:"Obadiah Zenyatta is the leader of a RedWater PMC. It has long " +
@@ -4328,4 +4371,4 @@ function initBladeburner() {
});
}
-export {Bladeburner};
+export { Bladeburner };
diff --git a/src/CinematicText.js b/src/CinematicText.js
index ae0fc2aa9..f1899a5b9 100644
--- a/src/CinematicText.js
+++ b/src/CinematicText.js
@@ -1,3 +1,4 @@
+
import { Engine } from "./engine";
import { setTimeoutRef } from "./utils/SetTimeoutRef";
@@ -8,7 +9,12 @@ import { isString } from "../utils/helpers/isString";
export let cinematicTextFlag = false;
-// Lines must be an array of strings
+/**
+ * Print a message using a hacking-style "typing" effect.
+ * Note that this clears the UI so that the text from this is the only thing visible.
+ *
+ * @param lines {string[]} Array of strings to print, where each element is a separate line
+ */
export function writeCinematicText(lines) {
cinematicTextFlag = true;
diff --git a/src/CodingContractGenerator.js b/src/CodingContractGenerator.js
index 354a2e849..05a271017 100644
--- a/src/CodingContractGenerator.js
+++ b/src/CodingContractGenerator.js
@@ -130,14 +130,15 @@ function getRandomReward() {
});
switch (reward.type) {
- case CodingContractRewardType.FactionReputation:
+ case CodingContractRewardType.FactionReputation: {
// Get a random faction that player is a part of. That
// faction must allow hacking contracts
var numFactions = factionsThatAllowHacking.length;
var randFaction = factionsThatAllowHacking[getRandomInt(0, numFactions - 1)];
reward.name = randFaction;
break;
- case CodingContractRewardType.CompanyReputation:
+ }
+ case CodingContractRewardType.CompanyReputation: {
const allJobs = Object.keys(Player.jobs);
if (allJobs.length > 0) {
reward.name = allJobs[getRandomInt(0, allJobs.length - 1)];
@@ -145,6 +146,7 @@ function getRandomReward() {
reward.type = CodingContractRewardType.Money;
}
break;
+ }
default:
break;
}
diff --git a/src/Constants.ts b/src/Constants.ts
index a37ff6534..855d36d52 100644
--- a/src/Constants.ts
+++ b/src/Constants.ts
@@ -8,93 +8,93 @@ import { IMap } from "./types";
export let CONSTANTS: IMap = {
Version: "0.46.1",
- //Max level for any skill, assuming no multipliers. Determined by max numerical value in javascript for experience
- //and the skill level formula in Player.js. Note that all this means it that when experience hits MAX_INT, then
- //the player will have this level assuming no multipliers. Multipliers can cause skills to go above this.
+ /** Max level for any skill, assuming no multipliers. Determined by max numerical value in javascript for experience
+ * and the skill level formula in Player.js. Note that all this means it that when experience hits MAX_INT, then
+ * the player will have this level assuming no multipliers. Multipliers can cause skills to go above this.
+ */
MaxSkillLevel: 975,
- //Milliseconds per game cycle
+ // Milliseconds per game cycle
MilliPerCycle: 200,
- //How much reputation is needed to join a megacorporation's faction
+ // How much reputation is needed to join a megacorporation's faction
CorpFactionRepRequirement: 200e3,
- /* Base costs */
+ // Base RAM costs
BaseCostFor1GBOfRamHome: 32000,
BaseCostFor1GBOfRamServer: 55000, //1 GB of RAM
+ // Cost to travel to another city
TravelCost: 200e3,
- /* Faction and Company favor */
- BaseFavorToDonate: 150,
- DonateMoneyToRepDivisor: 1e6,
+ // Faction and Company favor-related things
+ BaseFavorToDonate: 150,
+ DonateMoneyToRepDivisor: 1e6,
FactionReputationToFavorBase: 500,
FactionReputationToFavorMult: 1.02,
CompanyReputationToFavorBase: 500,
CompanyReputationToFavorMult: 1.02,
- /* Augmentation */
- //NeuroFlux Governor cost multiplier as you level up
+ // NeuroFlux Governor Augmentation cost multiplier
NeuroFluxGovernorLevelMult: 1.14,
- /* Netscript Constants */
- //RAM Costs for different commands
- ScriptBaseRamCost: 1.6,
- ScriptDomRamCost: 25,
- ScriptWhileRamCost: 0,
- ScriptForRamCost: 0,
- ScriptIfRamCost: 0,
- ScriptHackRamCost: 0.1,
- ScriptHackAnalyzeRamCost: 1,
- ScriptGrowRamCost: 0.15,
- ScriptGrowthAnalyzeRamCost: 1,
- ScriptWeakenRamCost: 0.15,
- ScriptScanRamCost: 0.2,
- ScriptPortProgramRamCost: 0.05,
- ScriptRunRamCost: 1.0,
- ScriptExecRamCost: 1.3,
- ScriptSpawnRamCost: 2.0,
- ScriptScpRamCost: 0.6,
- ScriptKillRamCost: 0.5, //Kill and killall
- ScriptHasRootAccessRamCost: 0.05,
- ScriptGetHostnameRamCost: 0.05, //getHostname() and getIp()
- ScriptGetHackingLevelRamCost: 0.05, //getHackingLevel()
- ScriptGetMultipliersRamCost: 4.0, //getHackingMultipliers() and getBitNodeMultipliers()
- ScriptGetServerRamCost: 0.1,
- ScriptFileExistsRamCost: 0.1,
- ScriptIsRunningRamCost: 0.1,
- ScriptHacknetNodesRamCost: 4.0, //Base cost for accessing Hacknet Node API
- ScriptHNUpgLevelRamCost: 0.4,
- ScriptHNUpgRamRamCost: 0.6,
- ScriptHNUpgCoreRamCost: 0.8,
- ScriptGetStockRamCost: 2.0,
- ScriptBuySellStockRamCost: 2.5,
+ // RAM Costs for Netscript functions
+ ScriptBaseRamCost: 1.6,
+ ScriptDomRamCost: 25,
+ ScriptWhileRamCost: 0,
+ ScriptForRamCost: 0,
+ ScriptIfRamCost: 0,
+ ScriptHackRamCost: 0.1,
+ ScriptHackAnalyzeRamCost: 1,
+ ScriptGrowRamCost: 0.15,
+ ScriptGrowthAnalyzeRamCost: 1,
+ ScriptWeakenRamCost: 0.15,
+ ScriptScanRamCost: 0.2,
+ ScriptPortProgramRamCost: 0.05,
+ ScriptRunRamCost: 1.0,
+ ScriptExecRamCost: 1.3,
+ ScriptSpawnRamCost: 2.0,
+ ScriptScpRamCost: 0.6,
+ ScriptKillRamCost: 0.5,
+ ScriptHasRootAccessRamCost: 0.05,
+ ScriptGetHostnameRamCost: 0.05,
+ ScriptGetHackingLevelRamCost: 0.05,
+ ScriptGetMultipliersRamCost: 4.0,
+ ScriptGetServerRamCost: 0.1,
+ ScriptFileExistsRamCost: 0.1,
+ ScriptIsRunningRamCost: 0.1,
+ ScriptHacknetNodesRamCost: 4.0,
+ ScriptHNUpgLevelRamCost: 0.4,
+ ScriptHNUpgRamRamCost: 0.6,
+ ScriptHNUpgCoreRamCost: 0.8,
+ ScriptGetStockRamCost: 2.0,
+ ScriptBuySellStockRamCost: 2.5,
ScriptGetPurchaseServerRamCost: 0.25,
- ScriptPurchaseServerRamCost: 2.25,
- ScriptGetPurchasedServerLimit: 0.05,
+ ScriptPurchaseServerRamCost: 2.25,
+ ScriptGetPurchasedServerLimit: 0.05,
ScriptGetPurchasedServerMaxRam: 0.05,
- ScriptRoundRamCost: 0.05,
- ScriptReadWriteRamCost: 1.0,
- ScriptArbScriptRamCost: 1.0, // Functions that apply to all scripts regardless of args
- ScriptGetScriptRamCost: 0.1,
- ScriptGetHackTimeRamCost: 0.05,
- ScriptGetFavorToDonate: 0.10,
- ScriptCodingContractBaseRamCost:10,
- ScriptSleeveBaseRamCost: 4,
+ ScriptRoundRamCost: 0.05,
+ ScriptReadWriteRamCost: 1.0,
+ ScriptArbScriptRamCost: 1.0,
+ ScriptGetScriptRamCost: 0.1,
+ ScriptGetHackTimeRamCost: 0.05,
+ ScriptGetFavorToDonate: 0.10,
+ ScriptCodingContractBaseRamCost: 10,
+ ScriptSleeveBaseRamCost: 4,
- ScriptSingularityFn1RamCost: 1,
- ScriptSingularityFn2RamCost: 2,
- ScriptSingularityFn3RamCost: 3,
+ ScriptSingularityFn1RamCost: 1,
+ ScriptSingularityFn2RamCost: 2,
+ ScriptSingularityFn3RamCost: 3,
- ScriptSingularityFnRamMult: 2, // Multiplier for RAM cost outside of BN-4
+ ScriptSingularityFnRamMult: 2, // Multiplier for RAM cost outside of BN-4
- ScriptGangApiBaseRamCost: 4,
+ ScriptGangApiBaseRamCost: 4,
- ScriptBladeburnerApiBaseRamCost: 4,
+ ScriptBladeburnerApiBaseRamCost: 4,
- NumNetscriptPorts: 20,
+ NumNetscriptPorts: 20,
- //Server constants
+ // Server-related constants
HomeComputerMaxRam: 1073741824, // 2 ^ 30
ServerBaseGrowthRate: 1.03, // Unadjusted Growth rate
ServerMaxGrowthRate: 1.0035, // Maximum possible growth rate (max rate accounting for server security)
@@ -102,49 +102,50 @@ export let CONSTANTS: IMap = {
ServerWeakenAmount: 0.05, // Amount by which server's security decreases when weakened
PurchasedServerLimit: 25,
- PurchasedServerMaxRam: 1048576, //2^20
+ PurchasedServerMaxRam: 1048576, // 2^20
- //Augmentation Constants
- AugmentationCostMultiplier: 5, //Used for balancing costs without having to readjust every Augmentation cost
- AugmentationRepMultiplier: 2.5, //Used for balancing rep cost without having to readjust every value
- MultipleAugMultiplier: 1.9,
+ // Augmentation Constants
+ AugmentationCostMultiplier: 5, // Used for balancing costs without having to readjust every Augmentation cost
+ AugmentationRepMultiplier: 2.5, // Used for balancing rep cost without having to readjust every value
+ MultipleAugMultiplier: 1.9,
- //How much a TOR router costs
- TorRouterCost: 200000,
+ // TOR Router
+ TorRouterCost: 200e3,
- //Infiltration constants
+ // Infiltration
InfiltrationBribeBaseAmount: 100e3, //Amount per clearance level
- InfiltrationMoneyValue: 5e3, //Convert "secret" value to money
+ InfiltrationMoneyValue: 5e3, //Convert "secret" value to money
InfiltrationRepValue: 1.4, //Convert "secret" value to faction reputation
InfiltrationExpPow: 0.8,
- //Stock market constants
- WSEAccountCost: 200e6,
- TIXAPICost: 5e9,
- MarketData4SCost: 1e9,
+ // Stock market
+ WSEAccountCost: 200e6,
+ TIXAPICost: 5e9,
+ MarketData4SCost: 1e9,
MarketDataTixApi4SCost: 25e9,
- StockMarketCommission: 100e3,
+ StockMarketCommission: 100e3,
- //Hospital/Health
+ // Hospital/Health
HospitalCostPerHp: 100e3,
- //Intelligence-related constants
- IntelligenceCrimeWeight: 0.05, //Weight for how much int affects crime success rates
- IntelligenceInfiltrationWeight: 0.1, //Weight for how much int affects infiltration success rates
+ // Intelligence-related constants
+ IntelligenceCrimeWeight: 0.05, // Weight for how much int affects crime success rates
+ IntelligenceInfiltrationWeight: 0.1, // Weight for how much int affects infiltration success rates
IntelligenceCrimeBaseExpGain: 0.001,
- IntelligenceProgramBaseExpGain: 500, //Program required hack level divided by this to determine int exp gain
- IntelligenceTerminalHackBaseExpGain: 200, //Hacking exp divided by this to determine int exp gain
+ IntelligenceProgramBaseExpGain: 500, // Program required hack level divided by this to determine int exp gain
+ IntelligenceTerminalHackBaseExpGain: 200, // Hacking exp divided by this to determine int exp gain
IntelligenceSingFnBaseExpGain: 0.002,
IntelligenceClassBaseExpGain: 0.000001,
- IntelligenceHackingMissionBaseExpGain: 0.03, //Hacking Mission difficulty multiplied by this to get exp gain
+ IntelligenceHackingMissionBaseExpGain: 0.03, // Hacking Mission difficulty multiplied by this to get exp gain
- //Hacking Missions
- HackingMissionRepToDiffConversion: 10000, //Faction rep is divided by this to get mission difficulty
- HackingMissionRepToRewardConversion: 7, //Faction rep divided byt his to get mission rep reward
- HackingMissionSpamTimeIncrease: 25000, //How much time limit increase is gained when conquering a Spam Node (ms)
- HackingMissionTransferAttackIncrease: 1.05, //Multiplier by which the attack for all Core Nodes is increased when conquering a Transfer Node
- HackingMissionMiscDefenseIncrease: 1.05, //The amount by which every misc node's defense is multiplied when one is conquered
- HackingMissionDifficultyToHacking: 135, //Difficulty is multiplied by this to determine enemy's "hacking" level (to determine effects of scan/attack, etc)
+ // Hacking Missions
+ // TODO Move this into Hacking Mission implementation
+ HackingMissionRepToDiffConversion: 10000, // Faction rep is divided by this to get mission difficulty
+ HackingMissionRepToRewardConversion: 7, // Faction rep divided byt his to get mission rep reward
+ HackingMissionSpamTimeIncrease: 25000, // How much time limit increase is gained when conquering a Spam Node (ms)
+ HackingMissionTransferAttackIncrease: 1.05, // Multiplier by which the attack for all Core Nodes is increased when conquering a Transfer Node
+ HackingMissionMiscDefenseIncrease: 1.05, // The amount by which every misc node's defense is multiplied when one is conquered
+ HackingMissionDifficultyToHacking: 135, // Difficulty is multiplied by this to determine enemy's "hacking" level (to determine effects of scan/attack, etc)
HackingMissionHowToPlay: "Hacking missions are a minigame that, if won, will reward you with faction reputation. " +
"In this game you control a set of Nodes and use them to try and defeat an enemy. Your Nodes " +
"are colored blue, while the enemy's are red. There are also other nodes on the map colored gray " +
@@ -192,7 +193,7 @@ export let CONSTANTS: IMap = {
"-Miscellaneous Nodes slowly raise their defense over time " +
"-Nodes slowly regenerate health over time.",
- /* Time Constants */
+ // Time-related constants
MillisecondsPer20Hours: 72000000,
GameCyclesPer20Hours: 72000000 / 200,
@@ -220,7 +221,7 @@ export let CONSTANTS: IMap = {
MillisecondsPerFiveMinutes: 300000,
GameCyclesPerFiveMinutes: 300000 / 200,
- /* Player Work / Action related Constants */
+ // Player Work & Action
FactionWorkHacking: "Faction Hacking Work",
FactionWorkField: "Faction Field Work",
FactionWorkSecurity: "Faction Security Work",
@@ -263,10 +264,11 @@ export let CONSTANTS: IMap = {
CrimeAssassination: "assassinate a high-profile target",
CrimeHeist: "pull off the ultimate heist",
- /* Coding Contract Constants */
- CodingContractBaseFactionRepGain: 2500,
- CodingContractBaseCompanyRepGain: 4000,
- CodingContractBaseMoneyGain: 75e6,
+ // Coding Contract
+ // TODO Move this into Coding contract impelmentation?
+ CodingContractBaseFactionRepGain: 2500,
+ CodingContractBaseCompanyRepGain: 4000,
+ CodingContractBaseMoneyGain: 75e6,
// BitNode/Source-File related stuff
TotalNumBitNodes: 24,
diff --git a/src/DevMenu.jsx b/src/DevMenu.jsx
index 9d3ec83cd..4ffddc824 100644
--- a/src/DevMenu.jsx
+++ b/src/DevMenu.jsx
@@ -33,7 +33,12 @@ import ReactDOM from "react-dom";
const Component = React.Component;
-const validSFN = [1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12];
+// Update as additional BitNodes get implemented
+const validSFN = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
+
+// Some dev menu buttons just add a lot of something for convenience
+const tonsPP = 1e27;
+const tonsP = 1e12;
class ValueAdjusterComponent extends Component {
@@ -189,13 +194,13 @@ class DevMenuComponent extends Component {
}
tonsOfExp() {
- Player.gainHackingExp(1e27);
- Player.gainStrengthExp(1e27);
- Player.gainDefenseExp(1e27);
- Player.gainDexterityExp(1e27);
- Player.gainAgilityExp(1e27);
- Player.gainCharismaExp(1e27);
- Player.gainIntelligenceExp(1e27);
+ Player.gainHackingExp(tonsPP);
+ Player.gainStrengthExp(tonsPP);
+ Player.gainDefenseExp(tonsPP);
+ Player.gainDexterityExp(tonsPP);
+ Player.gainAgilityExp(tonsPP);
+ Player.gainCharismaExp(tonsPP);
+ Player.gainIntelligenceExp(tonsPP);
Player.updateSkillLevels();
}
@@ -298,7 +303,7 @@ class DevMenuComponent extends Component {
tonsOfRep() {
for (const i in Factions) {
- Factions[i].playerReputation = 1e27;
+ Factions[i].playerReputation = tonsPP;
}
}
@@ -310,7 +315,7 @@ class DevMenuComponent extends Component {
tonsOfFactionFavor() {
for (const i in Factions) {
- Factions[i].favor = 1e27;
+ Factions[i].favor = tonsPP;
}
}
@@ -456,7 +461,7 @@ class DevMenuComponent extends Component {
tonsOfRepCompanies() {
for (const c in Companies) {
- Companies[c].playerReputation = 1e12;
+ Companies[c].playerReputation = tonsP;
}
}
@@ -468,7 +473,7 @@ class DevMenuComponent extends Component {
tonsOfFavorCompanies() {
for (const c in Companies) {
- Companies[c].favor = 1e12;
+ Companies[c].favor = tonsP;
}
}
@@ -493,7 +498,7 @@ class DevMenuComponent extends Component {
addTonsBladeburnerRank() {
if (!!Player.bladeburner) {
- Player.bladeburner.changeRank(1e12);
+ Player.bladeburner.changeRank(tonsP);
}
}
@@ -513,13 +518,13 @@ class DevMenuComponent extends Component {
addTonsBladeburnerCycles() {
if (!!Player.bladeburner) {
- Player.bladeburner.storedCycles += 1e12;
+ Player.bladeburner.storedCycles += tonsP;
}
}
addTonsGangCycles() {
if (!!Player.gang) {
- Player.gang.storedCycles = 1e12;
+ Player.gang.storedCycles = tonsP;
}
}
@@ -539,7 +544,7 @@ class DevMenuComponent extends Component {
addTonsCorporationCycles() {
if (!!Player.corporation) {
- Player.corporation.storedCycles = 1e12;
+ Player.corporation.storedCycles = tonsP;
}
}
@@ -646,16 +651,16 @@ class DevMenuComponent extends Component {
let sourceFiles = [];
validSFN.forEach( i => sourceFiles.push(
-
- SF-{i}:
-
- 0
- 1
- 2
- 3
-
-
-));
+
+ SF-{i}:
+
+ 0
+ 1
+ 2
+ 3
+
+
+ ));
@@ -1187,7 +1192,6 @@ class DevMenuComponent extends Component {
}
}
-
const devMenuContainerId = "dev-menu-container";
export function createDevMenu() {
@@ -1201,11 +1205,11 @@ export function createDevMenu() {
id: devMenuContainerId,
});
- const entireGameContainer = document.getElementById("entire-game-container");
- if (entireGameContainer == null) {
- throw new Error("Could not find entire-game-container DOM element");
- }
- entireGameContainer.appendChild(devMenuContainer);
+ const entireGameContainer = document.getElementById("entire-game-container");
+ if (entireGameContainer == null) {
+ throw new Error("Could not find entire-game-container DOM element");
+ }
+ entireGameContainer.appendChild(devMenuContainer);
ReactDOM.render( , devMenuContainer);
}
diff --git a/src/Gang.js b/src/Gang.js
index fcd9ddfbd..b8c80b4b2 100644
--- a/src/Gang.js
+++ b/src/Gang.js
@@ -1,6 +1,7 @@
-/*
-Also add police clashes
-balance point to keep them from running out of control
+/**
+ * TODO
+ * Add police clashes
+ * balance point to keep them from running out of control
*/
import { gangMemberTasksMetadata } from "./data/gangmembertasks";
@@ -57,7 +58,7 @@ $(document).keydown(function(event) {
}
});
-//Delete upgrade box when clicking outside
+// Delete upgrade box when clicking outside
$(document).mousedown(function(event) {
var boxId = "gang-member-upgrade-popup-box";
var contentId = "gang-member-upgrade-popup-box-content";
@@ -144,12 +145,12 @@ export function loadAllGangs(saveString) {
}
/**
- * @param facName - Name of corresponding faction
- * @param hacking - Boolean indicating whether or not its a hacking gang
+ * @param facName {string} Name of corresponding faction
+ * @param hacking {bollean} Whether or not its a hacking gang
*/
export function Gang(facName, hacking=false) {
this.facName = facName;
- this.members = []; //Array of GangMembers
+ this.members = [];
this.wanted = 1;
this.respect = 1;
@@ -204,7 +205,7 @@ Gang.prototype.process = function(numCycles=1, player) {
}
Gang.prototype.processGains = function(numCycles=1, player) {
- //Get gains per cycle
+ // Get gains per cycle
var moneyGains = 0, respectGains = 0, wantedLevelGains = 0;
for (var i = 0; i < this.members.length; ++i) {
respectGains += (this.members[i].calculateRespectGain(this));
@@ -569,10 +570,9 @@ Gang.fromJSON = function(value) {
Reviver.constructors.Gang = Gang;
-/*** Gang Member object ***/
function GangMember(name) {
this.name = name;
- this.task = "Unassigned"; //GangMemberTask object
+ this.task = "Unassigned";
this.earnedRespect = 0;
@@ -604,11 +604,11 @@ function GangMember(name) {
this.agi_asc_mult = 1;
this.cha_asc_mult = 1;
- this.upgrades = []; //Names of upgrades
- this.augmentations = []; //Names only
+ this.upgrades = []; // Names of upgrades
+ this.augmentations = []; // Names of augmentations only
}
-//Same formula for Player
+// Same skill calculation formula as Player
GangMember.prototype.calculateSkill = function(exp, mult=1) {
return Math.max(Math.floor(mult * (32 * Math.log(exp + 534.5) - 200)), 1);
}
@@ -652,7 +652,7 @@ GangMember.prototype.getTask = function() {
return GangMemberTasks["Unassigned"];
}
-//Gains are per cycle
+// Gains are per cycle
GangMember.prototype.calculateRespectGain = function(gang) {
const task = this.getTask();
if (task == null || !(task instanceof GangMemberTask) || task.baseRespect === 0) {return 0;}
@@ -777,9 +777,11 @@ GangMember.prototype.ascend = function() {
// Returns the multipliers that would be gained from ascension
GangMember.prototype.getAscensionResults = function() {
- // Calculate ascension bonus to stat multipliers.
- // This is based on the current number of multipliers from Non-Augmentation upgrades
- // + Ascension Bonus = N% of current bonus from Augmentations
+ /**
+ * Calculate ascension bonus to stat multipliers.
+ * This is based on the current number of multipliers from Non-Augmentation upgrades
+ * + Ascension Bonus = N% of current bonus from Augmentations
+ */
let hack = 1;
let str = 1;
let def = 1;
@@ -844,7 +846,7 @@ GangMember.fromJSON = function(value) {
Reviver.constructors.GangMember = GangMember;
-//Defines tasks that Gang Members can work on
+// Defines tasks that Gang Members can work on
function GangMemberTask(name="", desc="", isHacking=false, isCombat=false,
params={baseRespect: 0, baseWanted: 0, baseMoney: 0,
hackWeight: 0, strWeight: 0, defWeight: 0,
@@ -942,7 +944,7 @@ GangMemberUpgrade.prototype.createDescription = function() {
this.desc = lines.join(" ");
}
-//Passes in a GangMember object
+// Passes in a GangMember object
GangMemberUpgrade.prototype.apply = function(member) {
if (this.mults.str != null) { member.str_mult *= this.mults.str; }
if (this.mults.def != null) { member.def_mult *= this.mults.def; }
@@ -978,7 +980,7 @@ gangMemberUpgradesMetadata.forEach((e) => {
Gang.prototype.createGangMemberUpgradeBox = function(player, initialFilter="") {
const boxId = "gang-member-upgrade-popup-box";
if (UIElems.gangMemberUpgradeBoxOpened) {
- //Already opened, refreshing
+ // Already opened, refreshing
if (UIElems.gangMemberUpgradeBoxElements == null || UIElems.gangMemberUpgradeBox == null || UIElems.gangMemberUpgradeBoxContent == null) {
console.error("Refreshing Gang member upgrade box throws error because required elements are null");
return;
@@ -998,7 +1000,7 @@ Gang.prototype.createGangMemberUpgradeBox = function(player, initialFilter="") {
}
}
} else {
- //New popup
+ // New popup
UIElems.gangMemberUpgradeBoxFilter = createElement("input", {
type:"text", placeholder:"Filter gang members",
value:initialFilter,
@@ -1030,7 +1032,7 @@ Gang.prototype.createGangMemberUpgradeBox = function(player, initialFilter="") {
}
}
-//Create upgrade panels for each individual Gang Member
+// Create upgrade panels for each individual Gang Member
GangMember.prototype.createGangMemberUpgradePanel = function(gangObj, player) {
var container = createElement("div", {
border:"1px solid white",
@@ -1052,7 +1054,7 @@ GangMember.prototype.createGangMemberUpgradePanel = function(gangObj, player) {
"Cha: " + this.cha + " (x" + formatNumber(this.cha_mult * this.cha_asc_mult, 2) + ")\n",
});
- //Already purchased upgrades
+ // Already purchased upgrades
const ownedUpgradesElements = [];
function pushOwnedUpgrade(upgName) {
const upg = GangMemberUpgrades[upgName];
@@ -1078,7 +1080,7 @@ GangMember.prototype.createGangMemberUpgradePanel = function(gangObj, player) {
container.appendChild(ownedUpgrades);
container.appendChild(createElement("br", {}));
- //Upgrade buttons. Only show upgrades that can be afforded
+ // Upgrade buttons. Only show upgrades that can be afforded
const weaponUpgrades = [];
const armorUpgrades = [];
const vehicleUpgrades = [];
@@ -1210,18 +1212,18 @@ Gang.prototype.displayGangContent = function(player) {
if (!UIElems.gangContentCreated || UIElems.gangContainer == null) {
UIElems.gangContentCreated = true;
- //Create gang container
+ // Create gang container
UIElems.gangContainer = createElement("div", {
id:"gang-container", class:"generic-menupage-container",
});
- //Get variables
+ // Get variables
var facName = this.facName,
members = this.members,
wanted = this.wanted,
respect = this.respect;
- //Back button
+ // Back button
UIElems.gangContainer.appendChild(createElement("a", {
class:"a-link-button", display:"inline-block", innerText:"Back",
clickListener:()=>{
@@ -1231,7 +1233,7 @@ Gang.prototype.displayGangContent = function(player) {
}
}));
- //Buttons to switch between panels
+ // Buttons to switch between panels
UIElems.managementButton = createElement("a", {
id:"gang-management-subpage-button", class:"a-link-button-inactive",
display:"inline-block", innerHTML: "Gang Management (Alt+1)",
@@ -1263,7 +1265,7 @@ Gang.prototype.displayGangContent = function(player) {
UIElems.gangContainer.appendChild(UIElems.managementButton);
UIElems.gangContainer.appendChild(UIElems.territoryButton);
- //Subpage for managing gang members
+ // Subpage for managing gang members
UIElems.gangManagementSubpage = createElement("div", {
display:"block", id:"gang-management-subpage",
});
@@ -1359,7 +1361,7 @@ Gang.prototype.displayGangContent = function(player) {
});
UIElems.gangManagementSubpage.appendChild(UIElems.gangRecruitRequirementText);
- //Gang Member List management buttons (Expand/Collapse All, select a single member)
+ // Gang Member List management buttons (Expand/Collapse All, select a single member)
UIElems.gangManagementSubpage.appendChild(createElement("br", {}));
UIElems.gangExpandAllButton = createElement("a", {
class:"a-link-button", display:"inline-block",
@@ -1407,17 +1409,17 @@ Gang.prototype.displayGangContent = function(player) {
UIElems.gangManagementSubpage.appendChild(UIElems.gangMemberFilter);
UIElems.gangManagementSubpage.appendChild(UIElems.gangManageEquipmentButton);
- //Gang Member list
+ // Gang Member list
UIElems.gangMemberList = createElement("ul", {id:"gang-member-list"});
this.displayGangMemberList();
UIElems.gangManagementSubpage.appendChild(UIElems.gangMemberList);
- //Subpage for seeing gang territory information
+ // Subpage for seeing gang territory information
UIElems.gangTerritorySubpage = createElement("div", {
id:"gang-territory-subpage", display:"none"
});
- //Info text for territory page
+ // Info text for territory page
UIElems.gangTerritoryDescText = createElement("p", {
width:"70%",
innerHTML:
@@ -1582,7 +1584,7 @@ Gang.prototype.updateGangContent = function() {
}
}
} else {
- //Update information for overall gang
+ // Update information for overall gang
if (UIElems.gangInfo instanceof Element) {
var faction = Factions[this.facName];
var rep;
@@ -1592,7 +1594,7 @@ Gang.prototype.updateGangContent = function() {
rep = faction.playerReputation;
}
removeChildrenFromElement(UIElems.gangInfo);
- UIElems.gangInfo.appendChild(createElement("p", { // Respect
+ UIElems.gangInfo.appendChild(createElement("p", { // Respect
display: "inline-block",
innerText: "Respect: " + formatNumber(this.respect, 6) +
" (" + formatNumber(5*this.respectGainRate, 6) + " / sec)",
@@ -1603,7 +1605,7 @@ Gang.prototype.updateGangContent = function() {
}));
UIElems.gangInfo.appendChild(createElement("br"));
- UIElems.gangInfo.appendChild(createElement("p", { // Wanted level
+ UIElems.gangInfo.appendChild(createElement("p", { // Wanted level
display: "inline-block",
innerText: "Wanted Level: " + formatNumber(this.wanted, 6) +
" (" + formatNumber(5*this.wantedGainRate, 6) + " / sec)",
@@ -1615,20 +1617,20 @@ Gang.prototype.updateGangContent = function() {
var wantedPenalty = this.getWantedPenalty();
wantedPenalty = (1 - wantedPenalty) * 100;
- UIElems.gangInfo.appendChild(createElement("p", { // Wanted Level multiplier
+ UIElems.gangInfo.appendChild(createElement("p", { // Wanted Level multiplier
display: "inline-block",
innerText: `Wanted Level Penalty: -${formatNumber(wantedPenalty, 2)}%`,
tooltip: "Penalty for respect and money gain rates due to Wanted Level"
}));
UIElems.gangInfo.appendChild(createElement("br"));
- UIElems.gangInfo.appendChild(createElement("p", { // Money gain rate
+ UIElems.gangInfo.appendChild(createElement("p", { // Money gain rate
display: "inline-block",
innerText: `Money gain rate: ${numeralWrapper.format(5 * this.moneyGainRate, "$0.000a")} / sec`,
}));
UIElems.gangInfo.appendChild(createElement("br"));
- //Fix some rounding issues graphically
+ // Fix some rounding issues graphically
var territoryMult = AllGangs[this.facName].territory * 100;
let displayNumber;
if (territoryMult <= 0) {
@@ -1663,7 +1665,7 @@ Gang.prototype.updateGangContent = function() {
console.error("gang-info DOM element DNE");
}
- //Toggle the 'Recruit member button' if valid
+ // Toggle the 'Recruit member button' if valid
const numMembers = this.members.length;
const respectCost = this.getRespectNeededToRecruitMember();
@@ -1681,14 +1683,14 @@ Gang.prototype.updateGangContent = function() {
UIElems.gangRecruitRequirementText.innerHTML = `${formatNumber(respectCost, 2)} respect needed to recruit next member`;
}
- //Update information for each gang member
+ // Update information for each gang member
for (let i = 0; i < this.members.length; ++i) {
this.updateGangMemberDisplayElement(this.members[i]);
}
}
}
-//Takes in a GangMember object
+// Takes in a GangMember object
Gang.prototype.createGangMemberDisplayElement = function(memberObj) {
if (!UIElems.gangContentCreated) { return; }
const name = memberObj.name;
@@ -1829,7 +1831,7 @@ Gang.prototype.createGangMemberDisplayElement = function(memberObj) {
taskDiv.appendChild(taskSelector);
taskDiv.appendChild(gainInfo);
- //Panel for Description of task
+ // Panel for Description of task
var taskDescDiv = createElement("div", {
class:"gang-member-info-div",
id: name + "gang-member-task-desc",
diff --git a/src/Infiltration.js b/src/Infiltration.js
index 5b78e5f86..e7a5c95cd 100644
--- a/src/Infiltration.js
+++ b/src/Infiltration.js
@@ -17,21 +17,21 @@ let InfiltrationScenarios = {
}
function InfiltrationInstance(companyName, startLevel, val, maxClearance, diff) {
- this.companyName = companyName;
- this.clearanceLevel = 0;
- this.maxClearanceLevel = maxClearance;
- this.securityLevel = startLevel;
- this.difficulty = diff; //Affects how much security level increases. Represents a percentage
- this.baseValue = val; //Base value of company secrets
- this.secretsStolen = []; //Numbers representing value of stolen secrets
+ this.companyName = companyName;
+ this.clearanceLevel = 0;
+ this.maxClearanceLevel = maxClearance;
+ this.securityLevel = startLevel;
+ this.difficulty = diff; // Affects how much security level increases. Represents a percentage
+ this.baseValue = val; // Base value of company secrets
+ this.secretsStolen = []; // Numbers representing value of stolen secrets
- this.hackingExpGained = 0;
- this.strExpGained = 0;
- this.defExpGained = 0;
- this.dexExpGained = 0;
- this.agiExpGained = 0;
- this.chaExpGained = 0;
- this.intExpGained = 0;
+ this.hackingExpGained = 0;
+ this.strExpGained = 0;
+ this.defExpGained = 0;
+ this.dexExpGained = 0;
+ this.agiExpGained = 0;
+ this.chaExpGained = 0;
+ this.intExpGained = 0;
}
InfiltrationInstance.prototype.expMultiplier = function() {
@@ -106,7 +106,7 @@ InfiltrationInstance.prototype.gainIntelligenceExp = function(amt) {
InfiltrationInstance.prototype.calcGainedIntelligenceExp = function() {
if(!this.intExpGained || isNaN(this.intExpGained)) return 0;
- return Math.pow(this.intExpGained*this.expMultiplier(), CONSTANTS.InfiltrationExpPow);
+ return Math.pow(this.intExpGained * this.expMultiplier(), CONSTANTS.InfiltrationExpPow);
}
function beginInfiltration(companyName, startLevel, val, maxClearance, diff) {
@@ -159,7 +159,7 @@ function nextInfiltrationLevel(inst) {
bribeButton.style.display = "none";
escapeButton.style.display = "none";
- var rand = getRandomInt(0, 5); //This needs to change if more scenarios are added
+ var rand = getRandomInt(0, 5); // This needs to change if more scenarios are added
var scenario = null;
switch (rand) {
case 1:
@@ -442,7 +442,7 @@ function nextInfiltrationLevel(inst) {
function endInfiltrationLevel(inst) {
- //Check if you gained any secrets
+ // Check if you gained any secrets
if (inst.clearanceLevel % 5 == 0) {
var baseSecretValue = inst.baseValue * inst.clearanceLevel / 2;
var secretValue = baseSecretValue * Player.faction_rep_mult *
@@ -456,12 +456,12 @@ function endInfiltrationLevel(inst) {
"could be given to factions for reputation (" + formatNumber(secretValue, 3) + " rep )");
}
- //Increase security level based on difficulty
+ // Increase security level based on difficulty
inst.securityLevel *= (1 + (inst.difficulty / 100));
writeInfiltrationStatusText("You move on to the facility's next clearance level. This " +
"clearance level has " + inst.difficulty + "% higher security");
- //If this is max level, force endInfiltration
+ // If this is max level, force endInfiltration
if (inst.clearanceLevel >= inst.maxClearanceLevel) {
endInfiltration(inst, true);
} else {
@@ -629,8 +629,8 @@ function updateInfiltrationButtons(inst, scenario) {
let intWgt = CONSTANTS.IntelligenceInfiltrationWeight;
-//Kill
-//Success: 5%, Failure 10%, -Karma
+// Kill
+// Success: 5%, Failure 10%, -Karma
function attemptInfiltrationKill(inst) {
var chance = getInfiltrationKillChance(inst);
inst.gainStrengthExp(inst.securityLevel / 75) * Player.strength_exp_mult;
@@ -655,8 +655,8 @@ function getInfiltrationKillChance(inst) {
}
-//Knockout
-//Success: 3%, Failure: 10%
+// Knockout
+// Success: 3%, Failure: 10%
function attemptInfiltrationKnockout(inst) {
var chance = getInfiltrationKnockoutChance(inst);
inst.gainStrengthExp(inst.securityLevel / 70) * Player.strength_exp_mult;
@@ -680,8 +680,8 @@ function getInfiltrationKnockoutChance(inst) {
Player.agility) / (1.7 * lvl));
}
-//Stealth knockout
-//Success: 0%, Failure: 10%
+// Stealth knockout
+// Success: 0%, Failure: 10%
function attemptInfiltrationStealthKnockout(inst) {
var chance = getInfiltrationStealthKnockoutChance(inst);
inst.gainStrengthExp(inst.securityLevel / 75) * Player.strength_exp_mult;
@@ -704,8 +704,8 @@ function getInfiltrationStealthKnockoutChance(inst) {
intWgt * Player.intelligence) / (3 * lvl));
}
-//Assassination
-//Success: 0%, Failure: 5%, -Karma
+// Assassination
+// Success: 0%, Failure: 5%, -Karma
function attemptInfiltrationAssassinate(inst) {
var chance = getInfiltrationAssassinateChance(inst);
inst.gainStrengthExp(inst.securityLevel / 75) * Player.strength_exp_mult;
@@ -728,8 +728,8 @@ function getInfiltrationAssassinateChance(inst) {
}
-//Destroy security
-//Success: 5%, Failure: 10%
+// Destroy security
+// Success: 5%, Failure: 10%
function attemptInfiltrationDestroySecurity(inst) {
var chance = getInfiltrationDestroySecurityChance(inst);
inst.gainStrengthExp(inst.securityLevel / 75) * Player.strength_exp_mult;
@@ -755,8 +755,8 @@ function getInfiltrationDestroySecurityChance(inst) {
}
-//Hack security
-//Success: 3%, Failure: 5%
+// Hack security
+// Success: 3%, Failure: 5%
function attemptInfiltrationHack(inst) {
var chance = getInfiltrationHackChance(inst);
inst.gainHackingExp(inst.securityLevel / 30) * Player.hacking_exp_mult;
@@ -778,8 +778,8 @@ function getInfiltrationHackChance(inst) {
(intWgt * Player.intelligence)) / lvl);
}
-//Sneak past security
-//Success: 0%, Failure: 8%
+// Sneak past security
+// Success: 0%, Failure: 8%
function attemptInfiltrationSneak(inst) {
var chance = getInfiltrationSneakChance(inst);
inst.gainAgilityExp(inst.securityLevel / 30) * Player.agility_exp_mult;
@@ -799,8 +799,8 @@ function getInfiltrationSneakChance(inst) {
intWgt * Player.intelligence) / (2 * lvl));
}
-//Pick locked door
-//Success: 1%, Failure: 3%
+// Pick locked door
+// Success: 1%, Failure: 3%
function attemptInfiltrationPickLockedDoor(inst) {
var chance = getInfiltrationPickLockedDoorChance(inst);
inst.gainDexterityExp(inst.securityLevel / 25) * Player.dexterity_exp_mult;
@@ -820,8 +820,8 @@ function getInfiltrationPickLockedDoorChance(inst) {
intWgt * Player.intelligence) / lvl);
}
-//Bribe
-//Success: 0%, Failure: 15%,
+// Bribe
+// Success: 0%, Failure: 15%,
function attemptInfiltrationBribe(inst) {
var chance = getInfiltrationBribeChance(inst);
inst.gainCharismaExp(inst.securityLevel / 8) * Player.charisma_exp_mult;
@@ -839,8 +839,8 @@ function getInfiltrationBribeChance(inst) {
(Player.charisma) / lvl);
}
-//Escape
-//Failure: 5%
+// Escape
+// Failure: 5%
function attemptInfiltrationEscape(inst) {
var chance = getInfiltrationEscapeChance(inst);
inst.gainAgilityExp(inst.securityLevel / 30) * Player.agility_exp_mult;
diff --git a/src/InteractiveTutorial.js b/src/InteractiveTutorial.js
index 81f2c0bb6..3899d0683 100644
--- a/src/InteractiveTutorial.js
+++ b/src/InteractiveTutorial.js
@@ -11,27 +11,27 @@ import { createPopup } from "../utils/uiHelpers/createPopup";
import { removeElementById } from "../utils/uiHelpers/removeElementById";
-//Ordered array of keys to Interactive Tutorial Steps
+// Ordered array of keys to Interactive Tutorial Steps
const orderedITutorialSteps = [
"Start",
- "GoToCharacterPage", //Click on 'Stats' page
- "CharacterPage", //Introduction to 'Stats' page
- "CharacterGoToTerminalPage", //Go back to Terminal
- "TerminalIntro", //Introduction to Terminal
- "TerminalHelp", //Using 'help' Terminal command
- "TerminalLs", //Using 'ls' Terminal command
- "TerminalScan", //Using 'scan' Terminal command
- "TerminalScanAnalyze1", //Using 'scan-analyze' Terminal command
- "TerminalScanAnalyze2", //Using 'scan-analyze 3' Terminal command
- "TerminalConnect", //Connecting to foodnstuff
- "TerminalAnalyze", //Analyzing foodnstuff
- "TerminalNuke", //NUKE foodnstuff
- "TerminalManualHack", //Hack foodnstuff
- "TerminalHackingMechanics", //Explanation of hacking mechanics
- "TerminalCreateScript", //Create a script using 'nano'
- "TerminalTypeScript", //Script Editor page - Type script and then save & close
- "TerminalFree", //Using 'Free' Terminal command
- "TerminalRunScript", //Running script using 'run' Terminal command
+ "GoToCharacterPage", // Click on 'Stats' page
+ "CharacterPage", // Introduction to 'Stats' page
+ "CharacterGoToTerminalPage", // Go back to Terminal
+ "TerminalIntro", // Introduction to Terminal
+ "TerminalHelp", // Using 'help' Terminal command
+ "TerminalLs", // Using 'ls' Terminal command
+ "TerminalScan", // Using 'scan' Terminal command
+ "TerminalScanAnalyze1", // Using 'scan-analyze' Terminal command
+ "TerminalScanAnalyze2", // Using 'scan-analyze 3' Terminal command
+ "TerminalConnect", // Connecting to foodnstuff
+ "TerminalAnalyze", // Analyzing foodnstuff
+ "TerminalNuke", // NUKE foodnstuff
+ "TerminalManualHack", // Hack foodnstuff
+ "TerminalHackingMechanics", // Explanation of hacking mechanics
+ "TerminalCreateScript", // Create a script using 'nano'
+ "TerminalTypeScript", // Script Editor page - Type script and then save & close
+ "TerminalFree", // Using 'Free' Terminal command
+ "TerminalRunScript", // Running script using 'run' Terminal command
"TerminalGoToActiveScriptsPage",
"ActiveScriptsPage",
"ActiveScriptsToTerminal",
@@ -44,22 +44,22 @@ const orderedITutorialSteps = [
"End"
]
-//Create an 'enum' for the Steps
+// Create an 'enum' for the Steps
const iTutorialSteps = {};
for (let i = 0; i < orderedITutorialSteps.length; ++i) {
iTutorialSteps[orderedITutorialSteps[i]] = i;
}
var ITutorial = {
- currStep: 0, //iTutorialSteps.Start
+ currStep: 0, // iTutorialSteps.Start
isRunning: false,
- //Keeps track of whether each step has been done
+ // Keeps track of whether each step has been done
stepIsDone: {},
}
function iTutorialStart() {
- //Initialize Interactive Tutorial state by settings 'done' for each state to false
+ // Initialize Interactive Tutorial state by settings 'done' for each state to false
ITutorial.stepIsDone = {};
for (let i = 0; i < orderedITutorialSteps.length; ++i) {
ITutorial.stepIsDone[i] = false;
@@ -67,7 +67,7 @@ function iTutorialStart() {
Engine.loadTerminalContent();
- //Don't autosave during this interactive tutorial
+ // Don't autosave during this interactive tutorial
Engine.Counters.autoSaveCounter = Infinity;
console.log("Interactive Tutorial started");
ITutorial.currStep = 0;
@@ -75,21 +75,21 @@ function iTutorialStart() {
document.getElementById("interactive-tutorial-container").style.display = "block";
- //Exit tutorial button
+ // Exit tutorial button
var exitButton = clearEventListeners("interactive-tutorial-exit");
exitButton.addEventListener("click", function() {
iTutorialEnd();
return false;
});
- //Back button
+ // Back button
var backButton = clearEventListeners("interactive-tutorial-back");
backButton.addEventListener("click", function() {
iTutorialPrevStep();
return false;
});
- //Next button
+ // Next button
var nextButton = clearEventListeners("interactive-tutorial-next");
nextButton.addEventListener("click", function() {
iTutorialNextStep();
@@ -102,7 +102,7 @@ function iTutorialStart() {
function iTutorialEvaluateStep() {
if (!ITutorial.isRunning) {console.log("Interactive Tutorial not running"); return;}
- //Disable and clear main menu
+ // Disable and clear main menu
var terminalMainMenu = clearEventListeners("terminal-menu-link");
var statsMainMenu = clearEventListeners("stats-menu-link");
var activeScriptsMainMenu = clearEventListeners("active-scripts-menu-link");
@@ -116,7 +116,7 @@ function iTutorialEvaluateStep() {
cityMainMenu.removeAttribute("class");
tutorialMainMenu.removeAttribute("class");
- //Interactive Tutorial Next button
+ // Interactive Tutorial Next button
var nextBtn = document.getElementById("interactive-tutorial-next");
switch(ITutorial.currStep) {
@@ -134,7 +134,7 @@ function iTutorialEvaluateStep() {
"the main navigation menu (left-hand side of the screen)");
nextBtn.style.display = "none";
- //Flash 'Stats' menu and set its tutorial click handler
+ // Flash 'Stats' menu and set its tutorial click handler
statsMainMenu.setAttribute("class", "flashing-button");
statsMainMenu.addEventListener("click", function() {
Engine.loadCharacterContent();
@@ -154,7 +154,7 @@ function iTutorialEvaluateStep() {
"main navigation menu.");
nextBtn.style.display = "none";
- //Flash 'Terminal' menu and set its tutorial click handler
+ // Flash 'Terminal' menu and set its tutorial click handler
terminalMainMenu.setAttribute("class", "flashing-button");
terminalMainMenu.addEventListener("click", function() {
Engine.loadTerminalContent();
@@ -172,13 +172,13 @@ function iTutorialEvaluateStep() {
Engine.loadTerminalContent();
iTutorialSetText("Let's try it out. Start by entering the 'help' command into the Terminal " +
"(Don't forget to press Enter after typing the command)");
- nextBtn.style.display = "none"; //next step triggered by terminal command
+ nextBtn.style.display = "none"; // next step triggered by terminal command
break;
case iTutorialSteps.TerminalLs:
Engine.loadTerminalContent();
iTutorialSetText("The 'help' command displays a list of all available Terminal commands, how to use them, " +
"and a description of what they do. Let's try another command. Enter the 'ls' command");
- nextBtn.style.display = "none"; //next step triggered by terminal command
+ nextBtn.style.display = "none"; // next step triggered by terminal command
break;
case iTutorialSteps.TerminalScan:
Engine.loadTerminalContent();
@@ -187,7 +187,7 @@ function iTutorialEvaluateStep() {
"We'll get to what this does later. Using your home computer's terminal, you can connect " +
"to other machines throughout the world. Let's do that now by first entering " +
"the 'scan' command.");
- nextBtn.style.display = "none"; //next step triggered by terminal command
+ nextBtn.style.display = "none"; // next step triggered by terminal command
break;
case iTutorialSteps.TerminalScanAnalyze1:
Engine.loadTerminalContent();
@@ -197,7 +197,7 @@ function iTutorialEvaluateStep() {
"That's great and all, but there's so many servers. Which one should you go to? " +
"The 'scan-analyze' command gives some more detailed information about servers on the " +
"network. Try it now");
- nextBtn.style.display = "none"; //next step triggered by terminal command
+ nextBtn.style.display = "none"; // next step triggered by terminal command
break;
case iTutorialSteps.TerminalScanAnalyze2:
Engine.loadTerminalContent();
@@ -205,7 +205,7 @@ function iTutorialEvaluateStep() {
"information about each server that you can connect to (servers that are a distance of " +
"one node away). It is also possible to run 'scan-analyze' with " +
"a higher depth. Let's try a depth of two with the following command: 'scan-analyze 2'.")
- nextBtn.style.display = "none"; //next step triggered by terminal command
+ nextBtn.style.display = "none"; // next step triggered by terminal command
break;
case iTutorialSteps.TerminalConnect:
Engine.loadTerminalContent();
@@ -215,7 +215,7 @@ function iTutorialEvaluateStep() {
"the ip or the hostname, but dont use both. " +
"From the results of the 'scan-analyze' command, we can see that the 'foodnstuff' server is " +
"only one node away. Let's connect so it now using: 'connect foodnstuff'");
- nextBtn.style.display = "none"; //next step triggered by terminal command
+ nextBtn.style.display = "none"; // next step triggered by terminal command
break;
case iTutorialSteps.TerminalAnalyze:
Engine.loadTerminalContent();
@@ -224,7 +224,7 @@ function iTutorialEvaluateStep() {
"on servers and computers. Using your hacking abilities, you can hack servers " +
"to steal money and gain experience. " +
"Before you try to hack a server, you should run diagnostics using the 'analyze' command");
- nextBtn.style.display = "none"; //next step triggered by terminal command
+ nextBtn.style.display = "none"; // next step triggered by terminal command
break;
case iTutorialSteps.TerminalNuke:
Engine.loadTerminalContent();
@@ -236,13 +236,13 @@ function iTutorialEvaluateStep() {
"open ports. The 'analyze' results shows that there do not need to be any open ports " +
"on this machine for the NUKE virus to work, so go ahead and run the virus using the " +
"'run NUKE.exe' command.");
- nextBtn.style.display = "none"; //next step triggered by terminal command
+ nextBtn.style.display = "none"; // next step triggered by terminal command
break;
case iTutorialSteps.TerminalManualHack:
Engine.loadTerminalContent();
iTutorialSetText("You now have root access! You can hack the server using the 'hack' command. " +
"Try doing that now.");
- nextBtn.style.display = "none"; //next step triggered by terminal command
+ nextBtn.style.display = "none"; // next step triggered by terminal command
break;
case iTutorialSteps.TerminalHackingMechanics:
Engine.loadTerminalContent();
@@ -265,7 +265,7 @@ function iTutorialEvaluateStep() {
"command. Scripts must end with the '.script' extension. Let's make a script now by " +
"entering 'nano foodnstuff.script' after the hack command finishes running (Sidenote: Pressing ctrl + c" +
" will end a command like hack early)");
- nextBtn.style.display = "none"; //next step triggered by terminal command
+ nextBtn.style.display = "none"; // next step triggered by terminal command
break;
case iTutorialSteps.TerminalTypeScript:
Engine.loadScriptEditorContent("foodnstuff.script", "");
@@ -281,7 +281,7 @@ function iTutorialEvaluateStep() {
"For anyone with basic programming experience, this code should be straightforward. " +
"This script will continuously hack the 'foodnstuff' server. " +
"To save and close the script editor, press the button in the bottom left, or press ctrl + b.");
- nextBtn.style.display = "none"; //next step triggered in saveAndCloseScriptEditor() (Script.js)
+ nextBtn.style.display = "none"; // next step triggered in saveAndCloseScriptEditor() (Script.js)
break;
case iTutorialSteps.TerminalFree:
Engine.loadTerminalContent();
@@ -289,13 +289,13 @@ function iTutorialEvaluateStep() {
"run on any machine which you have root access to. Different servers have different " +
"amounts of RAM. You can also purchase more RAM for your home server. To check how much " +
"RAM is available on this machine, enter the 'free' command.");
- nextBtn.style.display = "none"; //next step triggered by terminal commmand
+ nextBtn.style.display = "none"; // next step triggered by terminal commmand
break;
case iTutorialSteps.TerminalRunScript:
Engine.loadTerminalContent();
iTutorialSetText("We have 16GB of free RAM on this machine, which is enough to run our " +
"script. Let's run our script using 'run foodnstuff.script'.");
- nextBtn.style.display = "none"; //next step triggered by terminal commmand
+ nextBtn.style.display = "none"; // next step triggered by terminal commmand
break;
case iTutorialSteps.TerminalGoToActiveScriptsPage:
Engine.loadTerminalContent();
@@ -309,7 +309,7 @@ function iTutorialEvaluateStep() {
"'Active Scripts' link in the main navigation menu.");
nextBtn.style.display = "none";
- //Flash 'Active Scripts' menu and set its tutorial click handler
+ // Flash 'Active Scripts' menu and set its tutorial click handler
activeScriptsMainMenu.setAttribute("class", "flashing-button");
activeScriptsMainMenu.addEventListener("click", function() {
Engine.loadActiveScriptsContent();
@@ -325,7 +325,7 @@ function iTutorialEvaluateStep() {
"link.");
nextBtn.style.display = "none";
- //Flash 'Terminal' button and set its tutorial click handler
+ // Flash 'Terminal' button and set its tutorial click handler
terminalMainMenu.setAttribute("class", "flashing-button");
terminalMainMenu.addEventListener("click", function() {
Engine.loadTerminalContent();
@@ -338,7 +338,7 @@ function iTutorialEvaluateStep() {
iTutorialSetText("One last thing about scripts, each active script contains logs that detail " +
"what it's doing. We can check these logs using the 'tail' command. Do that " +
"now for the script we just ran by typing 'tail foodnstuff.script'");
- nextBtn.style.display = "none"; //next step triggered by terminal command
+ nextBtn.style.display = "none"; // next step triggered by terminal command
break;
case iTutorialSteps.TerminalTailScript:
Engine.loadTerminalContent();
@@ -359,7 +359,7 @@ function iTutorialEvaluateStep() {
"the 'Hacknet Nodes' page through the main navigation menu now.");
nextBtn.style.display = "none";
- //Flash 'Hacknet' menu and set its tutorial click handler
+ // Flash 'Hacknet' menu and set its tutorial click handler
hacknetMainMenu.setAttribute("class", "flashing-button");
hacknetMainMenu.addEventListener("click", function() {
Engine.loadHacknetNodesContent();
@@ -371,7 +371,7 @@ function iTutorialEvaluateStep() {
Engine.loadHacknetNodesContent();
iTutorialSetText("From this page you can purchase new Hacknet Nodes and upgrade your " +
"existing ones. Let's purchase a new one now.");
- nextBtn.style.display = "none"; //Next step triggered by purchaseHacknet() (HacknetNode.js)
+ nextBtn.style.display = "none"; // Next step triggered by purchaseHacknet() (HacknetNode.js)
break;
case iTutorialSteps.HacknetNodesGoToWorldPage:
Engine.loadHacknetNodesContent();
@@ -382,7 +382,7 @@ function iTutorialEvaluateStep() {
"Let's go to the 'City' page through the main navigation menu.");
nextBtn.style.display = "none";
- //Flash 'City' menu and set its tutorial click handler
+ // Flash 'City' menu and set its tutorial click handler
cityMainMenu.setAttribute("class", "flashing-button");
cityMainMenu.addEventListener("click", function() {
Engine.loadLocationContent();
@@ -399,7 +399,7 @@ function iTutorialEvaluateStep() {
"Lastly, click on the 'Tutorial' link in the main navigation menu.");
nextBtn.style.display = "none";
- //Flash 'Tutorial' menu and set its tutorial click handler
+ // Flash 'Tutorial' menu and set its tutorial click handler
tutorialMainMenu.setAttribute("class", "flashing-button");
tutorialMainMenu.addEventListener("click", function() {
Engine.loadTutorialContent();
@@ -428,9 +428,9 @@ function iTutorialEvaluateStep() {
}
}
-//Go to the next step and evaluate it
+// Go to the next step and evaluate it
function iTutorialNextStep() {
- //Special behavior for certain steps
+ // Special behavior for certain steps
if (ITutorial.currStep === iTutorialSteps.GoToCharacterPage) {
document.getElementById("stats-menu-link").removeAttribute("class");
}
@@ -460,7 +460,7 @@ function iTutorialNextStep() {
iTutorialEvaluateStep();
}
-//Go to previous step and evaluate
+// Go to previous step and evaluate
function iTutorialPrevStep() {
if (ITutorial.currStep > iTutorialSteps.Start) {
ITutorial.currStep -= 1;
@@ -469,7 +469,7 @@ function iTutorialPrevStep() {
}
function iTutorialEnd() {
- //Re-enable auto save
+ // Re-enable auto save
if (Settings.AutosaveInterval === 0) {
Engine.Counters.autoSaveCounter = Infinity;
} else {
@@ -494,7 +494,7 @@ function iTutorialEnd() {
ITutorial.isRunning = false;
document.getElementById("interactive-tutorial-container").style.display = "none";
- //Create a popup with final introductory stuff
+ // Create a popup with final introductory stuff
var popupId = "interactive-tutorial-ending-popup";
var txt = createElement("p", {
innerHTML:
diff --git a/src/Literature.js b/src/Literature.js
index 0bc10e109..f5354a1e2 100644
--- a/src/Literature.js
+++ b/src/Literature.js
@@ -1,8 +1,9 @@
+/**
+ * Lore / world building literature files that can be found on servers.
+ * These files can be read by the player
+ */
import { dialogBoxCreate } from "../utils/DialogBox";
-/* Literature.js
- * Lore / world building literature that can be found on servers
- */
function Literature(title, filename, txt) {
this.title = title;
this.fn = filename;
@@ -10,10 +11,9 @@ function Literature(title, filename, txt) {
}
function showLiterature(fn) {
- var litObj = Literatures[fn];
- if (litObj == null) {return;}
- var txt = "" + litObj.title + " " +
- litObj.txt;
+ const litObj = Literatures[fn];
+ if (litObj == null) { return; }
+ const txt = `${litObj.title} ${litObj.txt}`;
dialogBoxCreate(txt);
}
@@ -430,7 +430,10 @@ function initLiterature() {
fn = "the-secret-war.lit";
txt = ""
Literatures[fn] = new Literature(title, fn, txt);
-
}
-export {Literatures, initLiterature, showLiterature};
+export {
+ Literatures,
+ initLiterature,
+ showLiterature
+};
diff --git a/src/Missions.js b/src/Missions.js
index 8a446b523..36c906146 100644
--- a/src/Missions.js
+++ b/src/Missions.js
@@ -15,7 +15,7 @@ import { clearEventListeners } from "../utils/uiHelpers/clearEventListeners";
import jsplumb from "jsplumb";
-let inMission = false; //Flag to denote whether a mission is running
+let inMission = false; // Flag to denote whether a mission is running
let currMission = null;
function setInMission(bool, mission) {
inMission = bool;
@@ -26,26 +26,26 @@ function setInMission(bool, mission) {
}
}
-//Keyboard shortcuts
+// Keyboard shortcuts
$(document).keydown(function(e) {
if (inMission && currMission && currMission.selectedNode.length != 0) {
switch (e.keyCode) {
- case 65: //a for Attack
+ case 65: // a for Attack
currMission.actionButtons[0].click();
break;
- case 83: //s for Scan
+ case 83: // s for Scan
currMission.actionButtons[1].click();
break;
- case 87: //w for Weaken
+ case 87: // w for Weaken
currMission.actionButtons[2].click();
break;
- case 70: //f for Fortify
+ case 70: // f for Fortify
currMission.actionButtons[3].click();
break;
- case 82: //r for Overflow
+ case 82: // r for Overflow
currMission.actionButtons[4].click();
break;
- case 68: //d for Detach connection
+ case 68: // d for Detach connection
currMission.actionButtons[5].click();
break;
default:
@@ -55,20 +55,20 @@ $(document).keydown(function(e) {
});
let NodeTypes = {
- Core: "CPU Core Node", //All actions available
- Firewall: "Firewall Node", //No actions available
- Database: "Database Node", //No actions available
- Spam: "Spam Node", //No actions Available
- Transfer: "Transfer Node", //Can Weaken, Scan, Fortify and Overflow
- Shield: "Shield Node" //Can Fortify
+ Core: "CPU Core Node", // All actions available
+ Firewall: "Firewall Node", // No actions available
+ Database: "Database Node", // No actions available
+ Spam: "Spam Node", // No actions Available
+ Transfer: "Transfer Node", // Can Weaken, Scan, Fortify and Overflow
+ Shield: "Shield Node" // Can Fortify
}
let NodeActions = {
- Attack: "Attacking", //Damaged based on attack stat + hacking level + opp def
- Scan: "Scanning", //-Def for target, affected by attack and hacking level
- Weaken: "Weakening", //-Attack for target, affected by attack and hacking level
- Fortify: "Fortifying", //+Defense for Node, affected by hacking level
- Overflow: "Overflowing", //+Attack but -Defense for Node, affected by hacking level
+ Attack: "Attacking", // Damaged based on attack stat + hacking level + opp def
+ Scan: "Scanning", // -Def for target, affected by attack and hacking level
+ Weaken: "Weakening", // -Attack for target, affected by attack and hacking level
+ Fortify: "Fortifying", // +Defense for Node, affected by hacking level
+ Overflow: "Overflowing", // +Attack but -Defense for Node, affected by hacking level
}
function Node(type, stats) {
@@ -79,14 +79,15 @@ function Node(type, stats) {
this.maxhp = this.hp;
this.plyrCtrl = false;
this.enmyCtrl = false;
- this.pos = [0, 0]; //x, y
- this.el = null; //Holds the Node's DOM element
+ this.pos = [0, 0]; // x, y
+ this.el = null; // Holds the Node's DOM element
this.action = null;
- this.targetedCount = 0; //Count of how many connections this node is the target of
+ this.targetedCount = 0; // Count of how many connections this node is the target of
- //Holds the JsPlumb Connection object for this Node,
- //where this Node is the Source (since each Node
- //can only have 1 outgoing Connection)
+ /**
+ * Holds the JsPlumb Connection object for this Node, where this Node is the Source (since each Node
+ * can only have 1 outgoing Connection)
+ */
this.conn = null;
}
@@ -112,12 +113,12 @@ Node.prototype.setControlledByEnemy = function() {
}
}
-//Sets this node to be the active node
+// Sets this node to be the active node
Node.prototype.select = function(actionButtons) {
if (this.enmyCtrl) {return;}
this.el.classList.add("hack-mission-player-node-active");
- //Make all buttons inactive
+ // Make all buttons inactive
for (var i = 0; i < actionButtons.length; ++i) {
actionButtons[i].classList.remove("a-link-button");
actionButtons[i].classList.add("a-link-button-inactive");
@@ -125,7 +126,7 @@ Node.prototype.select = function(actionButtons) {
switch(this.type) {
case NodeTypes.Core:
- //All buttons active
+ // All buttons active
for (var i = 0; i < actionButtons.length; ++i) {
actionButtons[i].classList.remove("a-link-button-inactive");
actionButtons[i].classList.add("a-link-button");
@@ -170,31 +171,33 @@ Node.prototype.untarget = function() {
--this.targetedCount;
}
-//Hacking mission instance
-//Takes in the reputation of the Faction for which the mission is
-//being conducted
+/**
+ * Hacking mission instance
+ * @param rep {number} How much reputation the player has for the faction
+ * @param fac {Faction} Faction for which this mission is being conducted
+ */
function HackingMission(rep, fac) {
this.faction = fac;
this.started = false;
- this.time = 180000; //5 minutes to start, milliseconds
+ this.time = 180000; // 5 minutes to start, milliseconds
this.playerCores = [];
- this.playerNodes = []; //Non-core nodes
+ this.playerNodes = []; // Non-core nodes
this.playerAtk = 0;
this.playerDef = 0;
this.enemyCores = [];
this.enemyDatabases = [];
- this.enemyNodes = []; //Non-core nodes
+ this.enemyNodes = []; // Non-core nodes
this.enemyAtk = 0;
this.enemyDef = 0;
this.miscNodes = [];
- this.selectedNode = []; //Which of the player's nodes are currently selected
+ this.selectedNode = []; // Which of the player's nodes are currently selected
- this.actionButtons = []; //DOM buttons for actions
+ this.actionButtons = []; // DOM buttons for actions
this.availablePositions = [];
for (var r = 0; r < 8; ++r) {
@@ -216,10 +219,10 @@ function HackingMission(rep, fac) {
}
HackingMission.prototype.init = function() {
- //Create Header DOM
+ // Create Header DOM
this.createPageDom();
- //Create player starting nodes
+ // Create player starting nodes
var home = Player.getHomeComputer()
for (var i = 0; i < home.cpuCores; ++i) {
var stats = {
@@ -233,7 +236,7 @@ HackingMission.prototype.init = function() {
this.removeAvailablePosition(i, 0);
}
- //Randomly generate enemy nodes (CPU and Firewall) based on difficulty
+ // Randomly generate enemy nodes (CPU and Firewall) based on difficulty
var numNodes = Math.min(8, Math.max(1, Math.round(this.difficulty / 4)));
var numFirewalls = Math.min(20,
getRandomInt(Math.round(this.difficulty/3), Math.round(this.difficulty/3) + 1));
@@ -309,10 +312,10 @@ HackingMission.prototype.createPageDom = function() {
wikiGuideBtn.style.display = "inline-block";
wikiGuideBtn.classList.add("hack-mission-header-element");
wikiGuideBtn.target = "_blank";
- //TODO Add link to wiki page wikiGuideBtn.href =
+ // TODO Add link to wiki page wikiGuideBtn.href =
- //Start button will get replaced with forfeit when game is started
+ // Start button will get replaced with forfeit when game is started
var startBtn = document.createElement("a");
startBtn.innerHTML = "Start";
startBtn.setAttribute("id", "hack-mission-start-btn");
@@ -339,15 +342,15 @@ HackingMission.prototype.createPageDom = function() {
timer.style.display = "inline-block";
timer.style.margin = "6px";
- //Create Action Buttons (Attack/Scan/Weaken/ etc...)
+ // Create Action Buttons (Attack/Scan/Weaken/ etc...)
var actionsContainer = document.createElement("span");
actionsContainer.style.display = "block";
actionsContainer.classList.add("hack-mission-action-buttons-container");
for (var i = 0; i < 6; ++i) {
this.actionButtons.push(document.createElement("a"));
this.actionButtons[i].style.display = "inline-block";
- this.actionButtons[i].classList.add("a-link-button-inactive"); //Disabled at start
- this.actionButtons[i].classList.add("tooltip"); //Disabled at start
+ this.actionButtons[i].classList.add("a-link-button-inactive"); // Disabled at start
+ this.actionButtons[i].classList.add("tooltip"); // Disabled at start
this.actionButtons[i].classList.add("hack-mission-header-element");
actionsContainer.appendChild(this.actionButtons[i]);
}
@@ -388,7 +391,7 @@ HackingMission.prototype.createPageDom = function() {
"also be done by simply clicking the white connection line.";
this.actionButtons[5].appendChild(dropconnTooltip);
- //Player/enemy defense displays will be in action container
+ // Player/enemy defense displays will be in action container
var playerStats = document.createElement("p");
var enemyStats = document.createElement("p");
playerStats.style.display = "inline-block";
@@ -402,7 +405,7 @@ HackingMission.prototype.createPageDom = function() {
actionsContainer.appendChild(playerStats);
actionsContainer.appendChild(enemyStats);
- //Set Action Button event listeners
+ // Set Action Button event listeners
this.actionButtons[0].addEventListener("click", ()=>{
if (!(this.selectedNode.length > 0)) {
console.log("ERR: Pressing Action button without selected node");
@@ -410,7 +413,7 @@ HackingMission.prototype.createPageDom = function() {
}
if (this.selectedNode[0].type !== NodeTypes.Core) {return;}
this.setActionButtonsActive(this.selectedNode[0].type);
- this.setActionButton(NodeActions.Attack, false); //Set attack button inactive
+ this.setActionButton(NodeActions.Attack, false); // Set attack button inactive
this.selectedNode.forEach(function(node){
node.action = NodeActions.Attack;
});
@@ -421,10 +424,10 @@ HackingMission.prototype.createPageDom = function() {
console.log("ERR: Pressing Action button without selected node");
return;
}
- var nodeType = this.selectedNode[0].type; //In a multiselect, every Node will have the same type
+ var nodeType = this.selectedNode[0].type; // In a multiselect, every Node will have the same type
if (nodeType !== NodeTypes.Core && nodeType !== NodeTypes.Transfer) {return;}
this.setActionButtonsActive(nodeType);
- this.setActionButton(NodeActions.Scan, false); //Set scan button inactive
+ this.setActionButton(NodeActions.Scan, false); // Set scan button inactive
this.selectedNode.forEach(function(node){
node.action = NodeActions.Scan;
});
@@ -435,10 +438,10 @@ HackingMission.prototype.createPageDom = function() {
console.log("ERR: Pressing Action button without selected node");
return;
}
- var nodeType = this.selectedNode[0].type; //In a multiselect, every Node will have the same type
+ var nodeType = this.selectedNode[0].type; // In a multiselect, every Node will have the same type
if (nodeType !== NodeTypes.Core && nodeType !== NodeTypes.Transfer) {return;}
this.setActionButtonsActive(nodeType);
- this.setActionButton(NodeActions.Weaken, false); //Set Weaken button inactive
+ this.setActionButton(NodeActions.Weaken, false); // Set Weaken button inactive
this.selectedNode.forEach(function(node){
node.action = NodeActions.Weaken;
});
@@ -450,7 +453,7 @@ HackingMission.prototype.createPageDom = function() {
return;
}
this.setActionButtonsActive(this.selectedNode[0].type);
- this.setActionButton(NodeActions.Fortify, false); //Set Fortify button inactive
+ this.setActionButton(NodeActions.Fortify, false); // Set Fortify button inactive
this.selectedNode.forEach(function(node){
node.action = NodeActions.Fortify;
});
@@ -464,7 +467,7 @@ HackingMission.prototype.createPageDom = function() {
var nodeType = this.selectedNode[0].type;
if (nodeType !== NodeTypes.Core && nodeType !== NodeTypes.Transfer) {return;}
this.setActionButtonsActive(nodeType);
- this.setActionButton(NodeActions.Overflow, false); //Set Overflow button inactive
+ this.setActionButton(NodeActions.Overflow, false); // Set Overflow button inactive
this.selectedNode.forEach(function(node){
node.action = NodeActions.Overflow;
});
@@ -482,11 +485,7 @@ HackingMission.prototype.createPageDom = function() {
}
node.action = NodeActions.Fortify;
});
- // if (this.selectedNode.conn) {
- // var endpoints = this.selectedNode.conn.endpoints;
- // endpoints[0].detachFrom(endpoints[1]);
- // }
- })
+ });
var timeDisplay = document.createElement("p");
@@ -513,8 +512,10 @@ HackingMission.prototype.setActionButtonsActive = function(nodeType=null) {
this.actionButtons[i].classList.remove("a-link-button-inactive");
}
- //For Transfer, FireWall and Shield Nodes, certain buttons should always be disabled
- //0 = Attack, 1 = Scan, 2 = Weaken, 3 = Fortify, 4 = overflow, 5 = Drop conn
+ /**
+ * For Transfer, FireWall and Shield Nodes, certain buttons should always be disabled
+ * 0 = Attack, 1 = Scan, 2 = Weaken, 3 = Fortify, 4 = overflow, 5 = Drop conn
+ */
if (nodeType) {
switch (nodeType) {
case NodeTypes.Firewall:
@@ -540,7 +541,7 @@ HackingMission.prototype.setActionButtonsActive = function(nodeType=null) {
}
}
-//True for active, false for inactive
+// True for active, false for inactive
HackingMission.prototype.setActionButton = function(i, active=true) {
if (isString(i)) {
switch (i) {
@@ -657,7 +658,7 @@ HackingMission.prototype.setNodePosition = function(nodeObj, x, y) {
HackingMission.prototype.setNodeRandomPosition = function(nodeObj, xlimit=0) {
var i = getRandomInt(0, this.availablePositions.length - 1);
if (this.availablePositions[i][1] < xlimit) {
- //Recurse if not within limit
+ // Recurse if not within limit
return this.setNodeRandomPosition(nodeObj, xlimit);
}
var pos = this.availablePositions.splice(i, 1);
@@ -666,15 +667,15 @@ HackingMission.prototype.setNodeRandomPosition = function(nodeObj, xlimit=0) {
}
HackingMission.prototype.createMap = function() {
- //Use a grid
+ // Use a grid
var map = document.createElement("div");
map.classList.add("hack-mission-grid");
map.setAttribute("id", "hacking-mission-map");
document.getElementById("mission-container").appendChild(map);
- //Create random Nodes for every space in the map that
- //hasn't been filled yet. The stats of each Node will be based on
- //the player/enemy attack
+ // Create random Nodes for every space in the map that
+ // hasn't been filled yet. The stats of each Node will be based on
+ // the player/enemy attack
var averageAttack = (this.playerAtk + this.enemyAtk) / 2;
for (var x = 0; x < 8; ++x) {
for (var y = 0; y < 8; ++y) {
@@ -682,7 +683,7 @@ HackingMission.prototype.createMap = function() {
var node, type = getRandomInt(0, 2);
var randMult = addOffset(0.85 + (this.difficulty / 2), 15);
switch (type) {
- case 0: //Spam
+ case 0: // Spam
var stats = {
atk: 0,
def: averageAttack * 1.1 + getRandomInt(15, 45),
@@ -690,7 +691,7 @@ HackingMission.prototype.createMap = function() {
}
node = new Node(NodeTypes.Spam, stats);
break;
- case 1: //Transfer
+ case 1: // Transfer
var stats = {
atk: 0,
def: averageAttack * 1.1 + getRandomInt(15, 45),
@@ -698,7 +699,7 @@ HackingMission.prototype.createMap = function() {
}
node = new Node(NodeTypes.Transfer, stats);
break;
- case 2: //Shield
+ case 2: // Shield
default:
var stats = {
atk: 0,
@@ -715,14 +716,14 @@ HackingMission.prototype.createMap = function() {
}
}
- //Create DOM elements in order
+ // Create DOM elements in order
for (var r = 0; r < 8; ++r) {
for (var c = 0; c < 8; ++c) {
this.createNodeDomElement(this.map[r][c]);
}
}
- //Configure all Player CPUS
+ // Configure all Player CPUS
for (var i = 0; i < this.playerCores.length; ++i) {
console.log("Configuring Player Node: " + this.playerCores[i].el.id);
this.configurePlayerNodeElement(this.playerCores[i].el);
@@ -733,12 +734,12 @@ HackingMission.prototype.createNodeDomElement = function(nodeObj) {
var nodeDiv = document.createElement("a"), txtEl = document.createElement('p');
nodeObj.el = nodeDiv;
- //Set the node element's id based on its coordinates
+ // Set the node element's id based on its coordinates
var id = "hacking-mission-node-" + nodeObj.pos[0] + "-" + nodeObj.pos[1];
nodeDiv.setAttribute("id", id);
txtEl.setAttribute("id", id + "-txt");
- //Set node classes for owner
+ // Set node classes for owner
nodeDiv.classList.add("hack-mission-node");
if (nodeObj.plyrCtrl) {
nodeDiv.classList.add("hack-mission-player-node");
@@ -746,7 +747,7 @@ HackingMission.prototype.createNodeDomElement = function(nodeObj) {
nodeDiv.classList.add("hack-mission-enemy-node");
}
- //Set node classes based on type
+ // Set node classes based on type
var txt;
switch (nodeObj.type) {
case NodeTypes.Core:
@@ -799,7 +800,7 @@ HackingMission.prototype.updateNodeDomElement = function(nodeObj) {
var id = "hacking-mission-node-" + nodeObj.pos[0] + "-" + nodeObj.pos[1];
var nodeDiv = document.getElementById(id), txtEl = document.getElementById(id + "-txt");
- //Set node classes based on type
+ // Set node classes based on type
var txt;
switch (nodeObj.type) {
case NodeTypes.Core:
@@ -837,9 +838,11 @@ HackingMission.prototype.updateNodeDomElement = function(nodeObj) {
txtEl.innerHTML = txt;
}
-//Gets a Node DOM element's corresponding Node object using its
-//element id. Function accepts either the DOM element object or the ID as
-//an argument
+/**
+ * Gets a Node DOM element's corresponding Node object using its
+ * element id. Function accepts either the DOM element object or the ID as
+ * an argument
+ */
HackingMission.prototype.getNodeFromElement = function(el) {
var id;
if (isString(el)) {
@@ -902,14 +905,16 @@ function clearAllSelectedNodes(hackMissionInst) {
}
}
-//Configures a DOM element representing a player-owned node to
-//be selectable and actionable
-//Note: Does NOT change its css class. This is handled by Node.setControlledBy...
+/**
+ * Configures a DOM element representing a player-owned node to
+ * be selectable and actionable.
+ * Note: Does NOT change its css class. This is handled by Node.setControlledBy...
+ */
HackingMission.prototype.configurePlayerNodeElement = function(el) {
var nodeObj = this.getNodeFromElement(el);
if (nodeObj == null) {console.log("Error getting Node object");}
- //Add event listener
+ // Add event listener
var self = this;
function selectNodeWrapper() {
selectNode(self, el);
@@ -927,10 +932,12 @@ HackingMission.prototype.configurePlayerNodeElement = function(el) {
}
}
-//Configures a DOM element representing an enemy-node by removing
-//any event listeners
+/**
+ * Configures a DOM element representing an enemy-node by removing
+ * any event listeners
+ */
HackingMission.prototype.configureEnemyNodeElement = function(el) {
- //Deselect node if it was the selected node
+ // Deselect node if it was the selected node
var nodeObj = this.getNodeFromElement(el);
for (var i = 0; i < this.selectedNode.length; ++i) {
if (this.selectedNode[i] == nodeObj) {
@@ -941,8 +948,10 @@ HackingMission.prototype.configureEnemyNodeElement = function(el) {
}
}
-//Returns bool indicating whether a node is reachable by player
-//by checking if any of the adjacent nodes are owned by the player
+/**
+ * Returns bool indicating whether a node is reachable by player
+ * by checking if any of the adjacent nodes are owned by the player
+ */
HackingMission.prototype.nodeReachable = function(node) {
var x = node.pos[0], y = node.pos[1];
if (x > 0 && this.map[x-1][y].plyrCtrl) {return true;}
@@ -985,7 +994,7 @@ HackingMission.prototype.initJsPlumb = function() {
this.jsplumbinstance = instance;
- //All player cores are sources
+ // All player cores are sources
for (var i = 0; i < this.playerCores.length; ++i) {
instance.makeSource(this.playerCores[i].el, {
deleteEndpointsOnEmpty:true,
@@ -995,7 +1004,7 @@ HackingMission.prototype.initJsPlumb = function() {
});
}
- //Everything else is a target
+ // Everything else is a target
for (var i = 0; i < this.enemyCores.length; ++i) {
instance.makeTarget(this.enemyCores[i].el, {
maxConnections:-1,
@@ -1025,7 +1034,7 @@ HackingMission.prototype.initJsPlumb = function() {
});
}
- //Clicking a connection drops it
+ // Clicking a connection drops it
instance.bind("click", (conn, originalEvent) => {
// Cannot drop enemy's connections
const sourceNode = this.getNodeFromElement(conn.source);
@@ -1035,15 +1044,15 @@ HackingMission.prototype.initJsPlumb = function() {
endpoints[0].detachFrom(endpoints[1]);
});
- //Connection events
+ // Connection events
instance.bind("connection", (info) => {
var targetNode = this.getNodeFromElement(info.target);
- //Do not detach for enemy nodes
+ // Do not detach for enemy nodes
var thisNode = this.getNodeFromElement(info.source);
if (thisNode.enmyCtrl) {return;}
- //If the node is not reachable, drop the connection
+ // If the node is not reachable, drop the connection
if (!this.nodeReachable(targetNode)) {
info.sourceEndpoint.detachFrom(info.targetEndpoint);
return;
@@ -1055,7 +1064,7 @@ HackingMission.prototype.initJsPlumb = function() {
++targetNode.targetedCount;
});
- //Detach Connection events
+ // Detach Connection events
instance.bind("connectionDetached", (info, originalEvent)=>{
var sourceNode = this.getNodeFromElement(info.source);
sourceNode.conn = null;
@@ -1065,7 +1074,7 @@ HackingMission.prototype.initJsPlumb = function() {
}
-//Drops all connections where the specified node is the source
+// Drops all connections where the specified node is the source
HackingMission.prototype.dropAllConnectionsFromNode = function(node) {
var allConns = this.jsplumbinstance.getAllConnections();
for (var i = allConns.length-1; i >= 0; --i) {
@@ -1075,7 +1084,7 @@ HackingMission.prototype.dropAllConnectionsFromNode = function(node) {
}
}
-//Drops all connections where the specified node is the target
+// Drops all connections where the specified node is the target
HackingMission.prototype.dropAllConnectionsToNode = function(node) {
var allConns = this.jsplumbinstance.getAllConnections();
for (var i = allConns.length-1; i >= 0; --i) {
@@ -1090,10 +1099,10 @@ var storedCycles = 0;
HackingMission.prototype.process = function(numCycles=1) {
if (!this.started) {return;}
storedCycles += numCycles;
- if (storedCycles < 2) {return;} //Only process every 3 cycles minimum
+ if (storedCycles < 2) {return;} // Only process every 3 cycles minimum
var res = false;
- //Process actions of all player nodes
+ // Process actions of all player nodes
this.playerCores.forEach((node)=>{
res |= this.processNode(node, storedCycles);
});
@@ -1106,7 +1115,7 @@ HackingMission.prototype.process = function(numCycles=1) {
}
});
- //Process actions of all enemy nodes
+ // Process actions of all enemy nodes
this.enemyCores.forEach((node)=>{
this.enemyAISelectAction(node);
res |= this.processNode(node, storedCycles);
@@ -1121,7 +1130,7 @@ HackingMission.prototype.process = function(numCycles=1) {
}
});
- //The hp of enemy databases increases slowly
+ // The hp of enemy databases increases slowly
this.enemyDatabases.forEach((node)=>{
node.maxhp += (0.1 * storedCycles);
node.hp += (0.1 * storedCycles);
@@ -1132,19 +1141,19 @@ HackingMission.prototype.process = function(numCycles=1) {
this.calculateDefenses();
}
- //Win if all enemy databases are conquered
+ // Win if all enemy databases are conquered
if (this.enemyDatabases.length === 0) {
this.finishMission(true);
return;
}
- //Lose if all your cores are gone
+ // Lose if all your cores are gone
if (this.playerCores.length === 0) {
this.finishMission(false);
return;
}
- //Defense/hp of misc nodes increases slowly over time
+ // Defense/hp of misc nodes increases slowly over time
this.miscNodes.forEach((node)=>{
node.def += (0.1 * storedCycles);
node.maxhp += (0.05 * storedCycles);
@@ -1153,7 +1162,7 @@ HackingMission.prototype.process = function(numCycles=1) {
this.updateNodeDomElement(node);
});
- //Update timer and check if player lost
+ // Update timer and check if player lost
this.time -= (storedCycles * Engine._idleSpeed);
if (this.time <= 0) {
this.finishMission(false);
@@ -1164,7 +1173,7 @@ HackingMission.prototype.process = function(numCycles=1) {
storedCycles = 0;
}
-//Returns a bool representing whether defenses need to be re-calculated
+// Returns a bool representing whether defenses need to be re-calculated
HackingMission.prototype.processNode = function(nodeObj, numCycles=1) {
if (nodeObj.action == null) {
return;
@@ -1179,21 +1188,21 @@ HackingMission.prototype.processNode = function(nodeObj, numCycles=1) {
}
if (targetNode == null) {
- //Player is in the middle of dragging the connection,
- //so the target node is null. Do nothing here
+ // Player is in the middle of dragging the connection,
+ // so the target node is null. Do nothing here
} else if (targetNode.plyrCtrl) {
def = this.playerDef;
atk = this.enemyAtk;
} else if (targetNode.enmyCtrl) {
def = this.enemyDef;
atk = this.playerAtk;
- } else { //Misc Node
+ } else { // Misc Node
def = targetNode.def;
nodeObj.plyrCtrl ? atk = this.playerAtk : atk = this.enemyAtk;
}
}
- //Calculations are per second, so divide everything by 5
+ // Calculations are per second, so divide everything by 5
var calcStats = false, plyr = nodeObj.plyrCtrl;
var enmyHacking = this.difficulty * CONSTANTS.HackingMissionDifficultyToHacking;
switch(nodeObj.action) {
@@ -1234,13 +1243,13 @@ HackingMission.prototype.processNode = function(nodeObj, numCycles=1) {
break;
}
- //Stats can't go below 0
+ // Stats can't go below 0
if (nodeObj.atk < 0) {nodeObj.atk = 0;}
if (nodeObj.def < 0) {nodeObj.def = 0;}
if (targetNode && targetNode.atk < 0) {targetNode.atk = 0;}
if (targetNode && targetNode.def < 0) {targetNode.def = 0;}
- //Conquering a node
+ // Conquering a node
if (targetNode && targetNode.hp <= 0) {
var conqueredByPlayer = nodeObj.plyrCtrl;
targetNode.hp = targetNode.maxhp;
@@ -1250,18 +1259,18 @@ HackingMission.prototype.processNode = function(nodeObj, numCycles=1) {
targetNode.deselect(this.actionButtons);
}
- //The conquered node has its stats reduced
+ // The conquered node has its stats reduced
targetNode.atk /= 2;
targetNode.def /= 3.5;
- //Flag for whether the target node was a misc node
+ // Flag for whether the target node was a misc node
var isMiscNode = !targetNode.plyrCtrl && !targetNode.enmyCtrl;
- //Remove all connections from Node
+ // Remove all connections from Node
this.dropAllConnectionsToNode(targetNode);
this.dropAllConnectionsFromNode(targetNode);
- //Changes the css class and turn the node into a JsPlumb Source/Target
+ // Changes the css class and turn the node into a JsPlumb Source/Target
if (conqueredByPlayer) {
targetNode.setControlledByPlayer();
this.jsplumbinstance.unmakeTarget(targetNode.el);
@@ -1273,7 +1282,7 @@ HackingMission.prototype.processNode = function(nodeObj, numCycles=1) {
});
} else {
targetNode.setControlledByEnemy();
- nodeObj.conn = null; //Clear connection
+ nodeObj.conn = null; // Clear connection
this.jsplumbinstance.unmakeSource(targetNode.el);
this.jsplumbinstance.makeTarget(targetNode.el, {
maxConnections:-1,
@@ -1284,7 +1293,7 @@ HackingMission.prototype.processNode = function(nodeObj, numCycles=1) {
calcStats = true;
- //Helper function to swap nodes between the respective enemyNodes/playerNodes arrays
+ // Helper function to swap nodes between the respective enemyNodes/playerNodes arrays
function swapNodes(orig, dest, targetNode) {
for (var i = 0; i < orig.length; ++i) {
if (orig[i] == targetNode) {
@@ -1324,7 +1333,7 @@ HackingMission.prototype.processNode = function(nodeObj, numCycles=1) {
case NodeTypes.Spam:
if (conqueredByPlayer) {
swapNodes(isMiscNode ? this.miscNodes : this.enemyNodes, this.playerNodes, targetNode);
- //Conquering spam node increases time limit
+ // Conquering spam node increases time limit
this.time += CONSTANTS.HackingMissionSpamTimeIncrease;
} else {
swapNodes(isMiscNode ? this.miscNodes : this.playerNodes, this.enemyNodes, targetNode);
@@ -1332,7 +1341,7 @@ HackingMission.prototype.processNode = function(nodeObj, numCycles=1) {
break;
case NodeTypes.Transfer:
- //Conquering a Transfer node increases the attack of all cores by some percentages
+ // Conquering a Transfer node increases the attack of all cores by some percentages
if (conqueredByPlayer) {
swapNodes(isMiscNode ? this.miscNodes : this.enemyNodes, this.playerNodes, targetNode);
this.playerCores.forEach(function(node) {
@@ -1358,7 +1367,7 @@ HackingMission.prototype.processNode = function(nodeObj, numCycles=1) {
break;
}
- //If a misc node was conquered, the defense for all misc nodes increases by some fixed amount
+ // If a misc node was conquered, the defense for all misc nodes increases by some fixed amount
if (isMiscNode) { //&& conqueredByPlayer) {
this.miscNodes.forEach((node)=>{
if (node.targetedCount === 0) {
@@ -1368,23 +1377,25 @@ HackingMission.prototype.processNode = function(nodeObj, numCycles=1) {
}
}
- //Update node DOMs
+ // Update node DOMs
this.updateNodeDomElement(nodeObj);
if (targetNode) {this.updateNodeDomElement(targetNode);}
return calcStats;
}
-//Enemy "AI" for CPU Core and Transfer Nodes
+// Enemy "AI" for CPU Core and Transfer Nodes
HackingMission.prototype.enemyAISelectAction = function(nodeObj) {
if (nodeObj == null) {return;}
switch(nodeObj.type) {
case NodeTypes.Core:
- //Select a single RANDOM target from miscNodes and player's Nodes
- //If it is reachable, it will target it. If not, no target will
- //be selected for now, and the next time process() gets called this will repeat
+ /**
+ * Select a single RANDOM target from miscNodes and player's Nodes
+ * If it is reachable, it will target it. If not, no target will
+ * be selected for now, and the next time process() gets called this will repeat
+ */
if (nodeObj.conn == null) {
if (this.miscNodes.length === 0) {
- //Randomly pick a player node and attack it if its reachable
+ // Randomly pick a player node and attack it if its reachable
var rand = getRandomInt(0, this.playerNodes.length-1);
var node;
if (this.playerNodes.length === 0) {
@@ -1393,23 +1404,23 @@ HackingMission.prototype.enemyAISelectAction = function(nodeObj) {
node = this.playerNodes[rand];
}
if (this.nodeReachableByEnemy(node)) {
- //Create connection
+ // Create connection
nodeObj.conn = this.jsplumbinstance.connect({
source:nodeObj.el,
target:node.el
});
++node.targetedCount;
} else {
- //Randomly pick a player core and attack it if its reachable
+ // Randomly pick a player core and attack it if its reachable
rand = getRandomInt(0, this.playerCores.length-1);
if (this.playerCores.length === 0) {
- return; //No Misc Nodes, no player Nodes, no Player cores. Player lost
+ return; // No Misc Nodes, no player Nodes, no Player cores. Player lost
} else {
node = this.playerCores[rand];
}
if (this.nodeReachableByEnemy(node)) {
- //Create connection
+ // Create connection
nodeObj.conn = this.jsplumbinstance.connect({
source:nodeObj.el,
target:node.el
@@ -1418,7 +1429,7 @@ HackingMission.prototype.enemyAISelectAction = function(nodeObj) {
}
}
} else {
- //Randomly pick a misc node and attack it if its reachable
+ // Randomly pick a misc node and attack it if its reachable
var rand = getRandomInt(0, this.miscNodes.length-1);
var node = this.miscNodes[rand];
if (this.nodeReachableByEnemy(node)) {
@@ -1430,10 +1441,10 @@ HackingMission.prototype.enemyAISelectAction = function(nodeObj) {
}
}
- //If no connection was made, set the Core to Fortify
+ // If no connection was made, set the Core to Fortify
nodeObj.action = NodeActions.Fortify;
} else {
- //If this node has a selected target
+ // If this node has a selected target
var targetNode;
if (nodeObj.conn.target) {
targetNode = this.getNodeFromElement(nodeObj.conn.target);
@@ -1458,7 +1469,7 @@ HackingMission.prototype.enemyAISelectAction = function(nodeObj) {
}
break;
case NodeTypes.Transfer:
- //Switch between fortifying and overflowing as necessary
+ // Switch between fortifying and overflowing as necessary
if (nodeObj.def < 125) {
nodeObj.action = NodeActions.Fortify;
} else {
@@ -1474,11 +1485,11 @@ HackingMission.prototype.enemyAISelectAction = function(nodeObj) {
}
}
-var hackEffWeightSelf = 130; //Weight for Node actions on self
-var hackEffWeightTarget = 25; //Weight for Node Actions against Target
-var hackEffWeightAttack = 80; //Weight for Attack action
+var hackEffWeightSelf = 130; // Weight for Node actions on self
+var hackEffWeightTarget = 25; // Weight for Node Actions against Target
+var hackEffWeightAttack = 80; // Weight for Attack action
-//Returns damage per cycle based on stats
+// Returns damage per cycle based on stats
HackingMission.prototype.calculateAttackDamage = function(atk, def, hacking = 0) {
return Math.max(0.55 * (atk + (hacking / hackEffWeightAttack) - def), 1);
}
@@ -1499,11 +1510,11 @@ HackingMission.prototype.calculateOverflowEffect = function(hacking=0) {
return 0.95 * hacking / hackEffWeightSelf;
}
-//Updates timer display
+// Updates timer display
HackingMission.prototype.updateTimer = function() {
var timer = document.getElementById("hacking-mission-timer");
- //Convert time remaining to a string of the form mm:ss
+ // Convert time remaining to a string of the form mm:ss
var seconds = Math.round(this.time / 1000);
var minutes = Math.trunc(seconds / 60);
seconds %= 60;
@@ -1511,7 +1522,7 @@ HackingMission.prototype.updateTimer = function() {
timer.innerText = "Time left: " + str;
}
-//The 'win' argument is a bool for whether or not the player won
+// The 'win' argument is a bool for whether or not the player won
HackingMission.prototype.finishMission = function(win) {
inMission = false;
currMission = null;
@@ -1530,13 +1541,13 @@ HackingMission.prototype.finishMission = function(win) {
dialogBoxCreate("Mission lost/forfeited! You did not gain any faction reputation.");
}
- //Clear mission container
+ // Clear mission container
var container = document.getElementById("mission-container");
while(container.firstChild) {
container.removeChild(container.firstChild);
}
- //Return to Faction page
+ // Return to Faction page
document.getElementById("mainmenu-container").style.visibility = "visible";
document.getElementById("character-overview-wrapper").style.visibility = "visible";
Engine.loadFactionContent();
diff --git a/src/NetscriptFunctions.js b/src/NetscriptFunctions.js
index fe9ca7c76..54a858bc6 100644
--- a/src/NetscriptFunctions.js
+++ b/src/NetscriptFunctions.js
@@ -134,13 +134,13 @@ import { createElement } from "../utils/uiHelpers/createElement";
import { createPopup } from "../utils/uiHelpers/createPopup";
import { removeElementById } from "../utils/uiHelpers/removeElementById";
-let hasCorporationSF = false; //Source-File 3
-let hasSingularitySF = false; //Source-File 4
-let hasAISF = false; //Source-File 5
-let hasBladeburnerSF = false; //Source-File 6
-let hasBladeburner2079SF = false; //Source-File 7
-let hasWallStreetSF = false; //Source-File 8
-let hasBn11SF = false; //Source-File 11
+let hasCorporationSF = false; // Source-File 3
+let hasSingularitySF = false; // Source-File 4
+let hasAISF = false; // Source-File 5
+let hasBladeburnerSF = false; // Source-File 6
+let hasBladeburner2079SF = false; // Source-File 7
+let hasWallStreetSF = false; // Source-File 8
+let hasBn11SF = false; // Source-File 11
let singularitySFLvl = 1;
let wallStreetSFLvl = 1;
@@ -216,7 +216,7 @@ var possibleLogs = {
setTerritoryWarfare: true,
}
-//Used to check and set flags for every Source File, despite the name of the function
+// Used to check and set flags for every Source File, despite the name of the function
function initSingularitySFFlags() {
for (var i = 0; i < Player.sourceFiles.length; ++i) {
if (Player.sourceFiles[i].n === 3) {hasCorporationSF = true;}
@@ -455,10 +455,10 @@ function NetscriptFunctions(workerScript) {
throw makeRuntimeRejectMsg(workerScript, "hack() error. Invalid IP or hostname passed in: " + ip + ". Stopping...");
}
- //Calculate the hacking time
- var hackingTime = calculateHackingTime(server); //This is in seconds
+ // Calculate the hacking time
+ var hackingTime = calculateHackingTime(server); // This is in seconds
- //No root access or skill level too low
+ // No root access or skill level too low
const canHack = netscriptCanHack(server, Player);
if (!canHack.res) {
workerScript.scriptRef.log(`ERROR: ${canHack.msg}`);
@@ -475,18 +475,17 @@ function NetscriptFunctions(workerScript) {
var rand = Math.random();
var expGainedOnSuccess = calculateHackingExpGain(server) * threads;
var expGainedOnFailure = (expGainedOnSuccess / 4);
- if (rand < hackChance) { //Success!
+ if (rand < hackChance) { // Success!
const percentHacked = calculatePercentMoneyHacked(server);
let maxThreadNeeded = Math.ceil(1/percentHacked*(server.moneyAvailable/server.moneyMax));
if (isNaN(maxThreadNeeded)) {
- //Server has a 'max money' of 0 (probably).
- //We'll set this to an arbitrarily large value
+ // Server has a 'max money' of 0 (probably). We'll set this to an arbitrarily large value
maxThreadNeeded = 1e6;
}
let moneyGained = Math.floor(server.moneyAvailable * percentHacked) * threads;
- //Over-the-top safety checks
+ // Over-the-top safety checks
if (moneyGained <= 0) {
moneyGained = 0;
expGainedOnSuccess = expGainedOnFailure;
@@ -508,7 +507,7 @@ function NetscriptFunctions(workerScript) {
server.fortify(CONSTANTS.ServerFortifyAmount * Math.min(threads, maxThreadNeeded));
return Promise.resolve(moneyGained);
} else {
- //Player only gains 25% exp for failure?
+ // Player only gains 25% exp for failure?
Player.gainHackingExp(expGainedOnFailure);
workerScript.scriptRef.onlineExpGained += expGainedOnFailure;
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.hack == null) {
@@ -586,7 +585,7 @@ function NetscriptFunctions(workerScript) {
throw makeRuntimeRejectMsg(workerScript, "Cannot grow(). Invalid IP or hostname passed in: " + ip);
}
- //No root access or skill level too low
+ // No root access or skill level too low
const canHack = netscriptCanGrow(server);
if (!canHack.res) {
workerScript.scriptRef.log(`ERROR: ${canHack.msg}`);
@@ -600,7 +599,7 @@ function NetscriptFunctions(workerScript) {
return netscriptDelay(growTime * 1000, workerScript).then(function() {
if (workerScript.env.stopFlag) {return Promise.reject(workerScript);}
const moneyBefore = server.moneyAvailable <= 0 ? 1 : server.moneyAvailable;
- server.moneyAvailable += (1 * threads); //It can be grown even if it has no money
+ server.moneyAvailable += (1 * threads); // It can be grown even if it has no money
var growthPercentage = processSingleServerGrowth(server, 450 * threads, Player);
const moneyAfter = server.moneyAvailable;
workerScript.scriptRef.recordGrow(server.ip, threads);
@@ -648,7 +647,7 @@ function NetscriptFunctions(workerScript) {
throw makeRuntimeRejectMsg(workerScript, "Cannot weaken(). Invalid IP or hostname passed in: " + ip);
}
- //No root access or skill level too low
+ // No root access or skill level too low
const canHack = netscriptCanWeaken(server);
if (!canHack.res) {
workerScript.scriptRef.log(`ERROR: ${canHack.msg}`);
@@ -1075,7 +1074,7 @@ function NetscriptFunctions(workerScript) {
throw makeRuntimeRejectMsg(workerScript, "ERROR: scp() call has incorrect number of arguments. Takes 2 or 3 arguments");
}
if (scriptname && scriptname.constructor === Array) {
- //Recursively call scp on all elements of array
+ // Recursively call scp on all elements of array
var res = false;
scriptname.forEach(function(script) {
if (NetscriptFunctions(workerScript).scp(script, ip1, ip2)) {
@@ -1121,7 +1120,7 @@ function NetscriptFunctions(workerScript) {
throw makeRuntimeRejectMsg(workerScript, "ERROR: scp() call has incorrect number of arguments. Takes 2 or 3 arguments");
}
- //Scp for lit files
+ // Scp for lit files
if (scriptname.endsWith(".lit")) {
var found = false;
for (var i = 0; i < currServ.messages.length; ++i) {
@@ -1141,7 +1140,7 @@ function NetscriptFunctions(workerScript) {
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) {
workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname);
}
- return true; //Already exists
+ return true; // Already exists
}
}
destServer.messages.push(scriptname);
@@ -1151,7 +1150,7 @@ function NetscriptFunctions(workerScript) {
return true;
}
- //Scp for text files
+ // Scp for text files
if (scriptname.endsWith(".txt")) {
var found = false, txtFile;
for (var i = 0; i < currServ.textFiles.length; ++i) {
@@ -1169,7 +1168,7 @@ function NetscriptFunctions(workerScript) {
for (var i = 0; i < destServer.textFiles.length; ++i) {
if (destServer.textFiles[i].fn === scriptname) {
- //Overwrite
+ // Overwrite
destServer.textFiles[i].text = txtFile.text;
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) {
workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname);
@@ -1185,7 +1184,7 @@ function NetscriptFunctions(workerScript) {
return true;
}
- //Scp for script files
+ // Scp for script files
var sourceScript = null;
for (var i = 0; i < currServ.scripts.length; ++i) {
if (scriptname == currServ.scripts[i].filename) {
@@ -1198,7 +1197,7 @@ function NetscriptFunctions(workerScript) {
return false;
}
- //Overwrite script if it already exists
+ // Overwrite script if it already exists
for (var i = 0; i < destServer.scripts.length; ++i) {
if (scriptname == destServer.scripts[i].filename) {
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) {
@@ -1213,7 +1212,7 @@ function NetscriptFunctions(workerScript) {
}
}
- //Create new script if it does not already exist
+ // Create new script if it does not already exist
var newScript = new Script();
newScript.filename = scriptname;
newScript.code = sourceScript.code;
@@ -1239,7 +1238,7 @@ function NetscriptFunctions(workerScript) {
throw makeRuntimeRejectMsg(workerScript, "ls() failed. Invalid IP or hostname passed in: " + ip);
}
- //Get the grep filter, if one exists
+ // Get the grep filter, if one exists
var filter = false;
if (arguments.length >= 2) {
filter = grep.toString();
@@ -1303,7 +1302,7 @@ function NetscriptFunctions(workerScript) {
}
}
- //Sort the files alphabetically then print each
+ // Sort the files alphabetically then print each
allFiles.sort();
return allFiles;
},
@@ -1708,7 +1707,7 @@ function NetscriptFunctions(workerScript) {
var gains = stock.price * shares - CONSTANTS.StockMarketCommission;
Player.gainMoney(gains);
- //Calculate net profit and add to script stats
+ // Calculate net profit and add to script stats
var netProfit = ((stock.price - stock.playerAvgPx) * shares) - CONSTANTS.StockMarketCommission;
if (isNaN(netProfit)) {netProfit = 0;}
workerScript.scriptRef.onlineMoneyMade += netProfit;
@@ -1908,7 +1907,7 @@ function NetscriptFunctions(workerScript) {
if (stock == null) {
throw makeRuntimeRejectMsg(workerScript, "ERROR: Invalid stock symbol passed into getStockVolatility()");
}
- return stock.mv / 100; //Convert from percentage to decimal
+ return stock.mv / 100; // Convert from percentage to decimal
},
getStockForecast : function(symbol) {
if (workerScript.checkingRam) {
@@ -1924,7 +1923,7 @@ function NetscriptFunctions(workerScript) {
}
var forecast = 50;
stock.b ? forecast += stock.otlkMag : forecast -= stock.otlkMag;
- return forecast / 100; //Convert from percentage to decimal
+ return forecast / 100; // Convert from percentage to decimal
},
purchase4SMarketData : function() {
if (workerScript.checkingRam) {
@@ -2087,25 +2086,25 @@ function NetscriptFunctions(workerScript) {
var ip = server.ip;
- //Can't delete server you're currently connected to
+ // Can't delete server you're currently connected to
if (server.isConnectedTo) {
workerScript.scriptRef.log("ERROR: deleteServer() failed because you are currently connected to the server you are trying to delete");
return false;
}
- //A server cannot delete itself
+ // A server cannot delete itself
if (ip === workerScript.serverIp) {
workerScript.scriptRef.log("ERROR: Cannot call deleteServer() on self. deleteServer() failed");
return false;
}
- //Delete all scripts running on server
+ // Delete all scripts running on server
if (server.runningScripts.length > 0) {
workerScript.scriptRef.log("ERROR: Cannot delete server " + server.hostname + " because it still has scripts running.");
return false;
}
- //Delete from player's purchasedServers array
+ // Delete from player's purchasedServers array
var found = false;
for (var i = 0; i < Player.purchasedServers.length; ++i) {
if (ip == Player.purchasedServers[i]) {
@@ -2121,10 +2120,10 @@ function NetscriptFunctions(workerScript) {
return false;
}
- //Delete from all servers
+ // Delete from all servers
delete AllServers[ip];
- //Delete from home computer
+ // Delete from home computer
found = false;
var homeComputer = Player.getHomeComputer();
for (var i = 0; i < homeComputer.serversOnNetwork.length; ++i) {
@@ -2136,7 +2135,7 @@ function NetscriptFunctions(workerScript) {
return true;
}
}
- //Wasn't found on home computer
+ // Wasn't found on home computer
workerScript.scriptRef.log("ERROR: Could not find server " + server.hostname +
"as a purchased server. This is likely a bug please contact game dev");
return false;
@@ -2165,8 +2164,8 @@ function NetscriptFunctions(workerScript) {
return updateStaticRam("write", CONSTANTS.ScriptReadWriteRamCost);
}
updateDynamicRam("write", CONSTANTS.ScriptReadWriteRamCost);
- if (!isNaN(port)) { //Write to port
- //Port 1-10
+ if (!isNaN(port)) { // Write to port
+ // Port 1-10
port = Math.round(port);
if (port < 1 || port > CONSTANTS.NumNetscriptPorts) {
throw makeRuntimeRejectMsg(workerScript, "ERROR: Trying to write to invalid port: " + port + ". Only ports 1-" + CONSTANTS.NumNetscriptPorts + " are valid.");
@@ -2176,17 +2175,17 @@ function NetscriptFunctions(workerScript) {
throw makeRuntimeRejectMsg(workerScript, "Could not find port: " + port + ". This is a bug contact the game developer");
}
return port.write(data);
- } else if (isString(port)) { //Write to script or text file
+ } else if (isString(port)) { // Write to script or text file
var fn = port;
var server = workerScript.getServer();
if (server == null) {
throw makeRuntimeRejectMsg(workerScript, "Error getting Server for this script in write(). This is a bug please contact game dev");
}
if (isScriptFilename(fn)) {
- //Write to script
+ // Write to script
let script = workerScript.getScriptOnServer(fn);
if (script == null) {
- //Create a new script
+ // Create a new script
script = new Script(fn, data, server.ip);
server.scripts.push(script);
return true;
@@ -2194,7 +2193,7 @@ function NetscriptFunctions(workerScript) {
mode === "w" ? script.code = data : script.code += data;
script.updateRamUsage();
} else {
- //Write to text file
+ // Write to text file
let txtFile = getTextFile(fn, server);
if (txtFile == null) {
txtFile = createTextFile(fn, data, server);
@@ -2235,8 +2234,8 @@ function NetscriptFunctions(workerScript) {
return updateStaticRam("read", CONSTANTS.ScriptReadWriteRamCost);
}
updateDynamicRam("read", CONSTANTS.ScriptReadWriteRamCost);
- if (!isNaN(port)) { //Read from port
- //Port 1-10
+ if (!isNaN(port)) { // Read from port
+ // Port 1-10
port = Math.round(port);
if (port < 1 || port > CONSTANTS.NumNetscriptPorts) {
throw makeRuntimeRejectMsg(workerScript, "ERROR: Trying to read from invalid port: " + port + ". Only ports 1-" + CONSTANTS.NumNetscriptPorts + " are valid.");
@@ -2246,21 +2245,21 @@ function NetscriptFunctions(workerScript) {
throw makeRuntimeRejectMsg(workerScript, "ERROR: Could not find port: " + port + ". This is a bug contact the game developer");
}
return port.read();
- } else if (isString(port)) { //Read from script or text file
+ } else if (isString(port)) { // Read from script or text file
let fn = port;
let server = getServer(workerScript.serverIp);
if (server == null) {
throw makeRuntimeRejectMsg(workerScript, "Error getting Server for this script in read(). This is a bug please contact game dev");
}
if (isScriptFilename(fn)) {
- //Read from script
+ // Read from script
let script = workerScript.getScriptOnServer(fn);
if (script == null) {
return "";
}
return script.code;
} else {
- //Read from text file
+ // Read from text file
let txtFile = getTextFile(fn, server);
if (txtFile !== null) {
return txtFile.text;
@@ -2295,7 +2294,7 @@ function NetscriptFunctions(workerScript) {
return updateStaticRam("clear", CONSTANTS.ScriptReadWriteRamCost);
}
updateDynamicRam("clear", CONSTANTS.ScriptReadWriteRamCost);
- if (!isNaN(port)) { //Clear port
+ if (!isNaN(port)) { // Clear port
port = Math.round(port);
if (port < 1 || port > CONSTANTS.NumNetscriptPorts) {
throw makeRuntimeRejectMsg(workerScript, "ERROR: Trying to clear invalid port: " + port + ". Only ports 1-" + CONSTANTS.NumNetscriptPorts + " are valid");
@@ -2305,7 +2304,7 @@ function NetscriptFunctions(workerScript) {
throw makeRuntimeRejectMsg(workerScript, "ERROR: Could not find port: " + port + ". This is a bug contact the game developer");
}
return port.clear();
- } else if (isString(port)) { //Clear text file
+ } else if (isString(port)) { // Clear text file
var fn = port;
var server = getServer(workerScript.serverIp);
if (server == null) {
@@ -2423,7 +2422,7 @@ function NetscriptFunctions(workerScript) {
workerScript.scriptRef.log("getHackTime() failed. Invalid IP or hostname passed in: " + ip);
throw makeRuntimeRejectMsg(workerScript, "getHackTime() failed. Invalid IP or hostname passed in: " + ip);
}
- return calculateHackingTime(server, hack, int); //Returns seconds
+ return calculateHackingTime(server, hack, int); // Returns seconds
},
getGrowTime : function(ip, hack, int) {
if (workerScript.checkingRam) {
@@ -2435,7 +2434,7 @@ function NetscriptFunctions(workerScript) {
workerScript.scriptRef.log("getGrowTime() failed. Invalid IP or hostname passed in: " + ip);
throw makeRuntimeRejectMsg(workerScript, "getGrowTime() failed. Invalid IP or hostname passed in: " + ip);
}
- return calculateGrowTime(server, hack, int); //Returns seconds
+ return calculateGrowTime(server, hack, int); // Returns seconds
},
getWeakenTime : function(ip, hack, int) {
if (workerScript.checkingRam) {
@@ -2447,7 +2446,7 @@ function NetscriptFunctions(workerScript) {
workerScript.scriptRef.log("getWeakenTime() failed. Invalid IP or hostname passed in: " + ip);
throw makeRuntimeRejectMsg(workerScript, "getWeakenTime() failed. Invalid IP or hostname passed in: " + ip);
}
- return calculateWeakenTime(server, hack, int); //Returns seconds
+ return calculateWeakenTime(server, hack, int); // Returns seconds
},
getScriptIncome : function(scriptname, ip) {
if (workerScript.checkingRam) {
@@ -2455,13 +2454,13 @@ function NetscriptFunctions(workerScript) {
}
updateDynamicRam("getScriptIncome", CONSTANTS.ScriptGetScriptRamCost);
if (arguments.length === 0) {
- //Get total script income
+ // Get total script income
var res = [];
res.push(updateActiveScriptsItems());
res.push(Player.scriptProdSinceLastAug / (Player.playtimeSinceLastAug/1000));
return res;
} else {
- //Get income for a particular script
+ // Get income for a particular script
var server = getServer(ip);
if (server == null) {
workerScript.scriptRef.log("getScriptIncome() failed. Invalid IP or hostnamed passed in: " + ip);
@@ -2491,7 +2490,7 @@ function NetscriptFunctions(workerScript) {
}
return total;
} else {
- //Get income for a particular script
+ // Get income for a particular script
var server = getServer(ip);
if (server == null) {
workerScript.scriptRef.log("getScriptExpGain() failed. Invalid IP or hostnamed passed in: " + ip);
@@ -3206,7 +3205,7 @@ function NetscriptFunctions(workerScript) {
workerScript.scriptRef.log("ERROR: Invalid job passed into applyToCompany: " + field + ". applyToCompany() failed");
return false;
}
- //The Player object's applyForJob function can return string with special error messages
+ // The Player object's applyForJob function can return string with special error messages
if (isString(res)) {
workerScript.scriptRef.log(res);
return false;
@@ -3298,7 +3297,7 @@ function NetscriptFunctions(workerScript) {
return false;
}
}
- //Make a copy of Player.factionInvitations
+ // Make a copy of Player.factionInvitations
return Player.factionInvitations.slice();
},
joinFaction : function(name) {
@@ -3327,7 +3326,7 @@ function NetscriptFunctions(workerScript) {
var fac = Factions[name];
joinFaction(fac);
- //Update Faction Invitation list to account for joined + banned factions
+ // Update Faction Invitation list to account for joined + banned factions
for (var i = 0; i < Player.factionInvitations.length; ++i) {
if (Player.factionInvitations[i] == name || Factions[Player.factionInvitations[i]].isBanned) {
Player.factionInvitations.splice(i, 1);
@@ -3383,7 +3382,7 @@ function NetscriptFunctions(workerScript) {
}
var fac = Factions[name];
- //Arrays listing factions that allow each time of work
+ // Arrays listing factions that allow each time of work
var hackAvailable = ["Illuminati", "Daedalus", "The Covenant", "ECorp", "MegaCorp",
"Bachman & Associates", "Blade Industries", "NWO", "Clarke Incorporated",
"OmniTek Incorporated", "Four Sigma", "KuaiGong International",
@@ -4695,7 +4694,7 @@ function NetscriptFunctions(workerScript) {
updateDynamicRam("joinBladeburnerDivision", CONSTANTS.ScriptBladeburnerApiBaseRamCost);
if ((Player.bitNodeN === 7 || hasBladeburner2079SF)) {
if (Player.bladeburner instanceof Bladeburner) {
- return true; //Already member
+ return true; // Already member
} else if (Player.strength >= 100 && Player.defense >= 100 &&
Player.dexterity >= 100 && Player.agility >= 100) {
Player.bladeburner = new Bladeburner({new:true});
@@ -5158,8 +5157,8 @@ function NetscriptFunctions(workerScript) {
return Player.sleeves[sleeveNumber].tryBuyAugmentation(Player, aug);
}
} // End sleeve
- } //End return
-} //End NetscriptFunction()
+ } // End return
+} // End NetscriptFunction()
export {NetscriptFunctions, initSingularitySFFlags, hasSingularitySF, hasBn11SF,
hasWallStreetSF, wallStreetSFLvl, hasCorporationSF, hasAISF, hasBladeburnerSF};
diff --git a/src/Player.js b/src/Player.js
index fe8140fdf..afa0d53af 100644
--- a/src/Player.js
+++ b/src/Player.js
@@ -10,7 +10,7 @@ export let Player = new PlayerObject();
export function loadPlayer(saveString) {
Player = JSON.parse(saveString, Reviver);
- //Parse Decimal.js objects
+ // Parse Decimal.js objects
Player.money = new Decimal(Player.money);
if (Player.corporation instanceof Corporation) {
diff --git a/src/Prestige.js b/src/Prestige.js
index 8eaab913e..c44bf4aa5 100755
--- a/src/Prestige.js
+++ b/src/Prestige.js
@@ -64,7 +64,7 @@ import Decimal from "decimal.js";
const BitNode8StartingMoney = 250e6;
-//Prestige by purchasing augmentation
+// Prestige by purchasing augmentation
function prestigeAugmentation() {
// Set Navigation to Terminal screen, for any logic that depends on it
routing.navigateTo(Page.Terminal);
@@ -81,17 +81,17 @@ function prestigeAugmentation() {
$("#terminal tr:not(:last)").remove();
postNetburnerText();
- //Delete all Worker Scripts objects
+ // Delete all Worker Scripts objects
prestigeWorkerScripts();
var homeComp = Player.getHomeComputer();
- //Delete all servers except home computer
+ // Delete all servers except home computer
prestigeAllServers();
- //Delete Special Server IPs
- prestigeSpecialServerIps(); //Must be done before initForeignServers()
+ // Delete Special Server IPs
+ prestigeSpecialServerIps(); // Must be done before initForeignServers()
- //Reset home computer (only the programs) and add to AllServers
+ // Reset home computer (only the programs) and add to AllServers
AddToAllServers(homeComp);
prestigeHomeComputer(homeComp);
@@ -106,39 +106,39 @@ function prestigeAugmentation() {
homeComp.programs.push(Programs.BruteSSHProgram.name);
}
- //Re-create foreign servers
+ // Re-create foreign servers
initForeignServers(Player.getHomeComputer());
- //Gain favor for Companies
+ // Gain favor for Companies
for (var member in Companies) {
if (Companies.hasOwnProperty(member)) {
Companies[member].gainFavor();
}
}
- //Gain favor for factions
+ // Gain favor for factions
for (var member in Factions) {
if (Factions.hasOwnProperty(member)) {
Factions[member].gainFavor();
}
}
- //Stop a Terminal action if there is onerror
+ // Stop a Terminal action if there is onerror
if (Engine._actionInProgress) {
Engine._actionInProgress = false;
Terminal.finishAction(true);
}
- //Re-initialize things - This will update any changes
- initFactions(); //Factions must be initialized before augmentations
- initAugmentations(); //Calls reapplyAllAugmentations() and resets Player multipliers
+ // Re-initialize things - This will update any changes
+ initFactions(); // Factions must be initialized before augmentations
+ initAugmentations(); // Calls reapplyAllAugmentations() and resets Player multipliers
Player.reapplyAllSourceFiles();
initCompanies();
- //Messages
+ // Messages
initMessages();
- //Gang, in BitNode 2
+ // Gang, in BitNode 2
if (Player.bitNodeN == 2 && Player.inGang()) {
var faction = Factions[Player.gang.facName];
if (faction instanceof Faction) {
@@ -146,19 +146,19 @@ function prestigeAugmentation() {
}
}
- //Cancel Bladeburner action
+ // Cancel Bladeburner action
if (Player.bladeburner instanceof Bladeburner) {
Player.bladeburner.prestige();
}
- //BitNode 8: Ghost of Wall Street
+ // BitNode 8: Ghost of Wall Street
if (Player.bitNodeN === 8) {Player.money = new Decimal(BitNode8StartingMoney);}
if (Player.bitNodeN === 8 || hasWallStreetSF) {
Player.hasWseAccount = true;
Player.hasTixApiAccess = true;
}
- //Reset Stock market
+ // Reset Stock market
if (Player.hasWseAccount) {
initStockMarket();
initSymbolToStockMap();
@@ -169,13 +169,13 @@ function prestigeAugmentation() {
stockMarketList.removeChild(stockMarketList.firstChild);
}
var watchlist = document.getElementById("stock-market-watchlist-filter");
- watchlist.value = ""; //Reset watchlist filter
+ watchlist.value = ""; // Reset watchlist filter
// Refresh Main Menu (the 'World' menu, specifically)
document.getElementById("world-menu-header").click();
document.getElementById("world-menu-header").click();
- //Red Pill
+ // Red Pill
if (augmentationExists(AugmentationNames.TheRedPill) &&
Augmentations[AugmentationNames.TheRedPill].owned) {
var WorldDaemon = AllServers[SpecialServerIps[SpecialServerNames.WorldDaemon]];
@@ -188,27 +188,27 @@ function prestigeAugmentation() {
}
-//Prestige by destroying Bit Node and gaining a Source File
+// Prestige by destroying Bit Node and gaining a Source File
function prestigeSourceFile() {
initBitNodeMultipliers(Player);
updateSourceFileFlags(Player);
Player.prestigeSourceFile();
- prestigeWorkerScripts(); //Delete all Worker Scripts objects
+ prestigeWorkerScripts(); // Delete all Worker Scripts objects
var homeComp = Player.getHomeComputer();
- //Delete all servers except home computer
- prestigeAllServers(); //Must be done before initForeignServers()
+ // Delete all servers except home computer
+ prestigeAllServers(); // Must be done before initForeignServers()
- //Delete Special Server IPs
+ // Delete Special Server IPs
prestigeSpecialServerIps();
- //Reset home computer (only the programs) and add to AllServers
+ // Reset home computer (only the programs) and add to AllServers
AddToAllServers(homeComp);
prestigeHomeComputer(homeComp);
- //Re-create foreign servers
+ // Re-create foreign servers
initForeignServers(Player.getHomeComputer());
if (SourceFileFlags[9] >= 2) {
@@ -253,11 +253,11 @@ function prestigeSourceFile() {
Player.reapplyAllSourceFiles();
initCompanies();
- //Clear terminal
+ // Clear terminal
$("#terminal tr:not(:last)").remove();
postNetburnerText();
- //Messages
+ // Messages
initMessages();
var mainMenu = document.getElementById("mainmenu-container");
@@ -265,17 +265,17 @@ function prestigeSourceFile() {
Terminal.resetTerminalInput();
Engine.loadTerminalContent();
- //Reinitialize Bit Node flags
+ // Reinitialize Bit Node flags
initSingularitySFFlags();
- //BitNode 3: Corporatocracy
+ // BitNode 3: Corporatocracy
if (Player.bitNodeN === 3) {
homeComp.messages.push("corporation-management-handbook.lit");
dialogBoxCreate("You received a copy of the Corporation Management Handbook on your home computer. " +
"Read it if you need help getting started with Corporations!");
}
- //BitNode 6: Bladeburner
+ // BitNode 6: Bladeburner
if (Player.bitNodeN === 6) {
var cinematicText = ["In the middle of the 21st century, OmniTek Incorporated advanced robot evolution " +
"with their Synthoids (synthetic androids), a being virtually identical to a human.",
@@ -319,7 +319,7 @@ function prestigeSourceFile() {
}
- //BitNode 8: Ghost of Wall Street
+ // BitNode 8: Ghost of Wall Street
if (Player.bitNodeN === 8) {Player.money = new Decimal(BitNode8StartingMoney);}
if (Player.bitNodeN === 8 || hasWallStreetSF) {
Player.hasWseAccount = true;
@@ -363,7 +363,7 @@ function prestigeSourceFile() {
document.getElementById("world-menu-header").click();
document.getElementById("world-menu-header").click();
- //Gain int exp
+ // Gain int exp
Player.gainIntelligenceExp(5);
}
diff --git a/src/RedPill.js b/src/RedPill.js
index f0e701d37..23a56ccfe 100644
--- a/src/RedPill.js
+++ b/src/RedPill.js
@@ -1,3 +1,6 @@
+/**
+ * Implementation for what happens when you destroy a BitNode
+ */
import { BitNodes } from "./BitNode/BitNode";
import { Engine } from "./engine";
import { Player } from "./Player";
@@ -18,10 +21,9 @@ import { clearEventListeners } from "../utils/uiHelpers/clearEventListeners";
import { removeChildrenFromElement } from "../utils/uiHelpers/removeChildrenFromElement";
-/* RedPill.js
- * Implements what happens when you have Red Pill augmentation and then hack the world daemon */
-//Returns promise
+
+// Returns promise
function writeRedPillLine(line) {
return new Promise(function(resolve, reject) {
var container = document.getElementById("red-pill-content");
@@ -100,8 +102,6 @@ function hackWorldDaemon(currentNodeNumber, flume=false) {
});
}
-//The bitNode name passed in will have a hyphen between number (e.g. BitNode-1)
-//This needs to be removed
function giveSourceFile(bitNodeNumber) {
var sourceFileKey = "SourceFile"+ bitNodeNumber.toString();
var sourceFile = SourceFiles[sourceFileKey];
@@ -110,7 +110,7 @@ function giveSourceFile(bitNodeNumber) {
return;
}
- //Check if player already has this source file
+ // Check if player already has this source file
var alreadyOwned = false;
var ownedSourceFile = null;
for (var i = 0; i < Player.sourceFiles.length; ++i) {
@@ -133,7 +133,7 @@ function giveSourceFile(bitNodeNumber) {
} else {
var playerSrcFile = new PlayerOwnedSourceFile(bitNodeNumber, 1);
Player.sourceFiles.push(playerSrcFile);
- if (bitNodeNumber === 5) { //Artificial Intelligence
+ if (bitNodeNumber === 5) { // Artificial Intelligence
Player.intelligence = 1;
}
dialogBoxCreate("You received a Source-File for destroying a Bit Node! " +
@@ -142,11 +142,11 @@ function giveSourceFile(bitNodeNumber) {
}
function loadBitVerse(destroyedBitNodeNum, flume=false) {
- //Clear the screen
+ // Clear the screen
var container = document.getElementById("red-pill-content");
removeChildrenFromElement(container);
- //Create the Bit Verse
+ // Create the Bit Verse
var bitVerseImage = document.createElement("pre");
var bitNodes = [];
for (var i = 1; i <= 12; ++i) {
@@ -211,7 +211,7 @@ function loadBitVerse(destroyedBitNodeNum, flume=false) {
container.appendChild(bitVerseImage);
- //Bit node event listeners
+ // Bit node event listeners
for (var i = 1; i <= 12; ++i) {
(function(i) {
var elemId = "bitnode-" + i.toString();
@@ -233,10 +233,10 @@ function loadBitVerse(destroyedBitNodeNum, flume=false) {
dialogBoxCreate("Not yet implemented! Coming soon!")
});
}
- }(i)); //Immediate invocation closure
+ }(i)); // Immediate invocation closure
}
- //Create lore text
+ // Create lore text
return writeRedPillLine("Many decades ago, a humanoid extraterrestial species which we call the Enders descended on the Earth...violently").then(function() {
return writeRedPillLine("Our species fought back, but it was futile. The Enders had technology far beyond our own...");
}).then(function() {
@@ -285,7 +285,7 @@ function loadBitVerse(destroyedBitNodeNum, flume=false) {
}
-//Returns string with DOM element for Bit Node
+// Returns string with DOM element for Bit Node
function createBitNode(n) {
var bitNodeStr = "BitNode" + n.toString();
var bitNode = BitNodes[bitNodeStr];
@@ -304,19 +304,19 @@ function createBitNodeYesNoEventListeners(newBitNode, destroyedBitNode, flume=fa
if (!flume) {
giveSourceFile(destroyedBitNode);
} else {
- //If player used flume, subtract 5 int exp. The prestigeSourceFile()
- //function below grants 5 int exp, so this allows sets net gain to 0
+ // If player used flume, subtract 5 int exp. The prestigeSourceFile()
+ // function below grants 5 int exp, so this allows sets net gain to 0
Player.gainIntelligenceExp(-5);
}
redPillFlag = false;
var container = document.getElementById("red-pill-content");
removeChildrenFromElement(container);
- //Set new Bit Node
+ // Set new Bit Node
Player.bitNodeN = newBitNode;
console.log("Entering Bit Node " + Player.bitNodeN);
- //Reenable terminal
+ // Reenable terminal
$("#hack-progress-bar").attr('id', "old-hack-progress-bar");
$("#hack-progress").attr('id', "old-hack-progress");
document.getElementById("terminal-input-td").innerHTML = '$ ';
diff --git a/src/SaveObject.js b/src/SaveObject.js
index 0f2606198..bd47e3a6e 100755
--- a/src/SaveObject.js
+++ b/src/SaveObject.js
@@ -72,7 +72,7 @@ function BitburnerSaveObject() {
BitburnerSaveObject.prototype.getSaveString = function() {
this.PlayerSave = JSON.stringify(Player);
- //Delete all logs from all running scripts
+ // Delete all logs from all running scripts
var TempAllServers = JSON.parse(JSON.stringify(AllServers), Reviver);
for (var ip in TempAllServers) {
var server = TempAllServers[ip];
@@ -106,7 +106,7 @@ BitburnerSaveObject.prototype.getSaveString = function() {
BitburnerSaveObject.prototype.saveGame = function(db) {
var saveString = this.getSaveString();
- //We'll save to both localstorage and indexedDb
+ // We'll save to both localstorage and indexedDb
var objectStore = db.transaction(["savestring"], "readwrite").objectStore("savestring");
var request = objectStore.put(saveString, "save");
@@ -115,12 +115,11 @@ BitburnerSaveObject.prototype.saveGame = function(db) {
}
request.onsuccess = function(e) {
- //console.log("Saved game to IndexedDB!");
+ // TODO anything here?
}
try {
window.localStorage.setItem("bitburnerSave", saveString);
- //console.log("Saved game to LocalStorage!");
} catch(e) {
if (e.code == 22) {
createStatusText("Save failed for localStorage! Check console(F12)");
@@ -260,7 +259,7 @@ function loadGame(saveString) {
evaluateVersionCompatibility(ver);
if (window.location.href.toLowerCase().includes("bitburner-beta")) {
- //Beta branch, always show changes
+ // Beta branch, always show changes
createBetaUpdateText();
} else if (ver != CONSTANTS.Version) {
createNewUpdateText();
@@ -296,8 +295,8 @@ function loadImportedGame(saveObj, saveString) {
var tempAllGangs = null;
let tempCorporationResearchTrees = null;
- //Check to see if the imported save file can be parsed. If any
- //errors are caught it will fail
+ // Check to see if the imported save file can be parsed. If any
+ // errors are caught it will fail
try {
var decodedSaveString = decodeURIComponent(escape(atob(saveString)));
tempSaveObj = new BitburnerSaveObject();
@@ -305,7 +304,7 @@ function loadImportedGame(saveObj, saveString) {
tempPlayer = JSON.parse(tempSaveObj.PlayerSave, Reviver);
- //Parse Decimal.js objects
+ // Parse Decimal.js objects
tempPlayer.money = new Decimal(tempPlayer.money);
tempAllServers = JSON.parse(tempSaveObj.AllServersSave, Reviver);
@@ -374,7 +373,7 @@ function loadImportedGame(saveObj, saveString) {
return false;
}
- //Since the save file is valid, load everything for real
+ // Since the save file is valid, load everything for real
saveString = decodeURIComponent(escape(atob(saveString)));
saveObj = JSON.parse(saveString, Reviver);
@@ -472,18 +471,18 @@ function loadImportedGame(saveObj, saveString) {
createPopup(popupId, [txt, gotitBtn]);
gameOptionsBoxClose();
- //Re-start game
+ // Re-start game
console.log("Importing game");
- Engine.setDisplayElements(); //Sets variables for important DOM elements
- Engine.init(); //Initialize buttons, work, etc.
+ Engine.setDisplayElements(); // Sets variables for important DOM elements
+ Engine.init(); // Initialize buttons, work, etc.
- //Calculate the number of cycles have elapsed while offline
+ // 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
+ // Process offline progress
+ var offlineProductionFromScripts = loadAllRunningScripts(); // This also takes care of offline production for those scripts
if (Player.isWorking) {
console.log("work() called in load() for " + numCyclesOffline * Engine._idleSpeed + " milliseconds");
if (Player.workType == CONSTANTS.WorkTypeFaction) {
@@ -501,16 +500,16 @@ function loadImportedGame(saveObj, saveString) {
}
}
- //Hacknet Nodes offline progress
+ // Hacknet Nodes offline progress
var offlineProductionFromHacknetNodes = processHacknetEarnings(numCyclesOffline);
const hacknetProdInfo = hasHacknetServers() ?
`${numeralWrapper.format(offlineProductionFromHacknetNodes, "0.000a")} hashes` :
`${numeralWrapper.formatMoney(offlineProductionFromHacknetNodes)}`;
- //Passive faction rep gain offline
+ // Passive faction rep gain offline
processPassiveFactionRepGain(numCyclesOffline);
- //Update total playtime
+ // Update total playtime
var time = numCyclesOffline * Engine._idleSpeed;
if (Player.totalPlaytime == null) {Player.totalPlaytime = 0;}
if (Player.playtimeSinceLastAug == null) {Player.playtimeSinceLastAug = 0;}
@@ -519,14 +518,14 @@ function loadImportedGame(saveObj, saveString) {
Player.playtimeSinceLastAug += time;
Player.playtimeSinceLastBitnode += time;
- //Re-apply augmentations
+ // Re-apply augmentations
Player.reapplyAllAugmentations();
- //Clear terminal
+ // Clear terminal
$("#terminal tr:not(:last)").remove();
Player.lastUpdate = Engine._lastUpdate;
- Engine.start(); //Run main game loop and Scripts loop
+ Engine.start(); // Run main game loop and Scripts loop
const timeOfflineString = convertTimeMsToTimeElapsedString(time);
dialogBoxCreate(`Offline for ${timeOfflineString}. While you were offline, your scripts ` +
"generated " +
@@ -582,12 +581,12 @@ BitburnerSaveObject.prototype.importGame = function() {
}
BitburnerSaveObject.prototype.deleteGame = function(db) {
- //Delete from local storage
+ // Delete from local storage
if (window.localStorage.getItem("bitburnerSave")) {
window.localStorage.removeItem("bitburnerSave");
}
- //Delete from indexedDB
+ // Delete from indexedDB
var request = db.transaction(["savestring"], "readwrite").objectStore("savestring").delete("save");
request.onsuccess = function(e) {
console.log("Successfully deleted save from indexedDb");
@@ -624,8 +623,6 @@ BitburnerSaveObject.fromJSON = function(value) {
Reviver.constructors.BitburnerSaveObject = BitburnerSaveObject;
-//Import game
-
function openImportFileHandler(evt) {
var file = evt.target.files[0];
if (!file) {
diff --git a/src/SourceFile.js b/src/SourceFile.js
index 168087800..e8c9d3bbf 100644
--- a/src/SourceFile.js
+++ b/src/SourceFile.js
@@ -1,8 +1,7 @@
import { Player } from "./Player";
import { BitNodes } from "./BitNode/BitNode";
-/* SourceFile.js */
-//Each SourceFile corresponds to a BitNode with the same number
+// Each SourceFile corresponds to a BitNode with the same number
function SourceFile(number, info="") {
var bitnodeKey = "BitNode" + number;
var bitnode = BitNodes[bitnodeKey];
@@ -80,7 +79,7 @@ function initSourceFiles() {
"In other words, level N of this Source-File will result in a multiplier of 1.01^N (or 0.99^N for multipliers that decrease)");
}
-//Takes in a PlayerOwnedSourceFile as the "srcFile" argument
+// Takes in a PlayerOwnedSourceFile as the "srcFile" argument
function applySourceFile(srcFile) {
var srcFileKey = "SourceFile" + srcFile.n;
var sourceFileObject = SourceFiles[srcFileKey];
diff --git a/src/Terminal.js b/src/Terminal.js
index 76516c6b3..9514b48a5 100644
--- a/src/Terminal.js
+++ b/src/Terminal.js
@@ -112,13 +112,13 @@ function isNumber(str) {
// Defines key commands in terminal
$(document).keydown(function(event) {
- //Terminal
+ // Terminal
if (routing.isOn(Page.Terminal)) {
var terminalInput = document.getElementById("terminal-input-text-box");
if (terminalInput != null && !event.ctrlKey && !event.shiftKey && !Terminal.contractOpen) {terminalInput.focus();}
if (event.keyCode === KEY.ENTER) {
- event.preventDefault(); //Prevent newline from being entered in Script Editor
+ event.preventDefault(); // Prevent newline from being entered in Script Editor
const command = terminalInput.value;
const dir = Terminal.currDir;
post(
@@ -129,35 +129,35 @@ $(document).keydown(function(event) {
);
if (command.length > 0) {
- Terminal.resetTerminalInput(); //Clear input first
+ Terminal.resetTerminalInput(); // Clear input first
Terminal.executeCommands(command);
}
}
if (event.keyCode === KEY.C && event.ctrlKey) {
if (Engine._actionInProgress) {
- //Cancel action
+ // Cancel action
post("Cancelling...");
Engine._actionInProgress = false;
Terminal.finishAction(true);
} else if (FconfSettings.ENABLE_BASH_HOTKEYS) {
- //Dont prevent default so it still copies
- Terminal.resetTerminalInput(); //Clear Terminal
+ // Dont prevent default so it still copies
+ Terminal.resetTerminalInput(); // Clear Terminal
}
}
if (event.keyCode === KEY.L && event.ctrlKey) {
event.preventDefault();
- Terminal.executeCommand("clear"); //Clear screen
+ Terminal.executeCommand("clear"); // Clear screen
}
- //Ctrl p same as up arrow
- //Ctrl n same as down arrow
+ // Ctrl p same as up arrow
+ // Ctrl n same as down arrow
if (event.keyCode === KEY.UPARROW ||
(FconfSettings.ENABLE_BASH_HOTKEYS && event.keyCode === KEY.P && event.ctrlKey)) {
if (FconfSettings.ENABLE_BASH_HOTKEYS) {event.preventDefault();}
- //Cycle through past commands
+ // Cycle through past commands
if (terminalInput == null) {return;}
var i = Terminal.commandHistoryIndex;
var len = Terminal.commandHistory.length;
@@ -178,7 +178,7 @@ $(document).keydown(function(event) {
if (event.keyCode === KEY.DOWNARROW ||
(FconfSettings.ENABLE_BASH_HOTKEYS && event.keyCode === KEY.M && event.ctrlKey)) {
if (FconfSettings.ENABLE_BASH_HOTKEYS) {event.preventDefault();}
- //Cycle through past commands
+ // Cycle through past commands
if (terminalInput == null) {return;}
var i = Terminal.commandHistoryIndex;
var len = Terminal.commandHistory.length;
@@ -188,7 +188,7 @@ $(document).keydown(function(event) {
Terminal.commandHistoryIndex = len;
}
- //Latest command, put nothing
+ // Latest command, put nothing
if (i == len || i == len-1) {
Terminal.commandHistoryIndex = len;
terminalInput.value = "";
@@ -202,7 +202,7 @@ $(document).keydown(function(event) {
if (event.keyCode === KEY.TAB) {
event.preventDefault();
- //Autocomplete
+ // Autocomplete
if (terminalInput == null) {return;}
var input = terminalInput.value;
if (input == "") {return;}
@@ -240,7 +240,7 @@ $(document).keydown(function(event) {
terminalInput.focus();
}
- //Extra Bash Emulation Hotkeys, must be enabled through .fconf
+ // Extra Bash Emulation Hotkeys, must be enabled through .fconf
if (FconfSettings.ENABLE_BASH_HOTKEYS) {
if (event.keyCode === KEY.A && event.ctrlKey) {
event.preventDefault();
@@ -278,17 +278,16 @@ $(document).keydown(function(event) {
event.preventDefault();
}
- //TODO AFTER THIS:
-
- //alt + d deletes word after cursor
- //^w deletes word before cursor
- //^k clears line after cursor
- //^u clears line before cursor
+ // TODO AFTER THIS:
+ // alt + d deletes word after cursor
+ // ^w deletes word before cursor
+ // ^k clears line after cursor
+ // ^u clears line before cursor
}
}
});
-//Keep terminal in focus
+// Keep terminal in focus
let terminalCtrlPressed = false, shiftKeyPressed = false;
$(document).ready(function() {
if (routing.isOn(Page.Terminal)) {
@@ -303,7 +302,7 @@ $(document).keydown(function(e) {
} else if (e.shiftKey) {
shiftKeyPressed = true;
} else if (terminalCtrlPressed || shiftKeyPressed || Terminal.contractOpen) {
- //Don't focus
+ // Don't focus
} else {
var inputTextBox = document.getElementById("terminal-input-text-box");
if (inputTextBox != null) {inputTextBox.focus();}
@@ -349,7 +348,7 @@ let Terminal = {
`` +
'';
- //Auto re-size the line element as it wraps
+ // Auto re-size the line element as it wraps
autosize(document.getElementById("terminal-input-text-box"));
} else {
document.getElementById("terminal-input-td").innerHTML =
@@ -377,7 +376,7 @@ let Terminal = {
terminalInput.value = inputText.substr(0, start-1) + inputText.substr(start);
}
break;
- case "deletewordbefore": //Delete rest of word before the cursor
+ case "deletewordbefore": // Delete rest of word before the cursor
for (var delStart = start-1; delStart > 0; --delStart) {
if (inputText.charAt(delStart) === " ") {
terminalInput.value = inputText.substr(0, delStart) + inputText.substr(start);
@@ -385,7 +384,7 @@ let Terminal = {
}
}
break;
- case "deletewordafter": //Delete rest of word after the cursor
+ case "deletewordafter": // Delete rest of word after the cursor
for (var delStart = start+1; delStart <= text.length+1; ++delStart) {
if (inputText.charAt(delStart) === " ") {
terminalInput.value = inputText.substr(0, start) + inputText.substr(delStart);
@@ -393,9 +392,9 @@ let Terminal = {
}
}
break;
- case "clearafter": //Deletes everything after cursor
+ case "clearafter": // Deletes everything after cursor
break;
- case "clearbefore:": //Deleetes everything before cursor
+ case "clearbefore:": // Deleetes everything before cursor
break;
}
} catch(e) {
@@ -456,7 +455,7 @@ let Terminal = {
startHack: function() {
Terminal.hackFlag = true;
- //Hacking through Terminal should be faster than hacking through a script
+ // Hacking through Terminal should be faster than hacking through a script
Terminal.actionTime = calculateHackingTime(Player.getCurrentServer()) / 4;
Terminal.startAction();
},
@@ -474,7 +473,7 @@ let Terminal = {
hackProgressPost("Time left:");
hackProgressBarPost("[");
- //Disable terminal
+ // Disable terminal
document.getElementById("terminal-input-td").innerHTML = ' ';
$('input[class=terminal-input]').prop('disabled', true);
},
@@ -487,17 +486,17 @@ let Terminal = {
}
},
- //Complete the hack/analyze command
+ // Complete the hack/analyze command
finishHack: function(cancelled = false) {
if (cancelled == false) {
var server = Player.getCurrentServer();
- //Calculate whether hack was successful
+ // Calculate whether hack was successful
var hackChance = calculateHackingChance(server);
var rand = Math.random();
var expGainedOnSuccess = calculateHackingExpGain(server);
var expGainedOnFailure = (expGainedOnSuccess / 4);
- if (rand < hackChance) { //Success!
+ if (rand < hackChance) { // Success!
if (SpecialServerIps[SpecialServerNames.WorldDaemon] &&
SpecialServerIps[SpecialServerNames.WorldDaemon] == server.ip) {
if (Player.bitNodeN == null) {
@@ -510,7 +509,7 @@ let Terminal = {
var moneyGained = calculatePercentMoneyHacked(server);
moneyGained = Math.floor(server.moneyAvailable * moneyGained);
- if (moneyGained <= 0) {moneyGained = 0;} //Safety check
+ if (moneyGained <= 0) {moneyGained = 0;} // Safety check
server.moneyAvailable -= moneyGained;
Player.gainMoney(moneyGained);
@@ -521,14 +520,14 @@ let Terminal = {
server.fortify(CONSTANTS.ServerFortifyAmount);
post("Hack successful! Gained " + numeralWrapper.format(moneyGained, '($0,0.00)') + " and " + numeralWrapper.format(expGainedOnSuccess, '0.0000') + " hacking EXP");
- } else { //Failure
- //Player only gains 25% exp for failure? TODO Can change this later to balance
+ } else { // Failure
+ // Player only gains 25% exp for failure? TODO Can change this later to balance
Player.gainHackingExp(expGainedOnFailure)
post("Failed to hack " + server.hostname + ". Gained " + numeralWrapper.format(expGainedOnFailure, '0.0000') + " 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
$("#hack-progress-bar").attr('id', "old-hack-progress-bar");
$("#hack-progress").attr('id', "old-hack-progress");
Terminal.resetTerminalInput();
@@ -596,7 +595,7 @@ let Terminal = {
executeCommands : function(commands) {
// Sanitize input
commands = commands.trim();
- commands = commands.replace(/\s\s+/g, ' '); //Replace all extra whitespace in command with a single space
+ commands = commands.replace(/\s\s+/g, ' '); // Replace all extra whitespace in command with a single space
// Handle Terminal History - multiple commands should be saved as one
if (Terminal.commandHistory[Terminal.commandHistory.length-1] != commands) {
@@ -644,7 +643,7 @@ let Terminal = {
if (endQuote === command.length-1) {
start = i = endQuote+1;
} else {
- start = i = endQuote+2; //Skip the space
+ start = i = endQuote+2; // Skip the space
}
continue;
}
@@ -663,7 +662,7 @@ let Terminal = {
if (endQuote === command.length-1) {
start = i = endQuote+1;
} else {
- start = i = endQuote+2; //Skip the space
+ start = i = endQuote+2; // Skip the space
}
continue;
}
@@ -705,15 +704,15 @@ let Terminal = {
},
executeCommand : function(command) {
- //Process any aliases
+ // Process any aliases
command = substituteAliases(command);
- //Allow usage of ./
+ // Allow usage of ./
if (command.startsWith("./")) {
command = "run " + command.slice(2);
}
- //Only split the first space
+ // Only split the first space
var commandArray = Terminal.parseCommandArguments(command);
if (commandArray.length == 0) { return; }
@@ -815,7 +814,7 @@ let Terminal = {
case iTutorialSteps.ActiveScriptsToTerminal:
if (commandArray.length == 2 &&
commandArray[0] == "tail" && commandArray[1] == "foodnstuff.script") {
- //Check that the script exists on this machine
+ // Check that the script exists on this machine
var runningScript = findRunningScript("foodnstuff.script", [], Player.getCurrentServer());
if (runningScript == null) {
post("Error: No such script exists");
@@ -941,7 +940,7 @@ let Terminal = {
postError("Incorrect number of arguments. Usage: check [script] [arg1] [arg2]...");
} else {
const scriptName = Terminal.getFilepath(commandArray[1]);
- //Can only tail script files
+ // Can only tail script files
if (!isScriptFilename(scriptName)) {
postError("tail can only be called on .script files (filename must end with .script)");
return;
@@ -977,7 +976,7 @@ let Terminal = {
postNetburnerText();
break;
case "connect": {
- //Disconnect from current server in terminal and connect to new one
+ // Disconnect from current server in terminal and connect to new one
if (commandArray.length !== 2) {
postError("Incorrect usage of connect command. Usage: connect [ip/hostname]");
return;
@@ -1003,7 +1002,7 @@ let Terminal = {
}
const fn = commandArray[1];
if (fn === "*" || fn === "*.script" || fn === "*.txt") {
- //Download all scripts as a zip
+ // Download all scripts as a zip
var zip = new JSZip();
if (fn === "*" || fn === "*.script") {
for (var i = 0; i < s.scripts.length; ++i) {
@@ -1081,8 +1080,8 @@ let Terminal = {
postError("Incorrect usage of hack command. Usage: hack");
return;
}
- //Hack the current PC (usually for money)
- //You can't hack your home pc or servers you purchased
+ // Hack the current PC (usually for money)
+ // You can't hack your home pc or servers you purchased
if (s.purchasedByPlayer) {
postError("Cannot hack your own machines! You are currently connected to your home PC or one of your purchased servers");
} else if (s.hasAdminRights == false ) {
@@ -1262,7 +1261,7 @@ let Terminal = {
return;
}
- //Check programs
+ // Check programs
let delTarget = Terminal.getFilepath(commandArray[1]);
const status = s.removeFile(delTarget);
@@ -1272,19 +1271,19 @@ let Terminal = {
break;
}
case "run":
- //Run a program or a script
+ // Run a program or a script
if (commandArray.length < 2) {
postError("Incorrect number of arguments. Usage: run [program/script] [-t] [num threads] [arg1] [arg2]...");
} else {
var executableName = commandArray[1];
- //Secret Music player!
+ // Secret Music player!
if (executableName === "musicplayer") {
post('', false);
return;
}
- //Check if its a script or just a program/executable
+ // Check if its a script or just a program/executable
if (isScriptFilename(executableName)) {
Terminal.runScript(commandArray);
} else if (executableName.endsWith(".cct")) {
@@ -1434,20 +1433,20 @@ let Terminal = {
post("Script Threads RAM Usage");
let currRunningScripts = s.runningScripts;
- //Iterate through scripts on current server
+ // Iterate through scripts on current server
for (let i = 0; i < currRunningScripts.length; i++) {
let script = currRunningScripts[i];
- //Calculate name padding
- let numSpacesScript = 32 - script.filename.length; //26 -> width of name column
+ // Calculate name padding
+ let numSpacesScript = 32 - script.filename.length; // 26 -> width of name column
if (numSpacesScript < 0) {numSpacesScript = 0;}
let spacesScript = Array(numSpacesScript+1).join(" ");
- //Calculate thread padding
- let numSpacesThread = 16 - (script.threads + "").length; //16 -> width of thread column
+ // Calculate thread padding
+ let numSpacesThread = 16 - (script.threads + "").length; // 16 -> width of thread column
let spacesThread = Array(numSpacesThread+1).join(" ");
- //Calculate and transform RAM usage
+ // Calculate and transform RAM usage
let ramUsage = numeralWrapper.format(script.getRamUsage() * script.threads, '0.00') + " GB";
var entry = [script.filename, spacesScript, script.threads, spacesThread, ramUsage];
@@ -1515,7 +1514,7 @@ let Terminal = {
post("Connected to " + serv.hostname);
Terminal.currDir = "/";
if (Player.getCurrentServer().hostname == "darkweb") {
- checkIfConnectedToDarkweb(); //Posts a 'help' message if connecting to dark web
+ checkIfConnectedToDarkweb(); // Posts a 'help' message if connecting to dark web
}
Terminal.resetTerminalInput();
},
@@ -1606,7 +1605,7 @@ let Terminal = {
prefix = null;
}
- //Display all programs and scripts
+ // Display all programs and scripts
let allFiles = [];
let folders = [];
@@ -1742,18 +1741,18 @@ let Terminal = {
const currServ = Player.getCurrentServer();
post("Hostname IP Root Access");
for (let i = 0; i < currServ.serversOnNetwork.length; i++) {
- //Add hostname
+ // Add hostname
let entry = getServerOnNetwork(currServ, i);
if (entry == null) { continue; }
entry = entry.hostname;
- //Calculate padding and add IP
+ // Calculate padding and add IP
let numSpaces = 21 - entry.length;
let spaces = Array(numSpaces+1).join(" ");
entry += spaces;
entry += getServerOnNetwork(currServ, i).ip;
- //Calculate padding and add root access info
+ // Calculate padding and add root access info
let hasRoot;
if (getServerOnNetwork(currServ, i).hasAdminRights) {
hasRoot = 'Y';
@@ -1769,7 +1768,7 @@ let Terminal = {
},
executeScanAnalyzeCommand: function(depth=1, all=false) {
- //TODO Using array as stack for now, can make more efficient
+ // TODO Using array as stack for now, can make more efficient
post("~~~~~~~~~~ Beginning scan-analyze ~~~~~~~~~~");
post(" ");
@@ -1800,7 +1799,7 @@ let Terminal = {
stack.push(getServerOnNetwork(s, i));
depthQueue.push(d+1);
}
- if (d == 0) {continue;} //Don't print current server
+ if (d == 0) {continue;} // Don't print current server
var titleDashes = Array((d-1) * 4 + 1).join("-");
if (Player.hasProgram(Programs.AutoLink.name)) {
post("" + titleDashes + "> " + s.hostname + " ", false);
@@ -1809,7 +1808,6 @@ let Terminal = {
}
var dashes = titleDashes + "--";
- //var dashes = Array(d * 2 + 1).join("-");
var c = "NO";
if (s.hasAdminRights) {c = "YES";}
post(`${dashes}Root Access: ${c}${!isHacknet ? ", Required hacking skill: " + s.requiredHackingSkill : ""}`);
@@ -1826,7 +1824,7 @@ let Terminal = {
if (Terminal.analyzeFlag || Terminal.hackFlag) {return;}
Terminal.connectToServer(hostname);
}
- }());//Immediate invocation
+ }());// Immediate invocation
}
},
@@ -1850,7 +1848,7 @@ let Terminal = {
const ip = destServer.ip;
const currServ = Player.getCurrentServer();
- //Scp for lit files
+ // Scp for lit files
if (scriptname.endsWith(".lit")) {
var found = false;
for (var i = 0; i < currServ.messages.length; ++i) {
@@ -1865,14 +1863,14 @@ let Terminal = {
for (var i = 0; i < destServer.messages.length; ++i) {
if (destServer.messages[i] === scriptname) {
post(scriptname + " copied over to " + destServer.hostname);
- return; //Already exists
+ return; // Already exists
}
}
destServer.messages.push(scriptname);
return post(scriptname + " copied over to " + destServer.hostname);
}
- //Scp for txt files
+ // Scp for txt files
if (scriptname.endsWith(".txt")) {
var found = false, txtFile;
for (var i = 0; i < currServ.textFiles.length; ++i) {
@@ -1928,8 +1926,8 @@ let Terminal = {
}
},
- //First called when the "run [program]" command is called. Checks to see if you
- //have the executable and, if you do, calls the executeProgram() function
+ // First called when the "run [program]" command is called. Checks to see if you
+ // have the executable and, if you do, calls the executeProgram() function
runProgram: function(commandArray) {
if (commandArray.length < 2) { return; }
@@ -1944,7 +1942,7 @@ let Terminal = {
post("ERROR: No such executable on home computer (Only programs that exist on your home computer can be run)");
},
- //Contains the implementations of all possible programs
+ // Contains the implementations of all possible programs
executeProgram: function(commandArray) {
if (commandArray.length < 2) { return; }
@@ -2238,16 +2236,16 @@ let Terminal = {
}
- //Check if this script is already running
+ // Check if this script is already running
if (findRunningScript(scriptName, args, server) != null) {
post("ERROR: This script is already running. Cannot run multiple instances");
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 < server.scripts.length; i++) {
if (server.scripts[i].filename === scriptName) {
- //Check for admin rights and that there is enough RAM availble to run
+ // Check for admin rights and that there is enough RAM availble to run
var script = server.scripts[i];
var ramUsage = script.ramUsage * numThreads;
var ramAvailable = server.maxRam - server.ramUsed;
@@ -2260,7 +2258,7 @@ let Terminal = {
numThreads + " threads. Script requires " + ramUsage + "GB of RAM");
return;
} else {
- //Able to run script
+ // Able to run script
post("Running script with " + numThreads + " thread(s) and args: " + arrayToString(args) + ".");
post("May take a few seconds to start up the process...");
var runningScriptObj = new RunningScript(script, args);
diff --git a/src/engine.jsx b/src/engine.jsx
index 3613d73b9..9def55e33 100644
--- a/src/engine.jsx
+++ b/src/engine.jsx
@@ -155,7 +155,8 @@ import "../css/grid.min.css";
import "../css/dev-menu.css";
-/* Shortcuts to navigate through the game
+/**
+ * Shortcuts to navigate through the game
* Alt-t - Terminal
* Alt-c - Character
* Alt-e - Script editor
@@ -209,7 +210,7 @@ $(document).keydown(function(e) {
e.preventDefault();
Engine.loadCreateProgramContent();
} else if (e.keyCode === KEY.F && e.altKey) {
- //Overriden by Fconf
+ // Overriden by Fconf
if (routing.isOn(Page.Terminal) && FconfSettings.ENABLE_BASH_HOTKEYS) {
return;
}
@@ -234,24 +235,25 @@ const Engine = {
version: "",
Debug: true,
- //Clickable objects
+ // Clickable objects
Clickables: {
- //Main menu buttons
+ // Main menu buttons
saveMainMenuButton: null,
deleteMainMenuButton: null,
},
- //Display objects
+ // Display objects
+ // TODO-Refactor this into its own component
Display: {
- //Progress bar
+ // Progress bar
progress: null,
- //Display for status text (such as "Saved" or "Loaded")
+ // Display for status text (such as "Saved" or "Loaded")
statusText: null,
hacking_skill: null,
- //Main menu content
+ // Main menu content
terminalContent: null,
characterContent: null,
scriptEditorContent: null,
@@ -271,15 +273,14 @@ const Engine = {
cinematicTextContent: null,
missionContent: null,
- //Character info
+ // Character info
characterInfo: null,
},
- //Time variables (milliseconds unix epoch time)
+ // Time variables (milliseconds unix epoch time)
_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
- /* Load content when a main menu button is clicked */
loadTerminalContent: function() {
Engine.hideAllContent();
Engine.Display.terminalContent.style.display = "block";
@@ -425,7 +426,6 @@ const Engine = {
loadWorkInProgressContent: function() {
Engine.hideAllContent();
var mainMenu = document.getElementById("mainmenu-container");
- //mainMenu.style.visibility = "hidden";
mainMenu.style.visibility = "hidden";
Engine.Display.workInProgressContent.style.display = "block";
routing.navigateTo(Page.WorkInProgress);
@@ -602,15 +602,16 @@ const Engine = {
}
},
- /* Display character info */
+ /// Display character info
updateCharacterInfo: function() {
displayCharacterInfo(Engine.Display.characterInfo, Player);
},
+ // TODO Refactor this into Faction implementation
displayFactionsInfo: function() {
removeChildrenFromElement(Engine.Display.factionsContent);
- //Factions
+ // Factions
Engine.Display.factionsContent.appendChild(createElement("h1", {
innerText:"Factions"
}));
@@ -620,7 +621,7 @@ const Engine = {
var factionsList = createElement("ul");
Engine.Display.factionsContent.appendChild(createElement("br"));
- //Add a button for each faction you are a member of
+ // Add a button for each faction you are a member of
for (var i = 0; i < Player.factions.length; ++i) {
(function () {
var factionName = Player.factions[i];
@@ -635,12 +636,12 @@ const Engine = {
}
}));
factionsList.appendChild(createElement("br"));
- }()); //Immediate invocation
+ }()); // Immediate invocation
}
Engine.Display.factionsContent.appendChild(factionsList);
Engine.Display.factionsContent.appendChild(createElement("br"));
- //Invited Factions
+ // Invited Factions
Engine.Display.factionsContent.appendChild(createElement("h1", {
innerText:"Outstanding Faction Invitations"
}));
@@ -652,7 +653,7 @@ const Engine = {
}));
var invitationsList = createElement("ul");
- //Add a button to accept for each faction you have invitiations for
+ // Add a button to accept for each faction you have invitiations for
for (var i = 0; i < Player.factionInvitations.length; ++i) {
(function () {
var factionName = Player.factionInvitations[i];
@@ -685,18 +686,18 @@ const Engine = {
Engine.Display.factionsContent.appendChild(invitationsList);
},
- /* Main Event Loop */
+ // Main Game Loop
idleTimer: function() {
- //Get time difference
+ // Get time difference
var _thisUpdate = new Date().getTime();
var diff = _thisUpdate - Engine._lastUpdate;
var offset = diff % Engine._idleSpeed;
- //Divide this by cycle time to determine how many cycles have elapsed since last update
+ // Divide this by cycle time to determine how many cycles have elapsed since last update
diff = Math.floor(diff / Engine._idleSpeed);
if (diff > 0) {
- //Update the game engine by the calculated number of cycles
+ // Update the game engine by the calculated number of cycles
Engine._lastUpdate = _thisUpdate - offset;
Player.lastUpdate = _thisUpdate - offset;
Engine.updateGame(diff);
@@ -714,7 +715,7 @@ const Engine = {
Player.playtimeSinceLastAug += time;
Player.playtimeSinceLastBitnode += time;
- //Start Manual hack
+ // Start Manual hack
if (Terminal.actionStarted === true) {
Engine._totalActionTime = Terminal.actionTime;
Engine._actionTimeLeft = Terminal.actionTime;
@@ -725,7 +726,7 @@ const Engine = {
Terminal.actionStarted = false;
}
- //Working
+ // Working
if (Player.isWorking) {
if (Player.workType == CONSTANTS.WorkTypeFaction) {
Player.workForFaction(numCycles);
@@ -747,20 +748,19 @@ const Engine = {
processStockPrices(numCycles);
}
- //Gang, if applicable
+ // Gang, if applicable
if (Player.bitNodeN == 2 && Player.inGang()) {
Player.gang.process(numCycles, Player);
}
- //Mission
+ // Mission
if (inMission && currMission) {
currMission.process(numCycles);
}
- //Corporation
+ // Corporation
if (Player.corporation instanceof Corporation) {
- //Stores cycles in a "buffer". Processed separately using Engine Counters
- //This is to avoid constant DOM redraws when Corporation is catching up
+ // Stores cycles in a "buffer". Processed separately using Engine Counters
Player.corporation.storeCycles(numCycles);
}
@@ -782,38 +782,41 @@ const Engine = {
}
}
- //Counters
+ // Counters
Engine.decrementAllCounters(numCycles);
Engine.checkCounters();
- //Manual hacks
+ // Manual hacks
if (Engine._actionInProgress == true) {
Engine.updateHackProgress(numCycles);
}
- //Update the running time of all active scripts
+ // Update the running time of all active scripts
updateOnlineScriptTimes(numCycles);
- //Hacknet Nodes
+ // Hacknet Nodes
processHacknetEarnings(numCycles);
},
- //Counters for the main event loop. Represent the number of game cycles are required
- //for something to happen.
+ /**
+ * Counters for the main event loop. Represent the number of game cycles that
+ * are required for something to happen. These counters are in game cycles,
+ * which is once every 200ms
+ */
Counters: {
- autoSaveCounter: 300, //Autosave every minute
- updateSkillLevelsCounter: 10, //Only update skill levels every 2 seconds. Might improve performance
+ autoSaveCounter: 300,
+ updateSkillLevelsCounter: 10,
updateDisplays: 3,
updateDisplaysMed: 9,
updateDisplaysLong: 15,
updateActiveScriptsDisplay: 5,
- createProgramNotifications: 10, //Checks whether any programs can be created and notifies
- checkFactionInvitations: 100, //Check whether you qualify for any faction invitations
+ createProgramNotifications: 10,
+ checkFactionInvitations: 100,
passiveFactionGrowth: 600,
messages: 150,
sCr: 1500,
- mechanicProcess: 5, //Processes certain mechanics (Corporation, Bladeburner)
- contractGeneration: 3000 //Generate Coding Contracts
+ mechanicProcess: 5, // Processes certain mechanics (Corporation, Bladeburner)
+ contractGeneration: 3000, // Generate Coding Contracts
},
decrementAllCounters: function(numCycles = 1) {
@@ -824,8 +827,10 @@ const Engine = {
}
},
- //Checks if any counters are 0 and if they are, executes whatever
- //is necessary and then resets the counter
+ /**
+ * Checks if any counters are 0. If they are, executes whatever
+ * is necessary and then resets the counter
+ */
checkCounters: function() {
if (Engine.Counters.autoSaveCounter <= 0) {
if (Settings.AutosaveInterval == null) {
@@ -845,7 +850,7 @@ const Engine = {
}
if (Engine.Counters.updateActiveScriptsDisplay <= 0) {
- //Always update, but make the interval longer if the page isn't active
+ // Always update, but make the interval longer if the page isn't active
updateActiveScriptsItems();
if (routing.isOn(Page.ActiveScripts)) {
Engine.Counters.updateActiveScriptsDisplay = 5;
@@ -925,7 +930,7 @@ const Engine = {
if (Engine.Counters.messages <= 0) {
checkForMessagesToSend();
if (Augmentations[AugmentationNames.TheRedPill].owned) {
- Engine.Counters.messages = 4500; //15 minutes for Red pill message
+ Engine.Counters.messages = 4500; // 15 minutes for Red pill message
} else {
Engine.Counters.messages = 150;
}
@@ -962,7 +967,8 @@ const Engine = {
}
},
- /* Calculates the hack progress for a manual (non-scripted) hack and updates the progress bar/time accordingly */
+ // Calculates the hack progress for a manual (non-scripted) hack and updates the progress bar/time accordingly
+ // TODO Refactor this into Terminal module
_totalActionTime: 0,
_actionTimeLeft: 0,
_actionTimeStr: "Time left: ",
@@ -971,34 +977,36 @@ const Engine = {
_actionInProgress: false,
updateHackProgress: function(numCycles = 1) {
var timeElapsedMilli = numCycles * Engine._idleSpeed;
- Engine._actionTimeLeft -= (timeElapsedMilli/ 1000); //Substract idle speed (ms)
+ Engine._actionTimeLeft -= (timeElapsedMilli/ 1000); // Substract idle speed (ms)
Engine._actionTimeLeft = Math.max(Engine._actionTimeLeft, 0);
- //Calculate percent filled
+ // Calculate percent filled
var percent = Math.round((1 - Engine._actionTimeLeft / Engine._totalActionTime) * 100);
- //Update progress bar
+ // Update progress bar
while (Engine._actionProgressBarCount * 2 <= percent) {
Engine._actionProgressStr = replaceAt(Engine._actionProgressStr, Engine._actionProgressBarCount, "|");
Engine._actionProgressBarCount += 1;
}
- //Update hack time remaining
+ // Update hack time remaining
Engine._actionTimeStr = "Time left: " + Math.max(0, Math.round(Engine._actionTimeLeft)).toString() + "s";
document.getElementById("hack-progress").innerHTML = Engine._actionTimeStr;
- //Dynamically update progress bar
+ // Dynamically update progress bar
document.getElementById("hack-progress-bar").innerHTML = Engine._actionProgressStr.replace( / /g, " " );
- //Once percent is 100, the hack is completed
+ // Once percent is 100, the hack is completed
if (percent >= 100) {
Engine._actionInProgress = false;
Terminal.finishAction();
}
},
- //Used when initializing a game
- //elems should be an array of all DOM elements under the header
+ /**
+ * Collapses a main menu header. Used when initializing the game.
+ * @param elems {HTMLElement[]} Elements under header
+ */
closeMainMenuHeader: function(elems) {
for (var i = 0; i < elems.length; ++i) {
elems[i].style.maxHeight = null;
@@ -1007,8 +1015,10 @@ const Engine = {
}
},
- //Used when initializing the game
- //elems should be an array of all DOM elements under the header
+ /**
+ * Expands a main menu header. Used when initializing the game.
+ * @param elems {HTMLElement[]} Elements under header
+ */
openMainMenuHeader: function(elems) {
for (var i = 0; i < elems.length; ++i) {
elems[i].style.maxHeight = elems[i].scrollHeight + "px";
@@ -1016,10 +1026,12 @@ const Engine = {
}
},
- //Used in game when clicking on a main menu header (NOT FOR INITIALIZATION)
- //open is a boolean specifying whether its being opened or closed
- //elems is an array of DOM elements for main menu tabs (li)
- //links is an array of DOM elements for main menu links (a)
+ /**
+ * Used in game when clicking on a main menu header (NOT used for initialization)
+ * @param open {boolean} Whether header is being opened or closed
+ * @param elems {HTMLElement[]} li Elements under header
+ * @param links {HTMLElement[]} a elements under header
+ */
toggleMainMenuHeader: function(open, elems, links) {
for (var i = 0; i < elems.length; ++i) {
if (open) {
@@ -1045,35 +1057,34 @@ const Engine = {
},
load: function(saveString) {
- //Initialize main menu accordion panels to all start as "open"
- var terminal = document.getElementById("terminal-tab");
- var createScript = document.getElementById("create-script-tab");
- var activeScripts = document.getElementById("active-scripts-tab");
- var createProgram = document.getElementById("create-program-tab");
- var stats = document.getElementById("stats-tab");
- var factions = document.getElementById("factions-tab");
- var augmentations = document.getElementById("augmentations-tab");
- var hacknetnodes = document.getElementById("hacknet-nodes-tab");
- var city = document.getElementById("city-tab");
- var travel = document.getElementById("travel-tab");
- var job = document.getElementById("job-tab");
- var stockmarket = document.getElementById("stock-market-tab");
- var bladeburner = document.getElementById("bladeburner-tab");
- var corp = document.getElementById("corporation-tab");
- var gang = document.getElementById("gang-tab");
- var tutorial = document.getElementById("tutorial-tab");
- var options = document.getElementById("options-tab");
- var dev = document.getElementById("dev-tab");
+ // Initialize main menu accordion panels to all start as "open"
+ const terminal = document.getElementById("terminal-tab");
+ const createScript = document.getElementById("create-script-tab");
+ const activeScripts = document.getElementById("active-scripts-tab");
+ const createProgram = document.getElementById("create-program-tab");
+ const stats = document.getElementById("stats-tab");
+ const factions = document.getElementById("factions-tab");
+ const augmentations = document.getElementById("augmentations-tab");
+ const hacknetnodes = document.getElementById("hacknet-nodes-tab");
+ const city = document.getElementById("city-tab");
+ const travel = document.getElementById("travel-tab");
+ const job = document.getElementById("job-tab");
+ const stockmarket = document.getElementById("stock-market-tab");
+ const bladeburner = document.getElementById("bladeburner-tab");
+ const corp = document.getElementById("corporation-tab");
+ const gang = document.getElementById("gang-tab");
+ const tutorial = document.getElementById("tutorial-tab");
+ const options = document.getElementById("options-tab");
+ const dev = document.getElementById("dev-tab");
- //Load game from save or create new game
+ // Load game from save or create new game
if (loadGame(saveString)) {
- console.log("Loaded game from save");
initBitNodes();
initBitNodeMultipliers(Player);
initSourceFiles();
- Engine.setDisplayElements(); //Sets variables for important DOM elements
- Engine.init(); //Initialize buttons, work, etc.
- initAugmentations(); //Also calls Player.reapplyAllAugmentations()
+ Engine.setDisplayElements(); // Sets variables for important DOM elements
+ Engine.init(); // Initialize buttons, work, etc.
+ initAugmentations(); // Also calls Player.reapplyAllAugmentations()
Player.reapplyAllSourceFiles();
initStockSymbols();
if (Player.hasWseAccount) {
@@ -1083,13 +1094,13 @@ const Engine = {
initSingularitySFFlags();
updateSourceFileFlags(Player);
- //Calculate the number of cycles have elapsed while offline
+ // 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
+ // Process offline progress
+ var offlineProductionFromScripts = loadAllRunningScripts(); // This also takes care of offline production for those scripts
if (Player.isWorking) {
console.log("work() called in load() for " + numCyclesOffline * Engine._idleSpeed + " milliseconds");
if (Player.workType == CONSTANTS.WorkTypeFaction) {
@@ -1107,13 +1118,13 @@ const Engine = {
}
}
- //Hacknet Nodes offline progress
+ // Hacknet Nodes offline progress
var offlineProductionFromHacknetNodes = processHacknetEarnings(numCyclesOffline);
const hacknetProdInfo = hasHacknetServers() ?
`${numeralWrapper.format(offlineProductionFromHacknetNodes, "0.000a")} hashes` :
`${numeralWrapper.formatMoney(offlineProductionFromHacknetNodes)}`;
- //Passive faction rep gain offline
+ // Passive faction rep gain offline
processPassiveFactionRepGain(numCyclesOffline);
// Stock Market offline progress
@@ -1150,7 +1161,7 @@ const Engine = {
}
}
- //Update total playtime
+ // Update total playtime
var time = numCyclesOffline * Engine._idleSpeed;
if (Player.totalPlaytime == null) {Player.totalPlaytime = 0;}
if (Player.playtimeSinceLastAug == null) {Player.playtimeSinceLastAug = 0;}
@@ -1160,14 +1171,14 @@ const Engine = {
Player.playtimeSinceLastBitnode += time;
Player.lastUpdate = Engine._lastUpdate;
- Engine.start(); //Run main game loop and Scripts loop
+ Engine.start(); // Run main game loop and Scripts loop
removeLoadingScreen();
const timeOfflineString = convertTimeMsToTimeElapsedString(time);
dialogBoxCreate(`Offline for ${timeOfflineString}. While you were offline, your scripts ` +
"generated " +
numeralWrapper.formatMoney(offlineProductionFromScripts) + " " +
"and your Hacknet Nodes generated " + hacknetProdInfo + " ");
- //Close main menu accordions for loaded game
+ // Close main menu accordions for loaded game
var visibleMenuTabs = [terminal, createScript, activeScripts, stats,
hacknetnodes, city, tutorial, options, dev];
if (Player.firstFacInvRecvd) {visibleMenuTabs.push(factions);}
@@ -1191,14 +1202,14 @@ const Engine = {
Engine.closeMainMenuHeader(visibleMenuTabs);
} else {
- //No save found, start new game
+ // No save found, start new game
console.log("Initializing new game");
initBitNodes();
initBitNodeMultipliers(Player);
initSourceFiles();
initSpecialServerIps();
- Engine.setDisplayElements(); //Sets variables for important DOM elements
- Engine.start(); //Run main game loop and Scripts loop
+ Engine.setDisplayElements(); // Sets variables for important DOM elements
+ Engine.start(); // Run main game loop and Scripts loop
Player.init();
initForeignServers(Player.getHomeComputer());
initCompanies();
@@ -1209,18 +1220,17 @@ const Engine = {
initLiterature();
initSingularitySFFlags();
- //Open main menu accordions for new game
- //Main menu accordions
- var hackingHdr = document.getElementById("hacking-menu-header");
+ // Open main menu accordions for new game
+ const hackingHdr = document.getElementById("hacking-menu-header");
hackingHdr.classList.toggle("opened");
- var characterHdr = document.getElementById("character-menu-header");
+ const characterHdr = document.getElementById("character-menu-header");
characterHdr.classList.toggle("opened");
- var worldHdr = document.getElementById("world-menu-header");
+ const worldHdr = document.getElementById("world-menu-header");
worldHdr.classList.toggle("opened");
- var helpHdr = document.getElementById("help-menu-header");
+ const helpHdr = document.getElementById("help-menu-header");
helpHdr.classList.toggle("opened");
- //Hide tabs that wont be revealed until later
+ // Hide tabs that wont be revealed until later
factions.style.display = "none";
augmentations.style.display = "none";
job.style.display = "none";
@@ -1238,18 +1248,18 @@ const Engine = {
tutorial, options]
);
- //Start interactive tutorial
+ // Start interactive tutorial
iTutorialStart();
removeLoadingScreen();
}
- //Initialize labels on game settings
+ // Initialize labels on game settings
setSettingsLabels();
scriptEditorInit();
Terminal.resetTerminalInput();
},
setDisplayElements: function() {
- //Content elements
+ // Content elements
Engine.Display.terminalContent = document.getElementById("terminal-container");
routing.navigateTo(Page.Terminal);
@@ -1294,22 +1304,22 @@ const Engine = {
Engine.Display.missionContent = document.getElementById("mission-container");
Engine.Display.missionContent.style.display = "none";
- //Character info
+ // Character info
Engine.Display.characterInfo = document.getElementById("character-content");
- //Location page (page that shows up when you visit a specific location in World)
+ // Location page (page that shows up when you visit a specific location in World)
Engine.Display.locationContent = document.getElementById("location-container");
Engine.Display.locationContent.style.display = "none";
- //Work In Progress
+ // Work In Progress
Engine.Display.workInProgressContent = document.getElementById("work-in-progress-container");
Engine.Display.workInProgressContent.style.display = "none";
- //Red Pill / Hack World Daemon
+ // Red Pill / Hack World Daemon
Engine.Display.redPillContent = document.getElementById("red-pill-container");
Engine.Display.redPillContent.style.display = "none";
- //Cinematic Text
+ // Cinematic Text
Engine.Display.cinematicTextContent = document.getElementById("cinematic-text-container");
Engine.Display.cinematicTextContent.style.display = "none";
@@ -1323,9 +1333,9 @@ const Engine = {
}
},
- /* Initialization */
+ // Initialization
init: function() {
- //Import game link
+ // Import game link
document.getElementById("import-game-link").onclick = function() {
saveObject.importGame();
};
@@ -1434,10 +1444,10 @@ const Engine = {
return false;
});
- //Active scripts list
+ // Active scripts list
Engine.ActiveScriptsList = document.getElementById("active-scripts-list");
- //Save, Delete, Import/Export buttons
+ // Save, Delete, Import/Export buttons
Engine.Clickables.saveMainMenuButton = document.getElementById("save-game-link");
Engine.Clickables.saveMainMenuButton.addEventListener("click", function() {
saveObject.saveGame(indexedDb);
@@ -1455,7 +1465,7 @@ const Engine = {
return false;
});
- //Character Overview buttons
+ // Character Overview buttons
document.getElementById("character-overview-save-button").addEventListener("click", function() {
saveObject.saveGame(indexedDb);
return false;
@@ -1466,13 +1476,13 @@ const Engine = {
return false;
});
- //Create Program buttons
+ // Create Program buttons
initCreateProgramButtons();
- //Message at the top of terminal
+ // Message at the top of terminal
postNetburnerText();
- //Player was working cancel button
+ // Player was working cancel button
if (Player.isWorking) {
var cancelButton = document.getElementById("work-in-progress-cancel-button");
cancelButton.addEventListener("click", function() {
@@ -1494,10 +1504,10 @@ const Engine = {
Engine.loadWorkInProgressContent();
}
- //character overview screen
+ // Character overview screen
document.getElementById("character-overview-container").style.display = "block";
- //Remove classes from links (they might be set from tutorial)
+ // Remove classes from links (they might be set from tutorial)
document.getElementById("terminal-menu-link").removeAttribute("class");
document.getElementById("stats-menu-link").removeAttribute("class");
document.getElementById("create-script-menu-link").removeAttribute("class");
@@ -1543,7 +1553,7 @@ const Engine = {
}
});
- //DEBUG Delete active Scripts on home
+ // DEBUG Delete active Scripts on home
document.getElementById("debug-delete-scripts-link").addEventListener("click", function() {
console.log("Deleting running scripts on home computer");
Player.getHomeComputer().runningScripts = [];
@@ -1552,7 +1562,7 @@ const Engine = {
return false;
});
- //DEBUG Soft Reset
+ // DEBUG Soft Reset
document.getElementById("debug-soft-reset").addEventListener("click", function() {
dialogBoxCreate("Soft Reset!");
prestigeAugmentation();
@@ -1562,10 +1572,10 @@ const Engine = {
},
start: function() {
- //Run main loop
+ // Run main loop
Engine.idleTimer();
- //Scripts
+ // Script-processing loop
runScriptsLoop();
}
};
@@ -1573,18 +1583,20 @@ const Engine = {
var indexedDb, indexedDbRequest;
window.onload = function() {
if (!window.indexedDB) {
- return Engine.load(null); //Will try to load from localstorage
+ return Engine.load(null); // Will try to load from localstorage
}
- //DB is called bitburnerSave
- //Object store is called savestring
- //key for the Object store is called save
+ /**
+ * DB is called bitburnerSave
+ * Object store is called savestring
+ * key for the Object store is called save
+ */
indexedDbRequest = window.indexedDB.open("bitburnerSave", 1);
indexedDbRequest.onerror = function(e) {
console.log("Error opening indexedDB: ");
console.log(e);
- return Engine.load(null); //Try to load from localstorage
+ return Engine.load(null); // Try to load from localstorage
};
indexedDbRequest.onsuccess = function(e) {
@@ -1595,11 +1607,11 @@ window.onload = function() {
var request = objectStore.get("save");
request.onerror = function(e) {
console.log("Error in Database request to get savestring: " + e);
- return Engine.load(null); //Try to load from localstorage
+ return Engine.load(null); // Try to load from localstorage
}
request.onsuccess = function(e) {
- Engine.load(request.result); //Is this right?
+ Engine.load(request.result);
}
};