From df89cc5002cdc9f0fe8deaa0d39cb27681cdb6a0 Mon Sep 17 00:00:00 2001 From: danielyxie Date: Thu, 11 Apr 2019 01:37:40 -0700 Subject: [PATCH 1/6] Improved module import styling for all top-level src files --- src/ActiveScriptsUI.js | 63 +++++---- src/Alias.ts | 4 +- src/Bladeburner.js | 66 +++++---- src/CinematicText.js | 39 +++--- src/CodingContractGenerator.js | 19 +-- src/CodingContracts.ts | 19 ++- src/Constants.ts | 2 +- src/DevMenu.jsx | 94 ++++++------- src/Gang.js | 51 ++++--- src/Infiltration.js | 36 ++--- src/InteractiveTutorial.js | 21 +-- src/Literature.js | 2 +- src/Missions.js | 27 ++-- src/NetscriptBladeburner.js | 6 +- src/NetscriptEnvironment.js | 4 +- src/NetscriptEvaluator.js | 32 ++--- src/NetscriptFunctions.js | 242 +++++++++++++++++++-------------- src/NetscriptGang.js | 6 +- src/NetscriptJSEvaluator.js | 2 +- src/NetscriptPort.js | 2 +- src/NetscriptWorker.js | 52 +++---- src/Prestige.js | 109 ++++++++------- src/RedPill.js | 32 +++-- src/SaveObject.js | 81 ++++++----- src/Terminal.js | 149 ++++++++++---------- src/TextFile.ts | 7 +- src/engine.jsx | 213 ++++++++++++++++------------- 27 files changed, 751 insertions(+), 629 deletions(-) diff --git a/src/ActiveScriptsUI.js b/src/ActiveScriptsUI.js index 1cdc66b26..910dde947 100644 --- a/src/ActiveScriptsUI.js +++ b/src/ActiveScriptsUI.js @@ -1,35 +1,38 @@ -import {workerScripts, - killWorkerScript} from "./NetscriptWorker"; -import { Player } from "./Player"; -import { getServer } from "./Server/ServerHelpers"; -import {numeralWrapper} from "./ui/numeralFormat"; -import {dialogBoxCreate} from "../utils/DialogBox"; -import {createAccordionElement} from "../utils/uiHelpers/createAccordionElement"; -import {arrayToString} from "../utils/helpers/arrayToString"; -import {createElement} from "../utils/uiHelpers/createElement"; -import {createProgressBarText} from "../utils/helpers/createProgressBarText"; -import {exceptionAlert} from "../utils/helpers/exceptionAlert"; -import {getElementById} from "../utils/uiHelpers/getElementById"; -import {logBoxCreate} from "../utils/LogBox"; -import {formatNumber, - convertTimeMsToTimeElapsedString } from "../utils/StringHelperFunctions"; -import {removeChildrenFromElement} from "../utils/uiHelpers/removeChildrenFromElement"; -import {removeElement} from "../utils/uiHelpers/removeElement"; -import {roundToTwo} from "../utils/helpers/roundToTwo"; -import {Page, routing} from "./ui/navigationTracking"; +// TODO - Convert this to React +import { workerScripts, killWorkerScript } from "./NetscriptWorker"; +import { Player } from "./Player"; +import { getServer } from "./Server/ServerHelpers"; -/* { - * serverName: { - * header: Server Header Element - * panel: Server Panel List (ul) element - * scripts: { - * script id: Ref to Script information - * } - * } - * ... +import { Page, routing } from "./ui/navigationTracking"; +import { numeralWrapper } from "./ui/numeralFormat"; + +import { dialogBoxCreate } from "../utils/DialogBox"; +import { logBoxCreate } from "../utils/LogBox"; +import { convertTimeMsToTimeElapsedString } from "../utils/StringHelperFunctions"; +import { arrayToString } from "../utils/helpers/arrayToString"; +import { createProgressBarText } from "../utils/helpers/createProgressBarText"; +import { exceptionAlert } from "../utils/helpers/exceptionAlert"; +import { roundToTwo } from "../utils/helpers/roundToTwo"; +import { createAccordionElement } from "../utils/uiHelpers/createAccordionElement"; +import { createElement } from "../utils/uiHelpers/createElement"; +import { getElementById } from "../utils/uiHelpers/getElementById"; +import { removeChildrenFromElement } from "../utils/uiHelpers/removeChildrenFromElement"; +import { removeElement } from "../utils/uiHelpers/removeElement"; + + +/** + * { + * serverName: { + * header: Server Header Element + * panel: Server Panel List (ul) element + * scripts: { + * script id: Ref to Script information + * } + * } + * ... */ -let ActiveScriptsUI = {}; -let ActiveScriptsTasks = []; //Sequentially schedule the creation/deletion of UI elements +const ActiveScriptsUI = {}; +const ActiveScriptsTasks = []; //Sequentially schedule the creation/deletion of UI elements const getHeaderHtml = (server) => { // TODO: calculate the longest hostname length rather than hard coding it diff --git a/src/Alias.ts b/src/Alias.ts index 587c73209..f512fe9c7 100644 --- a/src/Alias.ts +++ b/src/Alias.ts @@ -1,5 +1,5 @@ -import { IMap } from "./types"; -import { post } from "./ui/postToTerminal"; +import { IMap } from "./types"; +import { post } from "./ui/postToTerminal"; export let Aliases: IMap = {}; export let GlobalAliases: IMap = {}; diff --git a/src/Bladeburner.js b/src/Bladeburner.js index 7b37b9745..b5b36df72 100644 --- a/src/Bladeburner.js +++ b/src/Bladeburner.js @@ -1,34 +1,40 @@ -import { Augmentations } from "./Augmentation/Augmentations"; -import { AugmentationNames } from "./Augmentation/data/AugmentationNames"; -import { BitNodeMultipliers } from "./BitNode/BitNodeMultipliers"; -import { CONSTANTS } from "./Constants"; -import { Engine } from "./engine"; -import { Faction } from "./Faction/Faction"; -import { Factions, factionExists } from "./Faction/Factions"; -import { joinFaction, displayFactionContent } from "./Faction/FactionHelpers"; -import { Player } from "./Player"; -import { hackWorldDaemon, redPillFlag } from "./RedPill"; -import { numeralWrapper } from "./ui/numeralFormat"; -import { setTimeoutRef } from "./utils/SetTimeoutRef"; -import { KEY } from "../utils/helpers/keyCodes"; +import { Augmentations } from "./Augmentation/Augmentations"; +import { AugmentationNames } from "./Augmentation/data/AugmentationNames"; +import { BitNodeMultipliers } from "./BitNode/BitNodeMultipliers"; +import { CONSTANTS } from "./Constants"; +import { Engine } from "./engine"; +import { Faction } from "./Faction/Faction"; +import { Factions, factionExists } from "./Faction/Factions"; +import { joinFaction, displayFactionContent } from "./Faction/FactionHelpers"; +import { Player } from "./Player"; +import { hackWorldDaemon, redPillFlag } from "./RedPill"; -import { createProgressBarText } from "../utils/helpers/createProgressBarText"; -import { dialogBoxCreate } from "../utils/DialogBox"; -import { removeChildrenFromElement } from "../utils/uiHelpers/removeChildrenFromElement"; -import { Reviver, Generic_toJSON, - Generic_fromJSON } from "../utils/JSONReviver"; -import { addOffset } from "../utils/helpers/addOffset"; -import { appendLineBreaks } from "../utils/uiHelpers/appendLineBreaks"; -import { clearObject } from "../utils/helpers/clearObject"; -import { createElement } from "../utils/uiHelpers/createElement"; -import { createPopup } from "../utils/uiHelpers/createPopup"; -import { Page, routing } from "./ui/navigationTracking"; -import { exceptionAlert } from "../utils/helpers/exceptionAlert"; -import { formatNumber } from "../utils/StringHelperFunctions"; -import { getRandomInt } from "../utils/helpers/getRandomInt"; -import { getTimestamp } from "../utils/helpers/getTimestamp"; -import { removeElement } from "../utils/uiHelpers/removeElement"; -import { removeElementById } from "../utils/uiHelpers/removeElementById"; +import { Page, routing } from "./ui/navigationTracking"; +import { numeralWrapper } from "./ui/numeralFormat"; + +import { dialogBoxCreate } from "../utils/DialogBox"; +import { + Reviver, + Generic_toJSON, + Generic_fromJSON +} from "../utils/JSONReviver"; +import { setTimeoutRef } from "./utils/SetTimeoutRef"; +import { formatNumber } from "../utils/StringHelperFunctions"; + +import { addOffset } from "../utils/helpers/addOffset"; +import { clearObject } from "../utils/helpers/clearObject"; +import { createProgressBarText } from "../utils/helpers/createProgressBarText"; +import { exceptionAlert } from "../utils/helpers/exceptionAlert"; +import { getRandomInt } from "../utils/helpers/getRandomInt"; +import { getTimestamp } from "../utils/helpers/getTimestamp"; +import { KEY } from "../utils/helpers/keyCodes"; + +import { removeChildrenFromElement } from "../utils/uiHelpers/removeChildrenFromElement"; +import { appendLineBreaks } from "../utils/uiHelpers/appendLineBreaks"; +import { createElement } from "../utils/uiHelpers/createElement"; +import { createPopup } from "../utils/uiHelpers/createPopup"; +import { removeElement } from "../utils/uiHelpers/removeElement"; +import { removeElementById } from "../utils/uiHelpers/removeElementById"; const stealthIcon = ` ` const killIcon = `` diff --git a/src/CinematicText.js b/src/CinematicText.js index 32bf59bde..ae0fc2aa9 100644 --- a/src/CinematicText.js +++ b/src/CinematicText.js @@ -1,29 +1,29 @@ -import {Engine} from "./engine"; -import { setTimeoutRef } from "./utils/SetTimeoutRef"; +import { Engine } from "./engine"; +import { setTimeoutRef } from "./utils/SetTimeoutRef"; -import {removeChildrenFromElement} from "../utils/uiHelpers/removeChildrenFromElement"; -import {createElement} from "../utils/uiHelpers/createElement"; -import {exceptionAlert} from "../utils/helpers/exceptionAlert"; -import {isString} from "../utils/helpers/isString"; +import { removeChildrenFromElement } from "../utils/uiHelpers/removeChildrenFromElement"; +import { createElement } from "../utils/uiHelpers/createElement"; +import { exceptionAlert } from "../utils/helpers/exceptionAlert"; +import { isString } from "../utils/helpers/isString"; -var cinematicTextFlag = false; +export let cinematicTextFlag = false; -//Lines must be an array of strings -function writeCinematicText(lines) { +// Lines must be an array of strings +export function writeCinematicText(lines) { cinematicTextFlag = true; if (lines.constructor !== Array) { throw new Error("Invalid non-array argument passed into writeCinematicText()"); } - //We'll reuse the 'Red Pill' content + // Reuse the 'Red Pill' content Engine.loadCinematicTextContent(); - var container = document.getElementById("cinematic-text-container"); + const container = document.getElementById("cinematic-text-container"); container.style.width = "75%"; if (container == null) {throw new Error("Could not find cinematic-text-container for writeCinematicText()");} removeChildrenFromElement(container); - for (var i = 0; i < lines.length; ++i) { + for (let i = 0; i < lines.length; ++i) { if (!isString(lines[i])) { throw new Error("Invalid non-string element in 'lines' argument. writeCinematicText() failed"); } @@ -45,11 +45,11 @@ function writeCinematicTextRecurse(lines, lineNumber=0) { function writeCinematicTextLine(line) { return new Promise(function(resolve, reject) { - var container = document.getElementById("cinematic-text-container"); - var pElem = document.createElement("p"); + const container = document.getElementById("cinematic-text-container"); + const pElem = document.createElement("p"); container.appendChild(pElem); - var promise = writeCinematicTextLetter(pElem, line, 0); + const promise = writeCinematicTextLetter(pElem, line, 0); promise.then(function(res) { resolve(res); }, function(e) { @@ -61,14 +61,15 @@ function writeCinematicTextLine(line) { function writeCinematicTextLetter(pElem, line, i=0) { return new Promise(function(resolve, reject) { setTimeoutRef(function() { + const textToShow = line.substring(0, i); + if (i >= line.length) { - var textToShow = line.substring(0, i); pElem.innerHTML = textToShow; return resolve(true); } - var textToShow = line.substring(0, i); + pElem.innerHTML = textToShow + ""; - var promise = writeCinematicTextLetter(pElem, line, i+1); + const promise = writeCinematicTextLetter(pElem, line, i+1); promise.then(function(res) { resolve(res); }, function(e) { @@ -96,5 +97,3 @@ function cinematicTextEnd() { })); }); } - -export {cinematicTextFlag, writeCinematicText}; diff --git a/src/CodingContractGenerator.js b/src/CodingContractGenerator.js index 135d47863..354a2e849 100644 --- a/src/CodingContractGenerator.js +++ b/src/CodingContractGenerator.js @@ -1,12 +1,15 @@ -import { CodingContract, - CodingContractRewardType, - CodingContractTypes } from "./CodingContracts"; -import { Factions } from "./Faction/Factions"; -import { Player } from "./Player"; -import { AllServers } from "./Server/AllServers"; -import { GetServerByHostname } from "./Server/ServerHelpers"; +import { + CodingContract, + CodingContractRewardType, + CodingContractTypes +} from "./CodingContracts"; +import { Factions } from "./Faction/Factions"; +import { Player } from "./Player"; +import { AllServers } from "./Server/AllServers"; +import { GetServerByHostname } from "./Server/ServerHelpers"; + +import { getRandomInt } from "../utils/helpers/getRandomInt"; -import { getRandomInt } from "../utils/helpers/getRandomInt"; export function generateRandomContract() { // First select a random problem type diff --git a/src/CodingContracts.ts b/src/CodingContracts.ts index 8128eb934..222c8ef69 100644 --- a/src/CodingContracts.ts +++ b/src/CodingContracts.ts @@ -1,11 +1,17 @@ -import { codingContractTypesMetadata, - DescriptionFunc, - GeneratorFunc, - SolverFunc } from "./data/codingcontracttypes"; +import { + codingContractTypesMetadata, + DescriptionFunc, + GeneratorFunc, + SolverFunc +} from "./data/codingcontracttypes"; -import { IMap } from "./types"; +import { IMap } from "./types"; -import { Generic_fromJSON, Generic_toJSON, Reviver } from "../utils/JSONReviver"; +import { + Generic_fromJSON, + Generic_toJSON, + Reviver +} from "../utils/JSONReviver"; import { KEY } from "../utils/helpers/keyCodes"; import { createElement } from "../utils/uiHelpers/createElement"; import { createPopup } from "../utils/uiHelpers/createPopup"; @@ -13,6 +19,7 @@ import { removeElementById } from "../utils/uiHelpers/removeElementById"; + /* tslint:disable:no-magic-numbers completed-docs max-classes-per-file no-console */ /* Represents different types of problems that a Coding Contract can have */ diff --git a/src/Constants.ts b/src/Constants.ts index 6402b3e8a..a37ff6534 100644 --- a/src/Constants.ts +++ b/src/Constants.ts @@ -3,7 +3,7 @@ * * Constants for specific mechanics or features will NOT be here. */ -import {IMap} from "./types"; +import { IMap } from "./types"; export let CONSTANTS: IMap = { Version: "0.46.1", diff --git a/src/DevMenu.jsx b/src/DevMenu.jsx index 4b3417d79..9d3ec83cd 100644 --- a/src/DevMenu.jsx +++ b/src/DevMenu.jsx @@ -1,33 +1,35 @@ -import { AugmentationNames } from "./Augmentation/data/AugmentationNames"; -import { CodingContractTypes } from "./CodingContracts"; -import { generateContract, - generateRandomContract, - generateRandomContractOnHome } from "./CodingContractGenerator"; -import { Companies } from "./Company/Companies"; -import { Company } from "./Company/Company"; -import { Programs } from "./Programs/Programs"; -import { Factions } from "./Faction/Factions"; -import { Player } from "./Player"; -import { PlayerOwnedSourceFile } from "./SourceFile/PlayerOwnedSourceFile"; -import { AllServers } from "./Server/AllServers"; -import { GetServerByHostname } from "./Server/ServerHelpers"; -import { hackWorldDaemon } from "./RedPill"; -import { StockMarket, - SymbolToStockMap } from "./StockMarket/StockMarket"; -import { Stock } from "./StockMarket/Stock"; -import { Terminal } from "./Terminal"; +import { AugmentationNames } from "./Augmentation/data/AugmentationNames"; +import { CodingContractTypes } from "./CodingContracts"; +import { + generateContract, + generateRandomContract, + generateRandomContractOnHome +} from "./CodingContractGenerator"; +import { Companies } from "./Company/Companies"; +import { Company } from "./Company/Company"; +import { Programs } from "./Programs/Programs"; +import { Factions } from "./Faction/Factions"; +import { Player } from "./Player"; +import { PlayerOwnedSourceFile } from "./SourceFile/PlayerOwnedSourceFile"; +import { AllServers } from "./Server/AllServers"; +import { GetServerByHostname } from "./Server/ServerHelpers"; +import { hackWorldDaemon } from "./RedPill"; +import { StockMarket, SymbolToStockMap } from "./StockMarket/StockMarket"; +import { Stock } from "./StockMarket/Stock"; +import { Terminal } from "./Terminal"; -import { numeralWrapper } from "./ui/numeralFormat"; +import { numeralWrapper } from "./ui/numeralFormat"; -import { dialogBoxCreate } from "../utils/DialogBox"; -import { exceptionAlert } from "../utils/helpers/exceptionAlert"; -import { createElement } from "../utils/uiHelpers/createElement"; -import { createOptionElement } from "../utils/uiHelpers/createOptionElement"; -import { getSelectText } from "../utils/uiHelpers/getSelectData"; -import { removeElementById } from "../utils/uiHelpers/removeElementById"; +import { dialogBoxCreate } from "../utils/DialogBox"; +import { exceptionAlert } from "../utils/helpers/exceptionAlert"; +import { createElement } from "../utils/uiHelpers/createElement"; +import { createOptionElement } from "../utils/uiHelpers/createOptionElement"; +import { getSelectText } from "../utils/uiHelpers/getSelectData"; +import { removeElementById } from "../utils/uiHelpers/removeElementById"; import React from "react"; -import ReactDOM from "react-dom"; +import ReactDOM from "react-dom"; + const Component = React.Component; @@ -713,11 +715,11 @@ class DevMenuComponent extends Component { Hacking: - @@ -726,7 +728,7 @@ class DevMenuComponent extends Component { Strength: - Defense: - Dexterity: - Agility: - Charisma: - Intelligence: - Reputation: - Favor: - Reputation: - Favor: - Rank: - Cycles: - Cycles: - Cycles: - - + diff --git a/src/Gang.js b/src/Gang.js index e1cf03ab8..fcd9ddfbd 100644 --- a/src/Gang.js +++ b/src/Gang.js @@ -3,29 +3,36 @@ Also add police clashes balance point to keep them from running out of control */ -import { gangMemberTasksMetadata } from "./data/gangmembertasks"; -import { gangMemberUpgradesMetadata } from "./data/gangmemberupgrades"; +import { gangMemberTasksMetadata } from "./data/gangmembertasks"; +import { gangMemberUpgradesMetadata } from "./data/gangmemberupgrades"; + +import { Engine } from "./engine"; +import { Faction } from "./Faction/Faction"; +import { Factions } from "./Faction/Factions"; +import { displayFactionContent } from "./Faction/FactionHelpers"; + +import { Page, routing } from "./ui/navigationTracking"; +import { numeralWrapper } from "./ui/numeralFormat"; + +import { dialogBoxCreate } from "../utils/DialogBox"; +import { + Reviver, + Generic_toJSON, + Generic_fromJSON +} from "../utils/JSONReviver"; +import { formatNumber } from "../utils/StringHelperFunctions"; + +import { exceptionAlert } from "../utils/helpers/exceptionAlert"; +import { getRandomInt } from "../utils/helpers/getRandomInt"; +import { KEY } from "../utils/helpers/keyCodes"; + +import { createAccordionElement } from "../utils/uiHelpers/createAccordionElement"; +import { createElement } from "../utils/uiHelpers/createElement"; +import { createPopup } from "../utils/uiHelpers/createPopup"; +import { removeChildrenFromElement } from "../utils/uiHelpers/removeChildrenFromElement"; +import { removeElement } from "../utils/uiHelpers/removeElement"; +import { removeElementById } from "../utils/uiHelpers/removeElementById"; -import { Engine } from "./engine"; -import { Faction } from "./Faction/Faction"; -import { Factions } from "./Faction/Factions"; -import { displayFactionContent } from "./Faction/FactionHelpers"; -import { numeralWrapper } from "./ui/numeralFormat"; -import { dialogBoxCreate } from "../utils/DialogBox"; -import { Reviver, Generic_toJSON, - Generic_fromJSON } from "../utils/JSONReviver"; -import { KEY } from "../utils/helpers/keyCodes"; -import { createAccordionElement } from "../utils/uiHelpers/createAccordionElement"; -import { createElement } from "../utils/uiHelpers/createElement"; -import { createPopup } from "../utils/uiHelpers/createPopup"; -import { Page, - routing } from "./ui/navigationTracking"; -import { formatNumber } from "../utils/StringHelperFunctions"; -import { exceptionAlert } from "../utils/helpers/exceptionAlert"; -import { getRandomInt } from "../utils/helpers/getRandomInt"; -import { removeChildrenFromElement } from "../utils/uiHelpers/removeChildrenFromElement"; -import { removeElement } from "../utils/uiHelpers/removeElement"; -import { removeElementById } from "../utils/uiHelpers/removeElementById"; // Constants const GangRespectToReputationRatio = 5; // Respect is divided by this to get rep gain diff --git a/src/Infiltration.js b/src/Infiltration.js index 8997c0f18..5b78e5f86 100644 --- a/src/Infiltration.js +++ b/src/Infiltration.js @@ -1,30 +1,12 @@ -import { BitNodeMultipliers } from "./BitNode/BitNodeMultipliers"; -import { CONSTANTS } from "./Constants"; -import { Engine } from "./engine"; -import { Player } from "./Player"; -import { dialogBoxCreate } from "../utils/DialogBox"; -import { clearEventListeners } from "../utils/uiHelpers/clearEventListeners"; -import { getRandomInt } from "../utils/helpers/getRandomInt"; -import { infiltrationBoxCreate } from "../utils/InfiltrationBox"; -import { formatNumber } from "../utils/StringHelperFunctions"; - -/* Infiltration.js - * - * Kill - * Knockout (nonlethal) - * Stealth Knockout (nonlethal) - * Assassinate - * - * Hack Security - * Destroy Security - * Sneak past Security - * - * Pick the locked door - * - * Bribe security - * - * Escape - */ +import { BitNodeMultipliers } from "./BitNode/BitNodeMultipliers"; +import { CONSTANTS } from "./Constants"; +import { Engine } from "./engine"; +import { Player } from "./Player"; +import { dialogBoxCreate } from "../utils/DialogBox"; +import { clearEventListeners } from "../utils/uiHelpers/clearEventListeners"; +import { getRandomInt } from "../utils/helpers/getRandomInt"; +import { infiltrationBoxCreate } from "../utils/InfiltrationBox"; +import { formatNumber } from "../utils/StringHelperFunctions"; let InfiltrationScenarios = { Guards: "You see an armed security guard patrolling the area.", diff --git a/src/InteractiveTutorial.js b/src/InteractiveTutorial.js index 976e8aa18..81f2c0bb6 100644 --- a/src/InteractiveTutorial.js +++ b/src/InteractiveTutorial.js @@ -1,12 +1,15 @@ -import { Engine } from "./engine"; -import { Player } from "./Player"; -import { Settings } from "./Settings/Settings"; -import { initializeMainMenuLinks } from "./ui/MainMenu/Links"; -import { exceptionAlert } from "../utils/helpers/exceptionAlert"; -import { clearEventListeners } from "../utils/uiHelpers/clearEventListeners"; -import { createElement } from "../utils/uiHelpers/createElement"; -import { createPopup } from "../utils/uiHelpers/createPopup"; -import { removeElementById } from "../utils/uiHelpers/removeElementById"; +import { Engine } from "./engine"; +import { Player } from "./Player"; +import { Settings } from "./Settings/Settings"; + +import { initializeMainMenuLinks } from "./ui/MainMenu/Links"; + +import { exceptionAlert } from "../utils/helpers/exceptionAlert"; +import { clearEventListeners } from "../utils/uiHelpers/clearEventListeners"; +import { createElement } from "../utils/uiHelpers/createElement"; +import { createPopup } from "../utils/uiHelpers/createPopup"; +import { removeElementById } from "../utils/uiHelpers/removeElementById"; + //Ordered array of keys to Interactive Tutorial Steps const orderedITutorialSteps = [ diff --git a/src/Literature.js b/src/Literature.js index 67d4f517c..0bc10e109 100644 --- a/src/Literature.js +++ b/src/Literature.js @@ -1,4 +1,4 @@ -import {dialogBoxCreate} from "../utils/DialogBox"; +import { dialogBoxCreate } from "../utils/DialogBox"; /* Literature.js * Lore / world building literature that can be found on servers diff --git a/src/Missions.js b/src/Missions.js index 17b2d9378..8a446b523 100644 --- a/src/Missions.js +++ b/src/Missions.js @@ -1,14 +1,19 @@ -import { CONSTANTS } from "./Constants"; -import { Engine } from "./engine"; -import { displayFactionContent } from "./Faction/FactionHelpers"; -import { Player } from "./Player"; -import { dialogBoxCreate } from "../utils/DialogBox"; -import { clearEventListeners } from "../utils/uiHelpers/clearEventListeners"; -import { addOffset } from "../utils/helpers/addOffset"; -import { formatNumber } from "../utils/StringHelperFunctions"; -import { getRandomInt } from "../utils/helpers/getRandomInt"; -import { isString } from "../utils/helpers/isString"; -import jsplumb from 'jsplumb' +import { CONSTANTS } from "./Constants"; +import { Engine } from "./engine"; +import { displayFactionContent } from "./Faction/FactionHelpers"; +import { Player } from "./Player"; + +import { dialogBoxCreate } from "../utils/DialogBox"; +import { formatNumber } from "../utils/StringHelperFunctions"; + +import { addOffset } from "../utils/helpers/addOffset"; +import { getRandomInt } from "../utils/helpers/getRandomInt"; +import { isString } from "../utils/helpers/isString"; + +import { clearEventListeners } from "../utils/uiHelpers/clearEventListeners"; + +import jsplumb from "jsplumb"; + let inMission = false; //Flag to denote whether a mission is running let currMission = null; diff --git a/src/NetscriptBladeburner.js b/src/NetscriptBladeburner.js index 66298a6cc..61daa782f 100644 --- a/src/NetscriptBladeburner.js +++ b/src/NetscriptBladeburner.js @@ -1,6 +1,6 @@ -import {Player} from "./Player"; -import {Bladeburner} from "./Bladeburner"; -import {makeRuntimeRejectMsg} from "./NetscriptEvaluator"; +import { Player } from "./Player"; +import { Bladeburner } from "./Bladeburner"; +import { makeRuntimeRejectMsg } from "./NetscriptEvaluator"; function unknownBladeburnerActionErrorMessage(functionName, actionType, actionName) { return `ERROR: bladeburner.${functionName}() failed due to an invalid action specified. ` + diff --git a/src/NetscriptEnvironment.js b/src/NetscriptEnvironment.js index 480e4b45f..2c01abcfa 100644 --- a/src/NetscriptEnvironment.js +++ b/src/NetscriptEnvironment.js @@ -1,5 +1,5 @@ -import {NetscriptFunctions} from "./NetscriptFunctions"; -import {NetscriptPort} from "./NetscriptPort"; +import { NetscriptFunctions } from "./NetscriptFunctions"; +import { NetscriptPort } from "./NetscriptPort"; /* Environment * NetScript program environment diff --git a/src/NetscriptEvaluator.js b/src/NetscriptEvaluator.js index 6196d77bd..2321c1314 100644 --- a/src/NetscriptEvaluator.js +++ b/src/NetscriptEvaluator.js @@ -1,21 +1,21 @@ -import { BitNodeMultipliers } from "./BitNode/BitNodeMultipliers"; -import { CONSTANTS } from "./Constants"; -import { Player } from "./Player"; -import { Environment } from "./NetscriptEnvironment"; -import { WorkerScript, addWorkerScript} from "./NetscriptWorker"; -import { Server } from "./Server/Server"; -import { getServer } from "./Server/ServerHelpers"; -import { Settings } from "./Settings/Settings"; -import { RunningScript } from "./Script/RunningScript"; -import { Script } from "./Script/Script"; -import { findRunningScript } from "./Script/ScriptHelpers"; +import { BitNodeMultipliers } from "./BitNode/BitNodeMultipliers"; +import { CONSTANTS } from "./Constants"; +import { Player } from "./Player"; +import { Environment } from "./NetscriptEnvironment"; +import { WorkerScript, addWorkerScript } from "./NetscriptWorker"; +import { Server } from "./Server/Server"; +import { getServer } from "./Server/ServerHelpers"; +import { Settings } from "./Settings/Settings"; +import { RunningScript } from "./Script/RunningScript"; +import { Script } from "./Script/Script"; +import { findRunningScript } from "./Script/ScriptHelpers"; -import { setTimeoutRef } from "./utils/SetTimeoutRef"; +import { setTimeoutRef } from "./utils/SetTimeoutRef"; +import { parse, Node } from "../utils/acorn"; -import {parse, Node} from "../utils/acorn"; -import {arrayToString} from "../utils/helpers/arrayToString"; -import {isValidIPAddress} from "../utils/helpers/isValidIPAddress"; -import {isString} from "../utils/helpers/isString"; +import { arrayToString } from "../utils/helpers/arrayToString"; +import { isValidIPAddress } from "../utils/helpers/isValidIPAddress"; +import { isString } from "../utils/helpers/isString"; export function evaluateImport(exp, workerScript, checkingRam=false) { //When its checking RAM, it exports an array of nodes for each imported function diff --git a/src/NetscriptFunctions.js b/src/NetscriptFunctions.js index bb5755043..fe9ca7c76 100644 --- a/src/NetscriptFunctions.js +++ b/src/NetscriptFunctions.js @@ -1,117 +1,149 @@ -var sprintf = require('sprintf-js').sprintf, - vsprintf = require('sprintf-js').vsprintf +const sprintf = require("sprintf-js").sprintf; +const vsprintf = require("sprintf-js").vsprintf; -import {updateActiveScriptsItems} from "./ActiveScriptsUI"; -import { Augmentation } from "./Augmentation/Augmentation"; -import { Augmentations } from "./Augmentation/Augmentations"; -import { augmentationExists, - installAugmentations } from "./Augmentation/AugmentationHelpers"; -import { AugmentationNames } from "./Augmentation/data/AugmentationNames"; -import { BitNodeMultipliers } from "./BitNode/BitNodeMultipliers"; -import { findCrime } from "./Crime/CrimeHelpers"; -import {Bladeburner} from "./Bladeburner"; -import {Company} from "./Company/Company"; -import {Companies, companyExists} from "./Company/Companies"; -import {CompanyPosition} from "./Company/CompanyPosition"; -import {CompanyPositions} from "./Company/CompanyPositions"; -import {CONSTANTS} from "./Constants"; -import { DarkWebItems } from "./DarkWeb/DarkWebItems"; -import {calculateHackingChance, - calculateHackingExpGain, - calculatePercentMoneyHacked, - calculateHackingTime, - calculateGrowTime, - calculateWeakenTime} from "./Hacking"; -import {AllGangs} from "./Gang"; -import { Faction } from "./Faction/Faction"; -import { Factions, - factionExists } from "./Faction/Factions"; -import { joinFaction, - purchaseAugmentation } from "./Faction/FactionHelpers"; -import { FactionWorkType } from "./Faction/FactionWorkTypeEnum"; -import { netscriptCanGrow, - netscriptCanHack, - netscriptCanWeaken } from "./Hacking/netscriptCanHack"; +import { updateActiveScriptsItems } from "./ActiveScriptsUI"; +import { Augmentation } from "./Augmentation/Augmentation"; +import { Augmentations } from "./Augmentation/Augmentations"; +import { + augmentationExists, + installAugmentations +} from "./Augmentation/AugmentationHelpers"; +import { AugmentationNames } from "./Augmentation/data/AugmentationNames"; +import { BitNodeMultipliers } from "./BitNode/BitNodeMultipliers"; +import { findCrime } from "./Crime/CrimeHelpers"; +import { Bladeburner } from "./Bladeburner"; +import { Company } from "./Company/Company"; +import { Companies, companyExists } from "./Company/Companies"; +import { CompanyPosition } from "./Company/CompanyPosition"; +import { CompanyPositions } from "./Company/CompanyPositions"; +import { CONSTANTS } from "./Constants"; +import { DarkWebItems } from "./DarkWeb/DarkWebItems"; +import { + calculateHackingChance, + calculateHackingExpGain, + calculatePercentMoneyHacked, + calculateHackingTime, + calculateGrowTime, + calculateWeakenTime +} from "./Hacking"; +import { AllGangs } from "./Gang"; +import { Faction } from "./Faction/Faction"; +import { Factions, factionExists } from "./Faction/Factions"; +import { joinFaction, purchaseAugmentation } from "./Faction/FactionHelpers"; +import { FactionWorkType } from "./Faction/FactionWorkTypeEnum"; +import { + netscriptCanGrow, + netscriptCanHack, + netscriptCanWeaken +} from "./Hacking/netscriptCanHack"; -import { getCostOfNextHacknetNode, - getCostOfNextHacknetServer, - purchaseHacknet, - hasHacknetServers, - purchaseHashUpgrade } from "./Hacknet/HacknetHelpers"; -import { CityName } from "./Locations/data/CityNames"; -import { LocationName } from "./Locations/data/LocationNames"; +import { + getCostOfNextHacknetNode, + getCostOfNextHacknetServer, + purchaseHacknet, + hasHacknetServers, + purchaseHashUpgrade +} from "./Hacknet/HacknetHelpers"; +import { CityName } from "./Locations/data/CityNames"; +import { LocationName } from "./Locations/data/LocationNames"; -import { HacknetServer } from "./Hacknet/HacknetServer"; -import { Message } from "./Message/Message"; -import { Messages } from "./Message/MessageHelpers"; -import {inMission} from "./Missions"; -import {Player} from "./Player"; -import { Programs } from "./Programs/Programs"; -import { Script } from "./Script/Script"; -import { findRunningScript } from "./Script/ScriptHelpers"; -import { isScriptFilename } from "./Script/ScriptHelpersTS"; -import { AllServers, - AddToAllServers } from "./Server/AllServers"; -import { Server } from "./Server/Server"; -import { GetServerByHostname, - getServer, - getServerOnNetwork, - numCycleForGrowth, - processSingleServerGrowth } from "./Server/ServerHelpers"; -import { getPurchaseServerCost, - getPurchaseServerLimit, - getPurchaseServerMaxRam } from "./Server/ServerPurchases"; -import {Settings} from "./Settings/Settings"; -import {SpecialServerIps} from "./Server/SpecialServerIps"; -import {Stock} from "./StockMarket/Stock"; -import {StockMarket, StockSymbols, SymbolToStockMap, - initStockMarket, initSymbolToStockMap, buyStock, - sellStock, updateStockPlayerPosition, - shortStock, sellShort, OrderTypes, - PositionTypes, placeOrder, cancelOrder} from "./StockMarket/StockMarket"; -import { getStockmarket4SDataCost, - getStockMarket4STixApiCost } from "./StockMarket/StockMarketCosts"; -import { SourceFileFlags } from "./SourceFile/SourceFileFlags" -import {TextFile, getTextFile, createTextFile} from "./TextFile"; +import { HacknetServer } from "./Hacknet/HacknetServer"; +import { Message } from "./Message/Message"; +import { Messages } from "./Message/MessageHelpers"; +import { inMission } from "./Missions"; +import { Player } from "./Player"; +import { Programs } from "./Programs/Programs"; +import { Script } from "./Script/Script"; +import { findRunningScript } from "./Script/ScriptHelpers"; +import { isScriptFilename } from "./Script/ScriptHelpersTS"; +import { AllServers, AddToAllServers } from "./Server/AllServers"; +import { Server } from "./Server/Server"; +import { + GetServerByHostname, + getServer, + getServerOnNetwork, + numCycleForGrowth, + processSingleServerGrowth +} from "./Server/ServerHelpers"; +import { + getPurchaseServerCost, + getPurchaseServerLimit, + getPurchaseServerMaxRam +} from "./Server/ServerPurchases"; +import { Settings } from "./Settings/Settings"; +import { SpecialServerIps } from "./Server/SpecialServerIps"; +import { Stock } from "./StockMarket/Stock"; +import { + StockMarket, + StockSymbols, + SymbolToStockMap, + initStockMarket, + initSymbolToStockMap, + buyStock, + sellStock, + updateStockPlayerPosition, + shortStock, + sellShort, + OrderTypes, + PositionTypes, + placeOrder, + cancelOrder +} from "./StockMarket/StockMarket"; +import { + getStockmarket4SDataCost, + getStockMarket4STixApiCost +} from "./StockMarket/StockMarketCosts"; +import { SourceFileFlags } from "./SourceFile/SourceFileFlags"; +import { TextFile, getTextFile, createTextFile } from "./TextFile"; -import {unknownBladeburnerActionErrorMessage, - unknownBladeburnerExceptionMessage, - checkBladeburnerAccess} from "./NetscriptBladeburner"; -import * as nsGang from "./NetscriptGang"; -import {WorkerScript, workerScripts, - killWorkerScript, NetscriptPorts} from "./NetscriptWorker"; -import {makeRuntimeRejectMsg, netscriptDelay, - runScriptFromScript} from "./NetscriptEvaluator"; -import {NetscriptPort} from "./NetscriptPort"; -import { SleeveTaskType } from "./PersonObjects/Sleeve/SleeveTaskTypesEnum"; -import { findSleevePurchasableAugs } from "./PersonObjects/Sleeve/Sleeve"; +import { + unknownBladeburnerActionErrorMessage, + unknownBladeburnerExceptionMessage, + checkBladeburnerAccess +} from "./NetscriptBladeburner"; +import * as nsGang from "./NetscriptGang"; +import { + WorkerScript, + workerScripts, + killWorkerScript, + NetscriptPorts +} from "./NetscriptWorker"; +import { + makeRuntimeRejectMsg, + netscriptDelay, + runScriptFromScript +} from "./NetscriptEvaluator"; +import { NetscriptPort } from "./NetscriptPort"; +import { SleeveTaskType } from "./PersonObjects/Sleeve/SleeveTaskTypesEnum"; +import { findSleevePurchasableAugs } from "./PersonObjects/Sleeve/Sleeve"; -import {Page, routing} from "./ui/navigationTracking"; -import {numeralWrapper} from "./ui/numeralFormat"; -import {post} from "./ui/postToTerminal"; -import { setTimeoutRef } from "./utils/SetTimeoutRef"; -import { is2DArray } from "./utils/helpers/is2DArray"; +import { Page, routing } from "./ui/navigationTracking"; +import { numeralWrapper } from "./ui/numeralFormat"; +import { post } from "./ui/postToTerminal"; +import { setTimeoutRef } from "./utils/SetTimeoutRef"; +import { is2DArray } from "./utils/helpers/is2DArray"; -import {dialogBoxCreate} from "../utils/DialogBox"; -import {isPowerOfTwo} from "../utils/helpers/isPowerOfTwo"; -import {arrayToString} from "../utils/helpers/arrayToString"; -import {createRandomIp} from "../utils/IPAddress"; -import {formatNumber, isHTML} from "../utils/StringHelperFunctions"; -import {isString} from "../utils/helpers/isString"; +import { dialogBoxCreate } from "../utils/DialogBox"; +import { isPowerOfTwo } from "../utils/helpers/isPowerOfTwo"; +import { arrayToString } from "../utils/helpers/arrayToString"; +import { createRandomIp } from "../utils/IPAddress"; +import { formatNumber, isHTML } from "../utils/StringHelperFunctions"; +import { isString } from "../utils/helpers/isString"; -import { createElement } from "../utils/uiHelpers/createElement"; -import { createPopup } from "../utils/uiHelpers/createPopup"; -import { removeElementById } from "../utils/uiHelpers/removeElementById"; +import { createElement } from "../utils/uiHelpers/createElement"; +import { createPopup } from "../utils/uiHelpers/createPopup"; +import { removeElementById } from "../utils/uiHelpers/removeElementById"; -var hasCorporationSF = false, //Source-File 3 - hasSingularitySF = false, //Source-File 4 - hasAISF = false, //Source-File 5 - hasBladeburnerSF = false, //Source-File 6 - hasBladeburner2079SF = false, //Source-File 7 - hasWallStreetSF = false, //Source-File 8 - 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 -var singularitySFLvl=1, wallStreetSFLvl=1; +let singularitySFLvl = 1; +let wallStreetSFLvl = 1; var possibleLogs = { ALL: true, diff --git a/src/NetscriptGang.js b/src/NetscriptGang.js index 638bba084..1fce46666 100644 --- a/src/NetscriptGang.js +++ b/src/NetscriptGang.js @@ -1,6 +1,6 @@ -import {Player} from "./Player"; -import {Gang} from "./Gang"; -import {makeRuntimeRejectMsg} from "./NetscriptEvaluator"; +import { Player } from "./Player"; +import { Gang } from "./Gang"; +import { makeRuntimeRejectMsg } from "./NetscriptEvaluator"; export function unknownGangApiExceptionMessage(functionName, err) { return `gang.${functionName}() failed with exception: ` + err; diff --git a/src/NetscriptJSEvaluator.js b/src/NetscriptJSEvaluator.js index dc2606968..0f8032f90 100644 --- a/src/NetscriptJSEvaluator.js +++ b/src/NetscriptJSEvaluator.js @@ -1,4 +1,4 @@ -import {makeRuntimeRejectMsg} from "./NetscriptEvaluator"; +import { makeRuntimeRejectMsg } from "./NetscriptEvaluator"; // Makes a blob that contains the code of a given script. export function makeScriptBlob(code) { diff --git a/src/NetscriptPort.js b/src/NetscriptPort.js index 5820c77bf..df5fa842d 100644 --- a/src/NetscriptPort.js +++ b/src/NetscriptPort.js @@ -1,4 +1,4 @@ -import {Settings} from "./Settings/Settings"; +import { Settings } from "./Settings/Settings"; function NetscriptPort() { this.data = []; diff --git a/src/NetscriptWorker.js b/src/NetscriptWorker.js index e698166f8..7dcba4852 100644 --- a/src/NetscriptWorker.js +++ b/src/NetscriptWorker.js @@ -1,28 +1,34 @@ -import {addActiveScriptsItem, - deleteActiveScriptsItem, - updateActiveScriptsItems} from "./ActiveScriptsUI"; -import {CONSTANTS} from "./Constants"; -import {Engine} from "./engine"; -import {Interpreter} from "./JSInterpreter"; -import {Environment} from "./NetscriptEnvironment"; -import {evaluate, isScriptErrorMessage, - makeRuntimeRejectMsg, - killNetscriptDelay} from "./NetscriptEvaluator"; -import {NetscriptFunctions} from "./NetscriptFunctions"; -import {executeJSScript} from "./NetscriptJSEvaluator"; -import {NetscriptPort} from "./NetscriptPort"; -import { AllServers } from "./Server/AllServers"; -import {Settings} from "./Settings/Settings"; -import { setTimeoutRef } from "./utils/SetTimeoutRef"; +import { + addActiveScriptsItem, + deleteActiveScriptsItem, + updateActiveScriptsItems +} from "./ActiveScriptsUI"; +import { CONSTANTS } from "./Constants"; +import { Engine } from "./engine"; +import { Interpreter } from "./JSInterpreter"; +import { Environment } from "./NetscriptEnvironment"; +import { + evaluate, + isScriptErrorMessage, + makeRuntimeRejectMsg, + killNetscriptDelay +} from "./NetscriptEvaluator"; +import { NetscriptFunctions } from "./NetscriptFunctions"; +import { executeJSScript } from "./NetscriptJSEvaluator"; +import { NetscriptPort } from "./NetscriptPort"; +import { AllServers } from "./Server/AllServers"; +import { Settings } from "./Settings/Settings"; +import { setTimeoutRef } from "./utils/SetTimeoutRef"; -import {generate} from 'escodegen'; +import { generate } from "escodegen"; + +import { parse, Node } from "../utils/acorn"; +import { dialogBoxCreate } from "../utils/DialogBox"; +import { compareArrays } from "../utils/helpers/compareArrays"; +import { arrayToString } from "../utils/helpers/arrayToString"; +import { roundToTwo } from "../utils/helpers/roundToTwo"; +import { isString } from "../utils/StringHelperFunctions"; -import {parse, Node} from "../utils/acorn"; -import {dialogBoxCreate} from "../utils/DialogBox"; -import {compareArrays} from "../utils/helpers/compareArrays"; -import {arrayToString} from "../utils/helpers/arrayToString"; -import {roundToTwo} from "../utils/helpers/roundToTwo"; -import {isString} from "../utils/StringHelperFunctions"; const walk = require("acorn/dist/walk"); diff --git a/src/Prestige.js b/src/Prestige.js index 98ba2d6b0..8eaab913e 100755 --- a/src/Prestige.js +++ b/src/Prestige.js @@ -1,55 +1,68 @@ -import {deleteActiveScriptsItem} from "./ActiveScriptsUI"; -import { Augmentations } from "./Augmentation/Augmentations"; -import { augmentationExists, - initAugmentations } from "./Augmentation/AugmentationHelpers"; -import { AugmentationNames } from "./Augmentation/data/AugmentationNames"; -import { initBitNodeMultipliers } from "./BitNode/BitNode"; -import {Bladeburner} from "./Bladeburner"; -import {writeCinematicText} from "./CinematicText"; -import {Companies, initCompanies} from "./Company/Companies"; -import { resetIndustryResearchTrees } from "./Corporation/IndustryData"; -import { Programs } from "./Programs/Programs"; -import {Engine} from "./engine"; -import { Faction } from "./Faction/Faction"; -import { Factions, - initFactions } from "./Faction/Factions"; -import { joinFaction } from "./Faction/FactionHelpers"; -import {deleteGangDisplayContent} from "./Gang"; -import { Message } from "./Message/Message"; -import { initMessages, - Messages } from "./Message/MessageHelpers"; -import {initSingularitySFFlags, hasWallStreetSF}from "./NetscriptFunctions"; -import {WorkerScript, workerScripts, - prestigeWorkerScripts} from "./NetscriptWorker"; -import {Player} from "./Player"; +import { deleteActiveScriptsItem } from "./ActiveScriptsUI"; +import { Augmentations } from "./Augmentation/Augmentations"; +import { + augmentationExists, + initAugmentations +} from "./Augmentation/AugmentationHelpers"; +import { AugmentationNames } from "./Augmentation/data/AugmentationNames"; +import { initBitNodeMultipliers } from "./BitNode/BitNode"; +import { Bladeburner } from "./Bladeburner"; +import { writeCinematicText } from "./CinematicText"; +import { Companies, initCompanies } from "./Company/Companies"; +import { resetIndustryResearchTrees } from "./Corporation/IndustryData"; +import { Programs } from "./Programs/Programs"; +import { Engine } from "./engine"; +import { Faction } from "./Faction/Faction"; +import { Factions, initFactions } from "./Faction/Factions"; +import { joinFaction } from "./Faction/FactionHelpers"; +import { deleteGangDisplayContent } from "./Gang"; +import { Message } from "./Message/Message"; +import { initMessages, Messages } from "./Message/MessageHelpers"; +import { initSingularitySFFlags, hasWallStreetSF } from "./NetscriptFunctions"; +import { + WorkerScript, + workerScripts, + prestigeWorkerScripts +} from "./NetscriptWorker"; +import { Player } from "./Player"; -import { AllServers, - AddToAllServers, - initForeignServers, - prestigeAllServers } from "./Server/AllServers"; -import { Server } from "./Server/Server" -import { prestigeHomeComputer } from "./Server/ServerHelpers"; -import { SourceFileFlags, - updateSourceFileFlags } from "./SourceFile/SourceFileFlags"; -import { SpecialServerIps, - SpecialServerIpsMap, - prestigeSpecialServerIps, - SpecialServerNames} from "./Server/SpecialServerIps"; -import {initStockMarket, initSymbolToStockMap, - stockMarketContentCreated, - setStockMarketContentCreated} from "./StockMarket/StockMarket"; -import {Terminal, postNetburnerText} from "./Terminal"; +import { + AllServers, + AddToAllServers, + initForeignServers, + prestigeAllServers +} from "./Server/AllServers"; +import { Server } from "./Server/Server"; +import { prestigeHomeComputer } from "./Server/ServerHelpers"; +import { + SourceFileFlags, + updateSourceFileFlags +} from "./SourceFile/SourceFileFlags"; +import { + SpecialServerIps, + SpecialServerIpsMap, + prestigeSpecialServerIps, + SpecialServerNames +} from "./Server/SpecialServerIps"; +import { + initStockMarket, + initSymbolToStockMap, + stockMarketContentCreated, + setStockMarketContentCreated +} from "./StockMarket/StockMarket"; +import { Terminal, postNetburnerText } from "./Terminal"; -import {Page, routing} from "./ui/navigationTracking"; +import { Page, routing } from "./ui/navigationTracking"; -import Decimal from "decimal.js"; -import {dialogBoxCreate} from "../utils/DialogBox"; -import {removeElementById} from "../utils/uiHelpers/removeElementById"; -import {createElement} from "../utils/uiHelpers/createElement"; -import {createPopup} from "../utils/uiHelpers/createPopup"; -import {exceptionAlert} from "../utils/helpers/exceptionAlert"; +import { dialogBoxCreate } from "../utils/DialogBox"; +import { exceptionAlert } from "../utils/helpers/exceptionAlert"; +import { removeElementById } from "../utils/uiHelpers/removeElementById"; +import { createElement } from "../utils/uiHelpers/createElement"; +import { createPopup } from "../utils/uiHelpers/createPopup"; -let BitNode8StartingMoney = 250e6; +import Decimal from "decimal.js"; + +const BitNode8StartingMoney = 250e6; //Prestige by purchasing augmentation function prestigeAugmentation() { diff --git a/src/RedPill.js b/src/RedPill.js index 5420e43c5..f0e701d37 100644 --- a/src/RedPill.js +++ b/src/RedPill.js @@ -1,18 +1,22 @@ -import { BitNodes } from "./BitNode/BitNode"; -import { Engine } from "./engine"; -import { Player } from "./Player"; -import { prestigeSourceFile } from "./Prestige"; -import { SourceFiles, - SourceFile } from "./SourceFile"; -import { PlayerOwnedSourceFile } from "./SourceFile/PlayerOwnedSourceFile"; -import { Terminal } from "./Terminal"; -import { setTimeoutRef } from "./utils/SetTimeoutRef"; +import { BitNodes } from "./BitNode/BitNode"; +import { Engine } from "./engine"; +import { Player } from "./Player"; +import { prestigeSourceFile } from "./Prestige"; +import { SourceFiles, SourceFile } from "./SourceFile"; +import { PlayerOwnedSourceFile } from "./SourceFile/PlayerOwnedSourceFile"; +import { Terminal } from "./Terminal"; +import { setTimeoutRef } from "./utils/SetTimeoutRef"; + +import { dialogBoxCreate } from "../utils/DialogBox"; +import { + yesNoBoxCreate, + yesNoBoxGetYesButton, + yesNoBoxGetNoButton, + yesNoBoxClose +} from "../utils/YesNoBox"; +import { clearEventListeners } from "../utils/uiHelpers/clearEventListeners"; +import { removeChildrenFromElement } from "../utils/uiHelpers/removeChildrenFromElement"; -import {clearEventListeners} from "../utils/uiHelpers/clearEventListeners"; -import {dialogBoxCreate} from "../utils/DialogBox"; -import {removeChildrenFromElement} from "../utils/uiHelpers/removeChildrenFromElement"; -import {yesNoBoxCreate, yesNoBoxGetYesButton, - yesNoBoxGetNoButton, yesNoBoxClose} from "../utils/YesNoBox"; /* RedPill.js * Implements what happens when you have Red Pill augmentation and then hack the world daemon */ diff --git a/src/SaveObject.js b/src/SaveObject.js index d382765c9..0f2606198 100755 --- a/src/SaveObject.js +++ b/src/SaveObject.js @@ -1,41 +1,52 @@ -import {loadAliases, loadGlobalAliases, - Aliases, GlobalAliases} from "./Alias"; -import {Companies, loadCompanies} from "./Company/Companies"; -import {CompanyPosition} from "./Company/CompanyPosition"; -import {CONSTANTS} from "./Constants"; -import {Engine} from "./engine"; -import { Factions, - loadFactions } from "./Faction/Factions"; -import { processPassiveFactionRepGain } from "./Faction/FactionHelpers"; -import { loadFconf } from "./Fconf/Fconf"; -import { FconfSettings } from "./Fconf/FconfSettings"; -import {loadAllGangs, AllGangs} from "./Gang"; -import { hasHacknetServers, - processHacknetEarnings } from "./Hacknet/HacknetHelpers"; +import { + loadAliases, + loadGlobalAliases, + Aliases, + GlobalAliases +} from "./Alias"; +import { Companies, loadCompanies } from "./Company/Companies"; +import { CompanyPosition } from "./Company/CompanyPosition"; +import { CONSTANTS } from "./Constants"; +import { Engine } from "./engine"; +import { Factions, loadFactions } from "./Faction/Factions"; +import { processPassiveFactionRepGain } from "./Faction/FactionHelpers"; +import { loadFconf } from "./Fconf/Fconf"; +import { FconfSettings } from "./Fconf/FconfSettings"; +import { loadAllGangs, AllGangs } from "./Gang"; +import { + hasHacknetServers, + processHacknetEarnings +} from "./Hacknet/HacknetHelpers"; import { loadMessages, initMessages, Messages } from "./Message/MessageHelpers"; -import {Player, loadPlayer} from "./Player"; -import { loadAllRunningScripts } from "./Script/ScriptHelpers"; -import { AllServers, - loadAllServers } from "./Server/AllServers"; -import { Settings } from "./Settings/Settings"; -import { loadSpecialServerIps, - SpecialServerIps } from "./Server/SpecialServerIps"; -import {loadStockMarket, StockMarket} from "./StockMarket/StockMarket"; -import { setTimeoutRef } from "./utils/SetTimeoutRef"; +import { Player, loadPlayer } from "./Player"; +import { loadAllRunningScripts } from "./Script/ScriptHelpers"; +import { AllServers, loadAllServers } from "./Server/AllServers"; +import { Settings } from "./Settings/Settings"; +import { + loadSpecialServerIps, + SpecialServerIps +} from "./Server/SpecialServerIps"; +import { loadStockMarket, StockMarket } from "./StockMarket/StockMarket"; -import {dialogBoxCreate} from "../utils/DialogBox"; -import {gameOptionsBoxClose} from "../utils/GameOptions"; -import {clearEventListeners} from "../utils/uiHelpers/clearEventListeners"; -import {Reviver, Generic_toJSON, - Generic_fromJSON} from "../utils/JSONReviver"; -import { convertTimeMsToTimeElapsedString } from "../utils/StringHelperFunctions"; -import {createElement} from "../utils/uiHelpers/createElement"; -import {createPopup} from "../utils/uiHelpers/createPopup"; -import {createStatusText} from "./ui/createStatusText"; -import {numeralWrapper} from "./ui/numeralFormat"; -import {removeElementById} from "../utils/uiHelpers/removeElementById"; +import { createStatusText } from "./ui/createStatusText"; +import { numeralWrapper } from "./ui/numeralFormat"; -import Decimal from "decimal.js"; +import { setTimeoutRef } from "./utils/SetTimeoutRef"; + +import { dialogBoxCreate } from "../utils/DialogBox"; +import { gameOptionsBoxClose } from "../utils/GameOptions"; +import { convertTimeMsToTimeElapsedString } from "../utils/StringHelperFunctions"; +import { clearEventListeners } from "../utils/uiHelpers/clearEventListeners"; +import { + Reviver, + Generic_toJSON, + Generic_fromJSON +} from "../utils/JSONReviver"; +import { createElement } from "../utils/uiHelpers/createElement"; +import { createPopup } from "../utils/uiHelpers/createPopup"; +import { removeElementById } from "../utils/uiHelpers/removeElementById"; + +import Decimal from "decimal.js"; /* SaveObject.js * Defines the object used to save/load games diff --git a/src/Terminal.js b/src/Terminal.js index 544c9e602..76516c6b3 100644 --- a/src/Terminal.js +++ b/src/Terminal.js @@ -8,77 +8,85 @@ import { removeLeadingSlash, removeTrailingSlash } from "./Terminal/DirectoryHelpers"; +import { determineAllPossibilitiesForTabCompletion } from "./Terminal/determineAllPossibilitiesForTabCompletion"; +import { TerminalHelpText, HelpTexts } from "./Terminal/HelpText"; +import { tabCompletion } from "./Terminal/tabCompletion"; import { - determineAllPossibilitiesForTabCompletion -} from "./Terminal/determineAllPossibilitiesForTabCompletion"; - + Aliases, + GlobalAliases, + parseAliasDeclaration, + printAliases, + removeAlias, + substituteAliases +} from "./Alias"; +import { BitNodeMultipliers } from "./BitNode/BitNodeMultipliers"; import { - TerminalHelpText, - HelpTexts -} from "./Terminal/HelpText"; - + CodingContract, + CodingContractResult, + CodingContractRewardType +} from "./CodingContracts"; +import { CONSTANTS } from "./Constants"; +import { Programs } from "./Programs/Programs"; import { - tabCompletion -} from "./Terminal/tabCompletion"; - -import { Aliases, - GlobalAliases, - parseAliasDeclaration, - printAliases, - removeAlias, - substituteAliases } from "./Alias"; -import { BitNodeMultipliers } from "./BitNode/BitNodeMultipliers"; -import {CodingContract, CodingContractResult, - CodingContractRewardType} from "./CodingContracts"; -import {CONSTANTS} from "./Constants"; -import { Programs } from "./Programs/Programs"; -import { executeDarkwebTerminalCommand, - checkIfConnectedToDarkweb } from "./DarkWeb/DarkWeb"; -import { DarkWebItems } from "./DarkWeb/DarkWebItems"; -import {Engine} from "./engine"; -import { parseFconfSettings, - createFconf } from "./Fconf/Fconf"; -import { FconfSettings } from "./Fconf/FconfSettings"; -import {calculateHackingChance, - calculateHackingExpGain, - calculatePercentMoneyHacked, - calculateHackingTime, - calculateGrowTime, - calculateWeakenTime} from "./Hacking"; -import { HacknetServer } from "./Hacknet/HacknetServer"; -import {iTutorialNextStep, iTutorialSteps, - ITutorial} from "./InteractiveTutorial"; -import {showLiterature} from "./Literature"; -import { Message } from "./Message/Message"; -import { showMessage } from "./Message/MessageHelpers"; -import {killWorkerScript, addWorkerScript} from "./NetscriptWorker"; -import {Player} from "./Player"; -import {hackWorldDaemon} from "./RedPill"; -import { RunningScript } from "./Script/RunningScript"; -import { findRunningScript } from "./Script/ScriptHelpers"; -import { isScriptFilename } from "./Script/ScriptHelpersTS"; -import { AllServers } from "./Server/AllServers"; -import { Server } from "./Server/Server"; -import { GetServerByHostname, - getServer, - getServerOnNetwork } from "./Server/ServerHelpers"; -import {Settings} from "./Settings/Settings"; -import { SpecialServerIps, - SpecialServerNames } from "./Server/SpecialServerIps"; -import {getTextFile} from "./TextFile"; -import { setTimeoutRef } from "./utils/SetTimeoutRef"; -import {Page, routing} from "./ui/navigationTracking"; -import {numeralWrapper} from "./ui/numeralFormat"; -import {KEY} from "../utils/helpers/keyCodes"; -import {addOffset} from "../utils/helpers/addOffset"; -import {isString} from "../utils/helpers/isString"; -import {arrayToString} from "../utils/helpers/arrayToString"; -import {getTimestamp} from "../utils/helpers/getTimestamp"; -import {logBoxCreate} from "../utils/LogBox"; -import {yesNoBoxCreate, - yesNoBoxGetYesButton, - yesNoBoxGetNoButton, yesNoBoxClose} from "../utils/YesNoBox"; + executeDarkwebTerminalCommand, + checkIfConnectedToDarkweb +} from "./DarkWeb/DarkWeb"; +import { DarkWebItems } from "./DarkWeb/DarkWebItems"; +import { Engine } from "./engine"; +import { parseFconfSettings, createFconf } from "./Fconf/Fconf"; +import { FconfSettings } from "./Fconf/FconfSettings"; +import { + calculateHackingChance, + calculateHackingExpGain, + calculatePercentMoneyHacked, + calculateHackingTime, + calculateGrowTime, + calculateWeakenTime +} from "./Hacking"; +import { HacknetServer } from "./Hacknet/HacknetServer"; +import { + iTutorialNextStep, + iTutorialSteps, + ITutorial +} from "./InteractiveTutorial"; +import { showLiterature } from "./Literature"; +import { Message } from "./Message/Message"; +import { showMessage } from "./Message/MessageHelpers"; +import { killWorkerScript, addWorkerScript } from "./NetscriptWorker"; +import { Player } from "./Player"; +import { hackWorldDaemon } from "./RedPill"; +import { RunningScript } from "./Script/RunningScript"; +import { findRunningScript } from "./Script/ScriptHelpers"; +import { isScriptFilename } from "./Script/ScriptHelpersTS"; +import { AllServers } from "./Server/AllServers"; +import { Server } from "./Server/Server"; +import { + GetServerByHostname, + getServer, + getServerOnNetwork +} from "./Server/ServerHelpers"; +import { Settings } from "./Settings/Settings"; +import { + SpecialServerIps, + SpecialServerNames +} from "./Server/SpecialServerIps"; +import { getTextFile } from "./TextFile"; +import { setTimeoutRef } from "./utils/SetTimeoutRef"; +import { Page, routing } from "./ui/navigationTracking"; +import { numeralWrapper } from "./ui/numeralFormat"; +import { KEY } from "../utils/helpers/keyCodes"; +import { addOffset } from "../utils/helpers/addOffset"; +import { isString } from "../utils/helpers/isString"; +import { arrayToString } from "../utils/helpers/arrayToString"; +import { getTimestamp } from "../utils/helpers/getTimestamp"; +import { logBoxCreate } from "../utils/LogBox"; +import { + yesNoBoxCreate, + yesNoBoxGetYesButton, + yesNoBoxGetNoButton, + yesNoBoxClose +} from "../utils/YesNoBox"; import { post, postContent, @@ -87,9 +95,10 @@ import { hackProgressPost } from "./ui/postToTerminal"; -import autosize from 'autosize'; -import * as JSZip from 'jszip'; -import * as FileSaver from 'file-saver'; +import autosize from "autosize"; +import * as JSZip from "jszip"; +import * as FileSaver from "file-saver"; + function postNetburnerText() { post("Bitburner v" + CONSTANTS.Version); diff --git a/src/TextFile.ts b/src/TextFile.ts index 74254fff2..0e5a6bd3e 100644 --- a/src/TextFile.ts +++ b/src/TextFile.ts @@ -1,6 +1,11 @@ import { setTimeoutRef } from "./utils/SetTimeoutRef"; import { dialogBoxCreate } from "../utils/DialogBox"; -import { Generic_fromJSON, Generic_toJSON, Reviver } from "../utils/JSONReviver"; +import { + Generic_fromJSON, + Generic_toJSON, + Reviver +} from "../utils/JSONReviver"; + /** * Represents a plain text file that is typically stored on a server. diff --git a/src/engine.jsx b/src/engine.jsx index d7cd68d36..3613d73b9 100644 --- a/src/engine.jsx +++ b/src/engine.jsx @@ -1,104 +1,129 @@ -import {formatNumber, - convertTimeMsToTimeElapsedString, - replaceAt} from "../utils/StringHelperFunctions"; -import {loxBoxCreate, logBoxUpdateText, - logBoxOpened} from "../utils/LogBox"; -import {updateActiveScriptsItems} from "./ActiveScriptsUI"; -import { Augmentations } from "./Augmentation/Augmentations"; -import { installAugmentations, - initAugmentations, - displayAugmentationsContent, - PlayerOwnedAugmentation } from "./Augmentation/AugmentationHelpers"; -import { AugmentationNames } from "./Augmentation/data/AugmentationNames"; +import { + formatNumber, + convertTimeMsToTimeElapsedString, + replaceAt +} from "../utils/StringHelperFunctions"; +import { loxBoxCreate, logBoxUpdateText, logBoxOpened } from "../utils/LogBox"; +import { updateActiveScriptsItems } from "./ActiveScriptsUI"; +import { Augmentations } from "./Augmentation/Augmentations"; +import { + installAugmentations, + initAugmentations, + displayAugmentationsContent, + PlayerOwnedAugmentation +} from "./Augmentation/AugmentationHelpers"; +import { AugmentationNames } from "./Augmentation/data/AugmentationNames"; -import {BitNodes, initBitNodes, - initBitNodeMultipliers} from "./BitNode/BitNode"; -import {Bladeburner} from "./Bladeburner"; -import { CharacterOverviewComponent } from "./ui/React/CharacterOverview"; -import {cinematicTextFlag} from "./CinematicText"; -import {generateRandomContract} from "./CodingContractGenerator"; -import {CompanyPositions} from "./Company/CompanyPositions"; -import {initCompanies} from "./Company/Companies"; -import { Corporation } from "./Corporation/Corporation"; -import {CONSTANTS} from "./Constants"; -import {createDevMenu, closeDevMenu} from "./DevMenu"; -import { Factions, initFactions } from "./Faction/Factions"; -import { displayFactionContent, joinFaction, - processPassiveFactionRepGain, - inviteToFaction } from "./Faction/FactionHelpers"; -import { FconfSettings } from "./Fconf/FconfSettings"; -import { hasHacknetServers, - renderHacknetNodesUI, - clearHacknetNodesUI, - processHacknetEarnings } from "./Hacknet/HacknetHelpers"; -import {iTutorialStart} from "./InteractiveTutorial"; -import {initLiterature} from "./Literature"; -import { LocationName } from "./Locations/data/LocationNames"; -import { LocationRoot } from "./Locations/ui/Root"; -import { checkForMessagesToSend, initMessages } from "./Message/MessageHelpers"; -import {inMission, currMission} from "./Missions"; -import {initSingularitySFFlags, - hasSingularitySF, hasCorporationSF} from "./NetscriptFunctions"; -import {updateOnlineScriptTimes, - runScriptsLoop} from "./NetscriptWorker"; -import {Player} from "./Player"; -import {prestigeAugmentation, - prestigeSourceFile} from "./Prestige"; -import { Programs } from "./Programs/Programs"; -import { displayCreateProgramContent, - getNumAvailableCreateProgram, - initCreateProgramButtons } from "./Programs/ProgramHelpers"; -import {redPillFlag, hackWorldDaemon} from "./RedPill"; -import {saveObject, loadGame} from "./SaveObject"; -import { getCurrentEditor, - loadAllRunningScripts, - scriptEditorInit, - updateScriptEditorContent } from "./Script/ScriptHelpers"; -import { AllServers, - initForeignServers } from "./Server/AllServers"; +import { + BitNodes, + initBitNodes, + initBitNodeMultipliers +} from "./BitNode/BitNode"; +import { Bladeburner } from "./Bladeburner"; +import { CharacterOverviewComponent } from "./ui/React/CharacterOverview"; +import { cinematicTextFlag } from "./CinematicText"; +import { generateRandomContract } from "./CodingContractGenerator"; +import { CompanyPositions } from "./Company/CompanyPositions"; +import { initCompanies } from "./Company/Companies"; +import { Corporation } from "./Corporation/Corporation"; +import { CONSTANTS } from "./Constants"; +import { createDevMenu, closeDevMenu } from "./DevMenu"; +import { Factions, initFactions } from "./Faction/Factions"; +import { + displayFactionContent, + joinFaction, + processPassiveFactionRepGain, + inviteToFaction +} from "./Faction/FactionHelpers"; +import { FconfSettings } from "./Fconf/FconfSettings"; +import { + hasHacknetServers, + renderHacknetNodesUI, + clearHacknetNodesUI, + processHacknetEarnings +} from "./Hacknet/HacknetHelpers"; +import { iTutorialStart } from "./InteractiveTutorial"; +import { initLiterature } from "./Literature"; +import { LocationName } from "./Locations/data/LocationNames"; +import { LocationRoot } from "./Locations/ui/Root"; +import { checkForMessagesToSend, initMessages } from "./Message/MessageHelpers"; +import { inMission, currMission } from "./Missions"; +import { + initSingularitySFFlags, + hasSingularitySF, + hasCorporationSF +} from "./NetscriptFunctions"; +import { updateOnlineScriptTimes, runScriptsLoop } from "./NetscriptWorker"; +import { Player } from "./Player"; +import { prestigeAugmentation, prestigeSourceFile } from "./Prestige"; +import { Programs } from "./Programs/Programs"; +import { + displayCreateProgramContent, + getNumAvailableCreateProgram, + initCreateProgramButtons +} from "./Programs/ProgramHelpers"; +import { redPillFlag, hackWorldDaemon } from "./RedPill"; +import { saveObject, loadGame } from "./SaveObject"; +import { + getCurrentEditor, + loadAllRunningScripts, + scriptEditorInit, + updateScriptEditorContent +} from "./Script/ScriptHelpers"; +import { AllServers, initForeignServers } from "./Server/AllServers"; -import { Server } from "./Server/Server"; -import {Settings} from "./Settings/Settings"; -import { initSourceFiles, SourceFiles } from "./SourceFile"; -import { updateSourceFileFlags } from "./SourceFile/SourceFileFlags"; -import {SpecialServerIps, initSpecialServerIps} from "./Server/SpecialServerIps"; -import {StockMarket, StockSymbols, - SymbolToStockMap, initStockSymbols, - initSymbolToStockMap, stockMarketCycle, - processStockPrices, - displayStockMarketContent} from "./StockMarket/StockMarket"; -import {Terminal, postNetburnerText} from "./Terminal"; +import { Server } from "./Server/Server"; +import { Settings } from "./Settings/Settings"; +import { initSourceFiles, SourceFiles } from "./SourceFile"; +import { updateSourceFileFlags } from "./SourceFile/SourceFileFlags"; +import { + SpecialServerIps, + initSpecialServerIps +} from "./Server/SpecialServerIps"; +import { + StockMarket, + StockSymbols, + SymbolToStockMap, + initStockSymbols, + initSymbolToStockMap, + stockMarketCycle, + processStockPrices, + displayStockMarketContent +} from "./StockMarket/StockMarket"; +import { Terminal, postNetburnerText } from "./Terminal"; -import { Sleeve } from "./PersonObjects/Sleeve/Sleeve"; -import { clearSleevesPage, - createSleevesPage, - updateSleevesPage } from "./PersonObjects/Sleeve/SleeveUI"; -import { clearResleevesPage, - createResleevesPage } from "./PersonObjects/Resleeving/ResleevingUI"; +import { Sleeve } from "./PersonObjects/Sleeve/Sleeve"; +import { + clearSleevesPage, + createSleevesPage, + updateSleevesPage +} from "./PersonObjects/Sleeve/SleeveUI"; +import { + clearResleevesPage, + createResleevesPage +} from "./PersonObjects/Resleeving/ResleevingUI"; -import { createStatusText } from "./ui/createStatusText"; -import { displayCharacterInfo } from "./ui/displayCharacterInfo"; -import {Page, routing} from "./ui/navigationTracking"; -import {numeralWrapper} from "./ui/numeralFormat"; -import {setSettingsLabels} from "./ui/setSettingsLabels"; -import { initializeMainMenuHeaders } from "./ui/MainMenu/Headers"; -import { initializeMainMenuLinks, - MainMenuLinks } from "./ui/MainMenu/Links"; +import { createStatusText } from "./ui/createStatusText"; +import { displayCharacterInfo } from "./ui/displayCharacterInfo"; +import { Page, routing } from "./ui/navigationTracking"; +import { numeralWrapper } from "./ui/numeralFormat"; +import { setSettingsLabels } from "./ui/setSettingsLabels"; +import { initializeMainMenuHeaders } from "./ui/MainMenu/Headers"; +import { initializeMainMenuLinks, MainMenuLinks } from "./ui/MainMenu/Links"; +import { dialogBoxCreate } from "../utils/DialogBox"; +import { gameOptionsBoxClose, gameOptionsBoxOpen } from "../utils/GameOptions"; +import { getRandomInt } from "../utils/helpers/getRandomInt"; +import { removeChildrenFromElement } from "../utils/uiHelpers/removeChildrenFromElement"; +import { clearEventListeners } from "../utils/uiHelpers/clearEventListeners"; +import { createElement } from "../utils/uiHelpers/createElement"; +import { exceptionAlert } from "../utils/helpers/exceptionAlert"; +import { removeLoadingScreen } from "../utils/uiHelpers/removeLoadingScreen"; +import { KEY } from "../utils/helpers/keyCodes"; -import { dialogBoxCreate} from "../utils/DialogBox"; -import { gameOptionsBoxClose, - gameOptionsBoxOpen } from "../utils/GameOptions"; -import { getRandomInt } from "../utils/helpers/getRandomInt"; -import { removeChildrenFromElement } from "../utils/uiHelpers/removeChildrenFromElement"; -import { clearEventListeners } from "../utils/uiHelpers/clearEventListeners"; -import { createElement } from "../utils/uiHelpers/createElement"; -import { exceptionAlert } from "../utils/helpers/exceptionAlert"; -import { removeLoadingScreen } from "../utils/uiHelpers/removeLoadingScreen"; -import {KEY} from "../utils/helpers/keyCodes"; +import React from "react"; +import ReactDOM from "react-dom"; -import React from "react"; -import ReactDOM from "react-dom"; // These should really be imported with the module that is presenting that UI, but because they very much depend on the // cascade order, we'll pull them all in here. From 221b81d80205da3291dff8518e6eb54c557d8559 Mon Sep 17 00:00:00 2001 From: danielyxie Date: Fri, 12 Apr 2019 18:22:46 -0700 Subject: [PATCH 2/6] Fixed comment styling for all top-level src files --- src/ActiveScriptsUI.js | 60 ++-- src/Alias.ts | 10 +- src/Bladeburner.js | 559 ++++++++++++++++++--------------- src/CinematicText.js | 8 +- src/CodingContractGenerator.js | 6 +- src/Constants.ts | 192 +++++------ src/DevMenu.jsx | 68 ++-- src/Gang.js | 88 +++--- src/Infiltration.js | 78 ++--- src/InteractiveTutorial.js | 112 +++---- src/Literature.js | 21 +- src/Missions.js | 297 +++++++++--------- src/NetscriptFunctions.js | 129 ++++---- src/Player.js | 2 +- src/Prestige.js | 68 ++-- src/RedPill.js | 34 +- src/SaveObject.js | 47 ++- src/SourceFile.js | 5 +- src/Terminal.js | 152 +++++---- src/engine.jsx | 276 ++++++++-------- 20 files changed, 1149 insertions(+), 1063 deletions(-) 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}: - - - - - - - -)); + + SF-{i}: + + + + + + + + )); @@ -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 = { `
[${Player.getCurrentServer().hostname} ~${dir}]$
` + '",v.noCloneChecked=!!e.cloneNode(!0).lastChild.defaultValue}();var we=s.documentElement,xe=/^key/,Ce=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,ke=/^([^.]*)(?:\.(.+)|)/;function Ae(){return!0}function Ee(){return!1}function _e(){try{return s.activeElement}catch(e){}}function Se(e,t,n,r,i,o){var s,a;if("object"==typeof t){for(a in"string"!=typeof n&&(r=r||n,n=void 0),t)Se(e,a,n,r,t[a],o);return e}if(null==r&&null==i?(i=n,r=n=void 0):null==i&&("string"==typeof n?(i=r,r=void 0):(i=r,r=n,n=void 0)),!1===i)i=Ee;else if(!i)return e;return 1===o&&(s=i,(i=function(e){return k().off(e),s.apply(this,arguments)}).guid=s.guid||(s.guid=k.guid++)),e.each(function(){k.event.add(this,t,i,r,n)})}k.event={global:{},add:function(e,t,n,r,i){var o,s,a,l,u,c,h,d,f,p,g,m=J.get(e);if(m)for(n.handler&&(n=(o=n).handler,i=o.selector),i&&k.find.matchesSelector(we,i),n.guid||(n.guid=k.guid++),(l=m.events)||(l=m.events={}),(s=m.handle)||(s=m.handle=function(t){return void 0!==k&&k.event.triggered!==t.type?k.event.dispatch.apply(e,arguments):void 0}),u=(t=(t||"").match(I)||[""]).length;u--;)f=g=(a=ke.exec(t[u])||[])[1],p=(a[2]||"").split(".").sort(),f&&(h=k.event.special[f]||{},f=(i?h.delegateType:h.bindType)||f,h=k.event.special[f]||{},c=k.extend({type:f,origType:g,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&k.expr.match.needsContext.test(i),namespace:p.join(".")},o),(d=l[f])||((d=l[f]=[]).delegateCount=0,h.setup&&!1!==h.setup.call(e,r,p,s)||e.addEventListener&&e.addEventListener(f,s)),h.add&&(h.add.call(e,c),c.handler.guid||(c.handler.guid=n.guid)),i?d.splice(d.delegateCount++,0,c):d.push(c),k.event.global[f]=!0)},remove:function(e,t,n,r,i){var o,s,a,l,u,c,h,d,f,p,g,m=J.hasData(e)&&J.get(e);if(m&&(l=m.events)){for(u=(t=(t||"").match(I)||[""]).length;u--;)if(f=g=(a=ke.exec(t[u])||[])[1],p=(a[2]||"").split(".").sort(),f){for(h=k.event.special[f]||{},d=l[f=(r?h.delegateType:h.bindType)||f]||[],a=a[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),s=o=d.length;o--;)c=d[o],!i&&g!==c.origType||n&&n.guid!==c.guid||a&&!a.test(c.namespace)||r&&r!==c.selector&&("**"!==r||!c.selector)||(d.splice(o,1),c.selector&&d.delegateCount--,h.remove&&h.remove.call(e,c));s&&!d.length&&(h.teardown&&!1!==h.teardown.call(e,p,m.handle)||k.removeEvent(e,f,m.handle),delete l[f])}else for(f in l)k.event.remove(e,f+t[u],n,r,!0);k.isEmptyObject(l)&&J.remove(e,"handle events")}},dispatch:function(e){var t,n,r,i,o,s,a=k.event.fix(e),l=new Array(arguments.length),u=(J.get(this,"events")||{})[a.type]||[],c=k.event.special[a.type]||{};for(l[0]=a,t=1;t=1))for(;u!==this;u=u.parentNode||this)if(1===u.nodeType&&("click"!==e.type||!0!==u.disabled)){for(o=[],s={},n=0;n-1:k.find(i,this,null,[u]).length),s[i]&&o.push(r);o.length&&a.push({elem:u,handlers:o})}return u=this,l\x20\t\r\n\f]*)[^>]*)\/>/gi,De=/\s*$/g;function Le(e,t){return T(e,"table")&&T(11!==t.nodeType?t:t.firstChild,"tr")&&k(e).children("tbody")[0]||e}function Me(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function Pe(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Oe(e,t){var n,r,i,o,s,a,l,u;if(1===t.nodeType){if(J.hasData(e)&&(o=J.access(e),s=J.set(t,o),u=o.events))for(i in delete s.handle,s.events={},u)for(n=0,r=u[i].length;n1&&"string"==typeof p&&!v.checkClone&&Te.test(p))return e.each(function(i){var o=e.eq(i);g&&(t[0]=p.call(this,i,o.html())),je(o,t,n,r)});if(d&&(o=(i=be(t,e[0].ownerDocument,!1,e,r)).firstChild,1===i.childNodes.length&&(i=o),o||r)){for(a=(s=k.map(me(i,"script"),Me)).length;h")},clone:function(e,t,n){var r,i,o,s,a=e.cloneNode(!0),l=k.contains(e.ownerDocument,e);if(!(v.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||k.isXMLDoc(e)))for(s=me(a),r=0,i=(o=me(e)).length;r0&&ve(s,!l&&me(e,"script")),a},cleanData:function(e){for(var t,n,r,i=k.event.special,o=0;void 0!==(n=e[o]);o++)if(X(n)){if(t=n[J.expando]){if(t.events)for(r in t.events)i[r]?k.event.remove(n,r):k.removeEvent(n,r,t.handle);n[J.expando]=void 0}n[Q.expando]&&(n[Q.expando]=void 0)}}}),k.fn.extend({detach:function(e){return Ie(this,e,!0)},remove:function(e){return Ie(this,e)},text:function(e){return V(this,function(e){return void 0===e?k.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=e)})},null,e,arguments.length)},append:function(){return je(this,arguments,function(e){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||Le(this,e).appendChild(e)})},prepend:function(){return je(this,arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Le(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return je(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return je(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},empty:function(){for(var e,t=0;null!=(e=this[t]);t++)1===e.nodeType&&(k.cleanData(me(e,!1)),e.textContent="");return this},clone:function(e,t){return e=null!=e&&e,t=null==t?e:t,this.map(function(){return k.clone(this,e,t)})},html:function(e){return V(this,function(e){var t=this[0]||{},n=0,r=this.length;if(void 0===e&&1===t.nodeType)return t.innerHTML;if("string"==typeof e&&!De.test(e)&&!ge[(fe.exec(e)||["",""])[1].toLowerCase()]){e=k.htmlPrefilter(e);try{for(;n=0&&(l+=Math.max(0,Math.ceil(e["offset"+t[0].toUpperCase()+t.slice(1)]-o-l-a-.5))),l}function Qe(e,t,n){var r=$e(e),i=ze(e,t,r),o="border-box"===k.css(e,"boxSizing",!1,r),s=o;if(Ne.test(i)){if(!n)return i;i="auto"}return s=s&&(v.boxSizingReliable()||i===e.style[t]),("auto"===i||!parseFloat(i)&&"inline"===k.css(e,"display",!1,r))&&(i=e["offset"+t[0].toUpperCase()+t.slice(1)],s=!0),(i=parseFloat(i)||0)+Je(e,t,n||(o?"border":"content"),s,r,i)+"px"}function et(e,t,n,r,i){return new et.prototype.init(e,t,n,r,i)}k.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=ze(e,"opacity");return""===n?"1":n}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{},style:function(e,t,n,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var i,o,s,a=Y(t),l=Ve.test(t),u=e.style;if(l||(t=Xe(a)),s=k.cssHooks[t]||k.cssHooks[a],void 0===n)return s&&"get"in s&&void 0!==(i=s.get(e,!1,r))?i:u[t];"string"===(o=typeof n)&&(i=ie.exec(n))&&i[1]&&(n=le(e,t,i),o="number"),null!=n&&n==n&&("number"===o&&(n+=i&&i[3]||(k.cssNumber[a]?"":"px")),v.clearCloneStyle||""!==n||0!==t.indexOf("background")||(u[t]="inherit"),s&&"set"in s&&void 0===(n=s.set(e,n,r))||(l?u.setProperty(t,n):u[t]=n))}},css:function(e,t,n,r){var i,o,s,a=Y(t);return Ve.test(t)||(t=Xe(a)),(s=k.cssHooks[t]||k.cssHooks[a])&&"get"in s&&(i=s.get(e,!0,n)),void 0===i&&(i=ze(e,t,r)),"normal"===i&&t in Ke&&(i=Ke[t]),""===n||n?(o=parseFloat(i),!0===n||isFinite(o)?o||0:i):i}}),k.each(["height","width"],function(e,t){k.cssHooks[t]={get:function(e,n,r){if(n)return!Ue.test(k.css(e,"display"))||e.getClientRects().length&&e.getBoundingClientRect().width?Qe(e,t,r):ae(e,Ge,function(){return Qe(e,t,r)})},set:function(e,n,r){var i,o=$e(e),s="border-box"===k.css(e,"boxSizing",!1,o),a=r&&Je(e,t,r,s,o);return s&&v.scrollboxSize()===o.position&&(a-=Math.ceil(e["offset"+t[0].toUpperCase()+t.slice(1)]-parseFloat(o[t])-Je(e,t,"border",!1,o)-.5)),a&&(i=ie.exec(n))&&"px"!==(i[3]||"px")&&(e.style[t]=n,n=k.css(e,t)),Ze(0,n,a)}}}),k.cssHooks.marginLeft=He(v.reliableMarginLeft,function(e,t){if(t)return(parseFloat(ze(e,"marginLeft"))||e.getBoundingClientRect().left-ae(e,{marginLeft:0},function(){return e.getBoundingClientRect().left}))+"px"}),k.each({margin:"",padding:"",border:"Width"},function(e,t){k.cssHooks[e+t]={expand:function(n){for(var r=0,i={},o="string"==typeof n?n.split(" "):[n];r<4;r++)i[e+oe[r]+t]=o[r]||o[r-2]||o[0];return i}},"margin"!==e&&(k.cssHooks[e+t].set=Ze)}),k.fn.extend({css:function(e,t){return V(this,function(e,t,n){var r,i,o={},s=0;if(Array.isArray(t)){for(r=$e(e),i=t.length;s1)}}),k.Tween=et,et.prototype={constructor:et,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||k.easing._default,this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(k.cssNumber[n]?"":"px")},cur:function(){var e=et.propHooks[this.prop];return e&&e.get?e.get(this):et.propHooks._default.get(this)},run:function(e){var t,n=et.propHooks[this.prop];return this.options.duration?this.pos=t=k.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):et.propHooks._default.set(this),this}},et.prototype.init.prototype=et.prototype,et.propHooks={_default:{get:function(e){var t;return 1!==e.elem.nodeType||null!=e.elem[e.prop]&&null==e.elem.style[e.prop]?e.elem[e.prop]:(t=k.css(e.elem,e.prop,""))&&"auto"!==t?t:0},set:function(e){k.fx.step[e.prop]?k.fx.step[e.prop](e):1!==e.elem.nodeType||null==e.elem.style[k.cssProps[e.prop]]&&!k.cssHooks[e.prop]?e.elem[e.prop]=e.now:k.style(e.elem,e.prop,e.now+e.unit)}}},et.propHooks.scrollTop=et.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},k.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2},_default:"swing"},k.fx=et.prototype.init,k.fx.step={};var tt,nt,rt=/^(?:toggle|show|hide)$/,it=/queueHooks$/;function ot(){nt&&(!1===s.hidden&&n.requestAnimationFrame?n.requestAnimationFrame(ot):n.setTimeout(ot,k.fx.interval),k.fx.tick())}function st(){return n.setTimeout(function(){tt=void 0}),tt=Date.now()}function at(e,t){var n,r=0,i={height:e};for(t=t?1:0;r<4;r+=2-t)i["margin"+(n=oe[r])]=i["padding"+n]=e;return t&&(i.opacity=i.width=e),i}function lt(e,t,n){for(var r,i=(ut.tweeners[t]||[]).concat(ut.tweeners["*"]),o=0,s=i.length;o1)},removeAttr:function(e){return this.each(function(){k.removeAttr(this,e)})}}),k.extend({attr:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return void 0===e.getAttribute?k.prop(e,t,n):(1===o&&k.isXMLDoc(e)||(i=k.attrHooks[t.toLowerCase()]||(k.expr.match.bool.test(t)?ct:void 0)),void 0!==n?null===n?void k.removeAttr(e,t):i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:(e.setAttribute(t,n+""),n):i&&"get"in i&&null!==(r=i.get(e,t))?r:null==(r=k.find.attr(e,t))?void 0:r)},attrHooks:{type:{set:function(e,t){if(!v.radioValue&&"radio"===t&&T(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},removeAttr:function(e,t){var n,r=0,i=t&&t.match(I);if(i&&1===e.nodeType)for(;n=i[r++];)e.removeAttribute(n)}}),ct={set:function(e,t,n){return!1===t?k.removeAttr(e,n):e.setAttribute(n,n),n}},k.each(k.expr.match.bool.source.match(/\w+/g),function(e,t){var n=ht[t]||k.find.attr;ht[t]=function(e,t,r){var i,o,s=t.toLowerCase();return r||(o=ht[s],ht[s]=i,i=null!=n(e,t,r)?s:null,ht[s]=o),i}});var dt=/^(?:input|select|textarea|button)$/i,ft=/^(?:a|area)$/i;function pt(e){return(e.match(I)||[]).join(" ")}function gt(e){return e.getAttribute&&e.getAttribute("class")||""}function mt(e){return Array.isArray(e)?e:"string"==typeof e&&e.match(I)||[]}k.fn.extend({prop:function(e,t){return V(this,k.prop,e,t,arguments.length>1)},removeProp:function(e){return this.each(function(){delete this[k.propFix[e]||e]})}}),k.extend({prop:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return 1===o&&k.isXMLDoc(e)||(t=k.propFix[t]||t,i=k.propHooks[t]),void 0!==n?i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){var t=k.find.attr(e,"tabindex");return t?parseInt(t,10):dt.test(e.nodeName)||ft.test(e.nodeName)&&e.href?0:-1}}},propFix:{for:"htmlFor",class:"className"}}),v.optSelected||(k.propHooks.selected={get:function(e){var t=e.parentNode;return t&&t.parentNode&&t.parentNode.selectedIndex,null},set:function(e){var t=e.parentNode;t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex)}}),k.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){k.propFix[this.toLowerCase()]=this}),k.fn.extend({addClass:function(e){var t,n,r,i,o,s,a,l=0;if(y(e))return this.each(function(t){k(this).addClass(e.call(this,t,gt(this)))});if((t=mt(e)).length)for(;n=this[l++];)if(i=gt(n),r=1===n.nodeType&&" "+pt(i)+" "){for(s=0;o=t[s++];)r.indexOf(" "+o+" ")<0&&(r+=o+" ");i!==(a=pt(r))&&n.setAttribute("class",a)}return this},removeClass:function(e){var t,n,r,i,o,s,a,l=0;if(y(e))return this.each(function(t){k(this).removeClass(e.call(this,t,gt(this)))});if(!arguments.length)return this.attr("class","");if((t=mt(e)).length)for(;n=this[l++];)if(i=gt(n),r=1===n.nodeType&&" "+pt(i)+" "){for(s=0;o=t[s++];)for(;r.indexOf(" "+o+" ")>-1;)r=r.replace(" "+o+" "," ");i!==(a=pt(r))&&n.setAttribute("class",a)}return this},toggleClass:function(e,t){var n=typeof e,r="string"===n||Array.isArray(e);return"boolean"==typeof t&&r?t?this.addClass(e):this.removeClass(e):y(e)?this.each(function(n){k(this).toggleClass(e.call(this,n,gt(this),t),t)}):this.each(function(){var t,i,o,s;if(r)for(i=0,o=k(this),s=mt(e);t=s[i++];)o.hasClass(t)?o.removeClass(t):o.addClass(t);else void 0!==e&&"boolean"!==n||((t=gt(this))&&J.set(this,"__className__",t),this.setAttribute&&this.setAttribute("class",t||!1===e?"":J.get(this,"__className__")||""))})},hasClass:function(e){var t,n,r=0;for(t=" "+e+" ";n=this[r++];)if(1===n.nodeType&&(" "+pt(gt(n))+" ").indexOf(t)>-1)return!0;return!1}});var vt=/\r/g;k.fn.extend({val:function(e){var t,n,r,i=this[0];return arguments.length?(r=y(e),this.each(function(n){var i;1===this.nodeType&&(null==(i=r?e.call(this,n,k(this).val()):e)?i="":"number"==typeof i?i+="":Array.isArray(i)&&(i=k.map(i,function(e){return null==e?"":e+""})),(t=k.valHooks[this.type]||k.valHooks[this.nodeName.toLowerCase()])&&"set"in t&&void 0!==t.set(this,i,"value")||(this.value=i))})):i?(t=k.valHooks[i.type]||k.valHooks[i.nodeName.toLowerCase()])&&"get"in t&&void 0!==(n=t.get(i,"value"))?n:"string"==typeof(n=i.value)?n.replace(vt,""):null==n?"":n:void 0}}),k.extend({valHooks:{option:{get:function(e){var t=k.find.attr(e,"value");return null!=t?t:pt(k.text(e))}},select:{get:function(e){var t,n,r,i=e.options,o=e.selectedIndex,s="select-one"===e.type,a=s?null:[],l=s?o+1:i.length;for(r=o<0?l:s?o:0;r-1)&&(n=!0);return n||(e.selectedIndex=-1),o}}}}),k.each(["radio","checkbox"],function(){k.valHooks[this]={set:function(e,t){if(Array.isArray(t))return e.checked=k.inArray(k(e).val(),t)>-1}},v.checkOn||(k.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})}),v.focusin="onfocusin"in n;var yt=/^(?:focusinfocus|focusoutblur)$/,bt=function(e){e.stopPropagation()};k.extend(k.event,{trigger:function(e,t,r,i){var o,a,l,u,c,h,d,f,g=[r||s],m=p.call(e,"type")?e.type:e,v=p.call(e,"namespace")?e.namespace.split("."):[];if(a=f=l=r=r||s,3!==r.nodeType&&8!==r.nodeType&&!yt.test(m+k.event.triggered)&&(m.indexOf(".")>-1&&(m=(v=m.split(".")).shift(),v.sort()),c=m.indexOf(":")<0&&"on"+m,(e=e[k.expando]?e:new k.Event(m,"object"==typeof e&&e)).isTrigger=i?2:3,e.namespace=v.join("."),e.rnamespace=e.namespace?new RegExp("(^|\\.)"+v.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,e.result=void 0,e.target||(e.target=r),t=null==t?[e]:k.makeArray(t,[e]),d=k.event.special[m]||{},i||!d.trigger||!1!==d.trigger.apply(r,t))){if(!i&&!d.noBubble&&!b(r)){for(u=d.delegateType||m,yt.test(u+m)||(a=a.parentNode);a;a=a.parentNode)g.push(a),l=a;l===(r.ownerDocument||s)&&g.push(l.defaultView||l.parentWindow||n)}for(o=0;(a=g[o++])&&!e.isPropagationStopped();)f=a,e.type=o>1?u:d.bindType||m,(h=(J.get(a,"events")||{})[e.type]&&J.get(a,"handle"))&&h.apply(a,t),(h=c&&a[c])&&h.apply&&X(a)&&(e.result=h.apply(a,t),!1===e.result&&e.preventDefault());return e.type=m,i||e.isDefaultPrevented()||d._default&&!1!==d._default.apply(g.pop(),t)||!X(r)||c&&y(r[m])&&!b(r)&&((l=r[c])&&(r[c]=null),k.event.triggered=m,e.isPropagationStopped()&&f.addEventListener(m,bt),r[m](),e.isPropagationStopped()&&f.removeEventListener(m,bt),k.event.triggered=void 0,l&&(r[c]=l)),e.result}},simulate:function(e,t,n){var r=k.extend(new k.Event,n,{type:e,isSimulated:!0});k.event.trigger(r,null,t)}}),k.fn.extend({trigger:function(e,t){return this.each(function(){k.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];if(n)return k.event.trigger(e,t,n,!0)}}),v.focusin||k.each({focus:"focusin",blur:"focusout"},function(e,t){var n=function(e){k.event.simulate(t,e.target,k.event.fix(e))};k.event.special[t]={setup:function(){var r=this.ownerDocument||this,i=J.access(r,t);i||r.addEventListener(e,n,!0),J.access(r,t,(i||0)+1)},teardown:function(){var r=this.ownerDocument||this,i=J.access(r,t)-1;i?J.access(r,t,i):(r.removeEventListener(e,n,!0),J.remove(r,t))}}});var wt=n.location,xt=Date.now(),Ct=/\?/;k.parseXML=function(e){var t;if(!e||"string"!=typeof e)return null;try{t=(new n.DOMParser).parseFromString(e,"text/xml")}catch(e){t=void 0}return t&&!t.getElementsByTagName("parsererror").length||k.error("Invalid XML: "+e),t};var kt=/\[\]$/,At=/\r?\n/g,Et=/^(?:submit|button|image|reset|file)$/i,_t=/^(?:input|select|textarea|keygen)/i;function St(e,t,n,r){var i;if(Array.isArray(t))k.each(t,function(t,i){n||kt.test(e)?r(e,i):St(e+"["+("object"==typeof i&&null!=i?t:"")+"]",i,n,r)});else if(n||"object"!==C(t))r(e,t);else for(i in t)St(e+"["+i+"]",t[i],n,r)}k.param=function(e,t){var n,r=[],i=function(e,t){var n=y(t)?t():t;r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(null==n?"":n)};if(Array.isArray(e)||e.jquery&&!k.isPlainObject(e))k.each(e,function(){i(this.name,this.value)});else for(n in e)St(n,e[n],t,i);return r.join("&")},k.fn.extend({serialize:function(){return k.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=k.prop(this,"elements");return e?k.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!k(this).is(":disabled")&&_t.test(this.nodeName)&&!Et.test(e)&&(this.checked||!de.test(e))}).map(function(e,t){var n=k(this).val();return null==n?null:Array.isArray(n)?k.map(n,function(e){return{name:t.name,value:e.replace(At,"\r\n")}}):{name:t.name,value:n.replace(At,"\r\n")}}).get()}});var Ft=/%20/g,Dt=/#.*$/,Tt=/([?&])_=[^&]*/,Bt=/^(.*?):[ \t]*([^\r\n]*)$/gm,Lt=/^(?:GET|HEAD)$/,Mt=/^\/\//,Pt={},Ot={},Rt="*/".concat("*"),jt=s.createElement("a");function It(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(I)||[];if(y(n))for(;r=o[i++];)"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function Nt(e,t,n,r){var i={},o=e===Ot;function s(a){var l;return i[a]=!0,k.each(e[a]||[],function(e,a){var u=a(t,n,r);return"string"!=typeof u||o||i[u]?o?!(l=u):void 0:(t.dataTypes.unshift(u),s(u),!1)}),l}return s(t.dataTypes[0])||!i["*"]&&s("*")}function $t(e,t){var n,r,i=k.ajaxSettings.flatOptions||{};for(n in t)void 0!==t[n]&&((i[n]?e:r||(r={}))[n]=t[n]);return r&&k.extend(!0,e,r),e}jt.href=wt.href,k.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:wt.href,type:"GET",isLocal:/^(?:about|app|app-storage|.+-extension|file|res|widget):$/.test(wt.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Rt,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":JSON.parse,"text xml":k.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?$t($t(e,k.ajaxSettings),t):$t(k.ajaxSettings,e)},ajaxPrefilter:It(Pt),ajaxTransport:It(Ot),ajax:function(e,t){"object"==typeof e&&(t=e,e=void 0),t=t||{};var r,i,o,a,l,u,c,h,d,f,p=k.ajaxSetup({},t),g=p.context||p,m=p.context&&(g.nodeType||g.jquery)?k(g):k.event,v=k.Deferred(),y=k.Callbacks("once memory"),b=p.statusCode||{},w={},x={},C="canceled",A={readyState:0,getResponseHeader:function(e){var t;if(c){if(!a)for(a={};t=Bt.exec(o);)a[t[1].toLowerCase()]=t[2];t=a[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return c?o:null},setRequestHeader:function(e,t){return null==c&&(e=x[e.toLowerCase()]=x[e.toLowerCase()]||e,w[e]=t),this},overrideMimeType:function(e){return null==c&&(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(c)A.always(e[A.status]);else for(t in e)b[t]=[b[t],e[t]];return this},abort:function(e){var t=e||C;return r&&r.abort(t),E(0,t),this}};if(v.promise(A),p.url=((e||p.url||wt.href)+"").replace(Mt,wt.protocol+"//"),p.type=t.method||t.type||p.method||p.type,p.dataTypes=(p.dataType||"*").toLowerCase().match(I)||[""],null==p.crossDomain){u=s.createElement("a");try{u.href=p.url,u.href=u.href,p.crossDomain=jt.protocol+"//"+jt.host!=u.protocol+"//"+u.host}catch(e){p.crossDomain=!0}}if(p.data&&p.processData&&"string"!=typeof p.data&&(p.data=k.param(p.data,p.traditional)),Nt(Pt,p,t,A),c)return A;for(d in(h=k.event&&p.global)&&0==k.active++&&k.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!Lt.test(p.type),i=p.url.replace(Dt,""),p.hasContent?p.data&&p.processData&&0===(p.contentType||"").indexOf("application/x-www-form-urlencoded")&&(p.data=p.data.replace(Ft,"+")):(f=p.url.slice(i.length),p.data&&(p.processData||"string"==typeof p.data)&&(i+=(Ct.test(i)?"&":"?")+p.data,delete p.data),!1===p.cache&&(i=i.replace(Tt,"$1"),f=(Ct.test(i)?"&":"?")+"_="+xt+++f),p.url=i+f),p.ifModified&&(k.lastModified[i]&&A.setRequestHeader("If-Modified-Since",k.lastModified[i]),k.etag[i]&&A.setRequestHeader("If-None-Match",k.etag[i])),(p.data&&p.hasContent&&!1!==p.contentType||t.contentType)&&A.setRequestHeader("Content-Type",p.contentType),A.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+Rt+"; q=0.01":""):p.accepts["*"]),p.headers)A.setRequestHeader(d,p.headers[d]);if(p.beforeSend&&(!1===p.beforeSend.call(g,A,p)||c))return A.abort();if(C="abort",y.add(p.complete),A.done(p.success),A.fail(p.error),r=Nt(Ot,p,t,A)){if(A.readyState=1,h&&m.trigger("ajaxSend",[A,p]),c)return A;p.async&&p.timeout>0&&(l=n.setTimeout(function(){A.abort("timeout")},p.timeout));try{c=!1,r.send(w,E)}catch(e){if(c)throw e;E(-1,e)}}else E(-1,"No Transport");function E(e,t,s,a){var u,d,f,w,x,C=t;c||(c=!0,l&&n.clearTimeout(l),r=void 0,o=a||"",A.readyState=e>0?4:0,u=e>=200&&e<300||304===e,s&&(w=function(e,t,n){for(var r,i,o,s,a=e.contents,l=e.dataTypes;"*"===l[0];)l.shift(),void 0===r&&(r=e.mimeType||t.getResponseHeader("Content-Type"));if(r)for(i in a)if(a[i]&&a[i].test(r)){l.unshift(i);break}if(l[0]in n)o=l[0];else{for(i in n){if(!l[0]||e.converters[i+" "+l[0]]){o=i;break}s||(s=i)}o=o||s}if(o)return o!==l[0]&&l.unshift(o),n[o]}(p,A,s)),w=function(e,t,n,r){var i,o,s,a,l,u={},c=e.dataTypes.slice();if(c[1])for(s in e.converters)u[s.toLowerCase()]=e.converters[s];for(o=c.shift();o;)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!l&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),l=o,o=c.shift())if("*"===o)o=l;else if("*"!==l&&l!==o){if(!(s=u[l+" "+o]||u["* "+o]))for(i in u)if((a=i.split(" "))[1]===o&&(s=u[l+" "+a[0]]||u["* "+a[0]])){!0===s?s=u[i]:!0!==u[i]&&(o=a[0],c.unshift(a[1]));break}if(!0!==s)if(s&&e.throws)t=s(t);else try{t=s(t)}catch(e){return{state:"parsererror",error:s?e:"No conversion from "+l+" to "+o}}}return{state:"success",data:t}}(p,w,A,u),u?(p.ifModified&&((x=A.getResponseHeader("Last-Modified"))&&(k.lastModified[i]=x),(x=A.getResponseHeader("etag"))&&(k.etag[i]=x)),204===e||"HEAD"===p.type?C="nocontent":304===e?C="notmodified":(C=w.state,d=w.data,u=!(f=w.error))):(f=C,!e&&C||(C="error",e<0&&(e=0))),A.status=e,A.statusText=(t||C)+"",u?v.resolveWith(g,[d,C,A]):v.rejectWith(g,[A,C,f]),A.statusCode(b),b=void 0,h&&m.trigger(u?"ajaxSuccess":"ajaxError",[A,p,u?d:f]),y.fireWith(g,[A,C]),h&&(m.trigger("ajaxComplete",[A,p]),--k.active||k.event.trigger("ajaxStop")))}return A},getJSON:function(e,t,n){return k.get(e,t,n,"json")},getScript:function(e,t){return k.get(e,void 0,t,"script")}}),k.each(["get","post"],function(e,t){k[t]=function(e,n,r,i){return y(n)&&(i=i||r,r=n,n=void 0),k.ajax(k.extend({url:e,type:t,dataType:i,data:n,success:r},k.isPlainObject(e)&&e))}}),k._evalUrl=function(e){return k.ajax({url:e,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,throws:!0})},k.fn.extend({wrapAll:function(e){var t;return this[0]&&(y(e)&&(e=e.call(this[0])),t=k(e,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){for(var e=this;e.firstElementChild;)e=e.firstElementChild;return e}).append(this)),this},wrapInner:function(e){return y(e)?this.each(function(t){k(this).wrapInner(e.call(this,t))}):this.each(function(){var t=k(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=y(e);return this.each(function(n){k(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(e){return this.parent(e).not("body").each(function(){k(this).replaceWith(this.childNodes)}),this}}),k.expr.pseudos.hidden=function(e){return!k.expr.pseudos.visible(e)},k.expr.pseudos.visible=function(e){return!!(e.offsetWidth||e.offsetHeight||e.getClientRects().length)},k.ajaxSettings.xhr=function(){try{return new n.XMLHttpRequest}catch(e){}};var Wt={0:200,1223:204},zt=k.ajaxSettings.xhr();v.cors=!!zt&&"withCredentials"in zt,v.ajax=zt=!!zt,k.ajaxTransport(function(e){var t,r;if(v.cors||zt&&!e.crossDomain)return{send:function(i,o){var s,a=e.xhr();if(a.open(e.type,e.url,e.async,e.username,e.password),e.xhrFields)for(s in e.xhrFields)a[s]=e.xhrFields[s];for(s in e.mimeType&&a.overrideMimeType&&a.overrideMimeType(e.mimeType),e.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest"),i)a.setRequestHeader(s,i[s]);t=function(e){return function(){t&&(t=r=a.onload=a.onerror=a.onabort=a.ontimeout=a.onreadystatechange=null,"abort"===e?a.abort():"error"===e?"number"!=typeof a.status?o(0,"error"):o(a.status,a.statusText):o(Wt[a.status]||a.status,a.statusText,"text"!==(a.responseType||"text")||"string"!=typeof a.responseText?{binary:a.response}:{text:a.responseText},a.getAllResponseHeaders()))}},a.onload=t(),r=a.onerror=a.ontimeout=t("error"),void 0!==a.onabort?a.onabort=r:a.onreadystatechange=function(){4===a.readyState&&n.setTimeout(function(){t&&r()})},t=t("abort");try{a.send(e.hasContent&&e.data||null)}catch(e){if(t)throw e}},abort:function(){t&&t()}}}),k.ajaxPrefilter(function(e){e.crossDomain&&(e.contents.script=!1)}),k.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(e){return k.globalEval(e),e}}}),k.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET")}),k.ajaxTransport("script",function(e){var t,n;if(e.crossDomain)return{send:function(r,i){t=k("